list as member in a class - c++

I am having some trouble! My goal is to check an input number against a list of prime numbers to see if it is prime (in the list) via the find() function. I haven't gotten that far yet. This is homework so I have to overload the function operator and do it in this dumb (imho) way. Here is what I have thus far:
using namespace std;
class isprime {
public: isprime() { /*nothing...yet?*/
}
bool operator()(int);
list <int> pnums(1, 2);
private: int expandList(int number);
};
bool isprime::operator()(int number) {
if (pnums.back() < number) {}
}
int isprime::expandList(int number) {
for (int j = pnums.back(); j = number; j++) {
for (int i = 2; i < sqrt(j); i++) {
if (j % i != 0) pnums.push_back(j);
}
}
}
int main() {
isprime pcheck;
int number;
while (cin >> number) {
if (pcheck(number)) cout << number << " is prime!\n";
}
}
Here are my errors:
prime2.cpp:12: error: expected identifier before numeric constant
prime2.cpp:12: error: expected ',' or '...' before numeric
constant prime2.cpp: In member function 'bool
isprime::operator()(int)': prime2.cpp:19: error:
'((isprime*)this)->isprime::pnums' does not have class type
prime2.cpp: In member function 'int isprime::expandList(int)':
prime2.cpp:23: error: '((isprime*)this)->isprime::pnums' does not have
class type prime2.cpp:25: error:
'((isprime*)this)->isprime::pnums' does not have class type
I don't understand what is going wrong. Could anyone help me out?

The biggest problem is how you are trying use the constructor for the list in your class. If you simply remove (1, 2) from the list declaration in your class, it should compile. Second, if you want to call the constructor of an object in your class, I recommend this method
class isprime{
public:
isprime() : pnums(1,2) { /*nothing...yet?*/ }
...
list <int> pnums;
...

Related

No instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Enemy *, _Alloc=std::allocator<Enemy *>]" matches the argument list

for (auto enemy : this->enemies)
{
if (enemy->getHP() <= 0)
{
enemies.erase(enemy);
}
}
I have a vector enemies containing multiple of Enemy* elements and i want to erase an enemy if their hp is 0 or below
I write the code above and it gave me this error message:
No instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=Enemy *, _Alloc=std::allocator<Enemy *>]" matches the argument list
argument types are: (Enemy*)
object type is: std::vector<Enemy*,std::allocator<Enemy*>>
I assume that is not the right way to do it, so how?
Im new in stackoverflow and im still learning english so sorry if i made mistakes
EDIT:
It's my almost complete code:
struct enemyType
{
public:
int type;
sf::Vector2f pos;
}
std::vector<std::vector<enemyType>> enemyList = {
{
{ trashMonster, sf::Vector2f(5.f * 16, 18.f * 16) }
}
}
std::vector<Enemy*> enemies;
std::vector<Enemy*>* GetEnemy(int level)
{
for (int i = 0; i < enemyList[level].size(); i++)
{
switch (enemyList[level][i].type)
{
case trashMonster:
n_TrashMonster->setPosition(enemyList[level][i].pos);
enemies.emplace_back(n_TrashMonster);
break;
default:
std::cout << "Error to get an enemy\n";
break;
}
}
return &enemies;
}
//Code in different file
std::vector<Enemy*> enemies;
this->enemies = *GetEnemy(lvl);
for (auto enemy : this->enemies)
{
enemy->update(player->getCollisionBox());
//collision enemies to tilemap
collision::MapCollision(*this->map.getTilesCol(), *enemy);
if (enemy->getHP() <= 0)
{
enemies.erase(enemy);
}
}
Didn't include that because my code is a complete mess so I was afraid people won't get the point of my question and it's my first question here
The std::vector<T>::erase function does not have a erase(T a) overload. And if you want to remove elemennts from a vector you can't iterate over them like that. I suggest a convencional loop.
for (size_t i=0; i<this->enemies.size();++i){
if (this->enemies[i]->getHP()){
std::swap(enemies[i],enemies::back());
delete enemies::back();//Only if you don't free the space elsewere
enemies.pop_back();
}
}
Edit:
This will mess up the order of the vector. If you don't want that you can use erase(enemies.begin()+i) iinstead of swaping it back and removeing it
When using STL containers usually you don't even need an (explicit) for loop. Use std::remove_if like this
#include <vector>
#include <algorithm>
#include <iostream>
class Enemy
{
public:
// not explicit on purpose, so I can initalize vector more quickly (in real code you should have explicit constructors if they have one argument of a different type)
Enemy(int hp) :
m_hp{ hp }
{
};
int getHP() const noexcept
{
return m_hp;
}
int m_hp;
};
int main()
{
// create a test vector with enemies with given hitpoints
std::vector<Enemy> enemies{ 1,2,0,4,5,6,0,7,8 };
// boolean lambda function that determines if an enemy is dead.
auto enemy_is_dead = [](const Enemy& enemy) { return enemy.getHP() <= 0; };
// use remove_if (this will move all the items to be removed to the end
auto remove_from = std::remove_if(enemies.begin(), enemies.end(), enemy_is_dead );
// then shrink the vector
enemies.erase(remove_from, enemies.end());
for (const auto& enemy : enemies)
{
std::cout << enemy.getHP() << " ";
}
return 0;
}

