Object Vector Issues

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!
You need to dereference 'it'.
availableTables.push_back(*it);
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.
Last edited on
Ok thanks!
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?
Last edited on
What is the function supposed to return?
return it; @pi Lord
Yay295 the function is supposed to return a Table object, and Little Bobby Tables that gives an error because it is not a Table object.
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.
Do you want to display how many tables are available? If so, you use the typical for loop for an iterator:
1
2
for (it=availableTables.begin(); it!=availableTables.end(); it++)
cout<<*it;
No I just want to be able to access the first available one. Thanks everyone for the help!
Topic archived. No new replies allowed.