Hello, I am currently having issues with a program I am working on that uses vectors of objects. I have a class Table that includes a bool isAvailable. Then I have two vectors of Tables, allTables and availableTables. In a function, I determine which tables are available using the isAvailable variable. My problem is that when I try to run this statement "availableTables.push_back(it)" my program gives this error:
"Error 1 error C2664: 'void std::vector<Table,std::allocator<_Ty>>::push_back(const Table &)' : cannot convert argument 1 from std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Table>>>' to 'Table &&'"
My question is: If the method I am currently using does not work, what should I be using instead? If my method should work, what am I doing wrong? Basically, how do I get this function to work?
Parts of code:
Table class:
class Table {
public:
vector<Food> orders;
int tablenum;
bool isAvailable;
Table(int tn);
void cook();
};
Vectors:
vector<Table> allTables;
vector<Table> availableTables;
Function:
void availableTable() {
vector<Table>::iterator it;
for (it = allTables.begin(); it < allTables.end(); ++it) {
if (it->isAvailable == true)
availableTables.push_back(it);
}
}
Any help would be appreciated. Thanks in advance!
Yay295 is right. When you use an iterator you have to dereference what it is pointing at. It's like passing by reference/ memory, where you need a pointer to look at what is inside the memory address you are referencing.
So I tried doing this:
it = availableTables.begin();
++it;
return *it;
in a function to return the first available table, but I get an error saying the iterator is not dereferencable. What do I do in this situation if I cannot dereference it?
I fixed it! The issue was that I was checking for the bool isAvailable in each Table object, but I had never declared that bool, so it defaulted to false. My solution was simply to change the class constructor to include the bool. Basically the iterator was pointing to the beginning of availableTables, which was null, so it was not dereferencable because there was nothing there.