My operator overload isn't returning in my int main?

I'm trying to make a code that adds 2 octal numbers and then converts the sum to decimal using operator overloading. However, whenever I try and use my convert operator($), I get "$num1 was not declared in this scope". can anyone help me?
Note: I know some of the things can be changed for simplicity but it has to be this way because that's the way my teacher wants it. My main problem is calling the operator in the main. Thanks!
#include <iostream>
#include <math.h>
#include <algorithm>//reverse
#include <vector>
using namespace std;
int gnum=0;
class Oct{
private:
int number;//Base 10
vector <int> octnum;//separated out number
public:
Oct();
void input();//input 457
void setNum(int);//sending setNum a base 10 number(457)
void operator+ (Oct);//if(sum>7)sum-8
int operator$ ();//converts sum to base 10
void display();
vector <int> octSum;//vector of added numbers
};
Oct::Oct()
{
number = 0;
octnum.push_back(0);
}
void Oct::input()
{
cout<<"Enter your number: ";
cin>>number;
gnum = number;
}
void Oct::setNum(int num)
{
while(num!=0)
{
octnum.push_back(num%10);
num=num/10;
}
octnum.push_back(0);
if(octnum[0]==0)
{
octnum.erase(octnum.begin());
}
}
void Oct::display()
{
for(int i = 0;i<octSum.size();i++)
{
cout<<octSum[i];
}
cout<<endl;
}
void Oct::operator+ (Oct num2)
{
int carry = 0;
int add = 0;
for(int i = 0;i<octnum.size();i++)
{
add = octnum[i]+num2.octnum[i]+carry;
if(add>7)
{
add=add-8;
carry = 1;
}
else
{
carry = 0;
}
octSum.push_back(add);
}
}
int Oct::operator$ ()
{
for(int i = 0;i<octSum.size();i++)
{
octSum[i]=octSum[i]*int(pow(8,i)+0.5);
}
reverse(octSum.begin(),octSum.end());
int sum = 0;
for(int i = 0;i<octSum.size();i++)
{
sum = sum + octSum[i]*int(pow(10,octSum.size()-1-i)+0.5);
}
return sum;
}
int main()
{
Oct num1,num2;
num1.input();
num1.setNum(gnum);
num2.input();
num2.setNum(gnum);
num1+num2;
int j = $num1;
num1.display();
return(0);
}
$ is not an operator in C++. It is just a character without any specific meaning. Whether it is supported as physical character in the source code is implementation-defined and it is also implementation-defined whether it will be parsed as part of an identifier. If it is parsed as part of an identifier, it will become part of the token, the same way as characters a to z do.
Apparently your compiler is supporting $ as source file character and as character in identifiers and therefore you are not overloading an operator, you are defining a normal member function with the name operator$ and you are referencing an identifier $num1 in main that has not been declared beforehand.
You cannot invent new operators.

Sorting doesn't work with templated class

I have an insertion sort function
void insertionSort(ArrayList<int> myData)
{
for (int i = 1; i < myData.getSize(); i++) {
int index = myData[i];
int j = i;
while (j > 0 && myData[j-1] > index) {
myData.swap(j - 1, j);
j--;
}
myData[j] = index;
}
}
which uses this swap function
template<class TYPE>
void ArrayList<TYPE>::swap(int from, int to) throw(std::out_of_range)
{
int temp = 0;
temp = this->items[from];
this->items[from] = this->items[to];
this->items[to] = temp;
swapNum++;
}
This is how my private methods look like
TYPE * items;
int currentLength;
static int swapNum;
I have an overloaded [] operator and a getSize() function that I think I wrote well and not contributing to my problem. Now if I do this in my main.cpp
ArrayList<int>m_Data(1);
and append say 4,2,9,1 on the m_Data and call
insertionSort(m_Data);
I get two errors
1. Error C2440 '=': cannot convert from 'std::string' to 'int'
on the swap function and
2. The insertion sort doesn't work
First problem: it should be something like TYPE temp = this->items[from]. After repairing it (I used STL swap) function works. Well, it works on STL vector and swap. If you still do have problem, then your array structure is probably invalid.
EDIT: In function 'insertionSort' shouldn't you have template (as in swap function)?

Error in program with structures and pointers (Structures, C++)

I have a structure , which contains three variables under the object list.-Names, registration nos, amount.
struct vendor
{
int reg, amt;
char add[30];
}list[10];
I have made a function to find the minimum amount(amt) ,using the referencing concept.
int low(vendor *p, int n)
{
int i;
min = (p->amt);
for(i =1;i<n;i++)
{
if(min > *(p->amt))
{
min = *(p->amt);
}
p++;
}
return min;
}
In the main I have included the syntax:
low(list, n);
I am getting an error:
Invalid argument of unary '*' operator.
I have tried using the dot operator also and is not working.
This is my first program in pointers in structs with functions.
Can you please point out the error in the code.
Thank You very much
Anupam
(Update) the full code:
#include <iostream>
using namespace std;
struct vendor
{
int reg, amt;
char add[30];
}list[10];
int low(vendor *p, int n)
{
int i;
min = (p->amt);
for(i =1;i<n;i++)
{
if(min > (p->amt))
{
min = (p->amt);
}
p++;
}
return min;
}
int main()
{
int i;
int fa;
int n,fr;
cin >> n;
for(i =0;i<n;i++)
{
cin >>list[i].reg>>list[i].add>>list[i].amt;
// Enter reg no. , address and amount.
}
low(list, n); // Calling function
for(i = 0;i<n;i++)
{
if(fr == list[i].amt)
// This is to check for position of least amount.
// For printing the reg no. and address of least amt.
{
fa = i;
}
}
cout << fr <<"\n" << fa <<endl;
// print the reg no. and address of least amt.
}
Errors:
Overloaded function with no contextual type information.
Invalid operands of types <unresolved overloaded function
Cannot resolve overloaded function
The declaration for min is missing in low() function.
int min = (p->amt);
This should help you compile your code.
p is a pointer to a vendor. *p is a vender. p->amt is an int.
So when you want the amt of an object that is pointed to by p you can do it in one of two ways: p->amt or (*p).amt
You fix your code by using p->amt or (*p).amt. *p->amt or *(p->amt) are invalid.
p is a object of vendor which type is pointer . "->" is used to use pointer object . So use p->amt .
you can also use (*p).amt .
Updated Answer :
decleration of min is missing . please use this :
int min = p->amt ;
or use this :
int min = (*p).amt;

access private member variable through private member, same class

// M9P369.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
const int MaxSize = 100;
using namespace std;
class Set {
int len; // number of members
char members[MaxSize]; // the set is stored in this array
int find(char ch); // find an element
public:
Set() { len = 0; } // constructor to make a null set initially
int getLength() { return len; } // return number of elements in the set
void showset(); // display the set
bool isMember(char ch); // check for membership
Set operator+(char ch); // overload operator to add an element to the set
Set operator-(char ch); // overload operator to remove an element from the set
Set operator+(Set ob2); // set Union - overloaded by the different type from above overload+ function
Set operator-(Set ob2); // set difference same as above.
};
// Return the index of the element passed in, or -1 if nothing found.
int Set::find(char ch) {
int i;
for (i=0; i < len; i++)
if (members.[i] == ch) return i;
return -1;
}
// Show the set
void Set::showset() {
cout << "{ ";
for (int i=0; i<len; i++)
cout << members[i] << " ";
cout << "}\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
I am learning operator overloading, and came across a class access problem.
The line
if (members.[i] == ch) return i;
Gives a tooltip error 'expression must have class type', and compile errors:
\m9p369.cpp(34): error C2059: syntax error : '['
\m9p369.cpp(40): error C2228: left of '.showset' must have class/struct/union
\m9p369.cpp(41): error C2228: left of '.cout' must have class/struct/union
I am defining the private member function find() of class Set, and I get the error upon trying to access the private member char array of the same class, members. Error seems to say I should specify which class it's referring to, why? I already specify the class in the definition:
int Set::find(char ch) {
As I understand, members should be in the scope of the function definition. I looked hard for any stray characters I couldn't find anything odd, all parenthesis seem to match.
Problem is here:
members.[i]
It should be just
members[i]
Remeove the . from
if (members.[i] == ch) return i;
~~~~~~~~~~~^