Is this possible to store a structure in vector? If so, how? And, how to manipulate with it? I mean, how to use push_back() to add an item and how to use at() to read a member from it.Code:struct cart { int index; string pname; }; vector <cart> a;
Is this possible to store a structure in vector? If so, how? And, how to manipulate with it? I mean, how to use push_back() to add an item and how to use at() to read a member from it.Code:struct cart { int index; string pname; }; vector <cart> a;
Yes.
etc. Haven't you tried that before?Code:vector<cart> a; cart thing;// put values in there somewhere a.push_back( thing );
It works the same as if you stored a string in a vector.
You can use a constructor for the struct and use that to push objects onto the vector without using a named temp object as well.
Code:struct cart { int index; string pname; cart(string name,int val) : pname(name), index(val) {} }; vector <cart> a; a.push_back( cart("Bob",14) ); a.push_back( cart("Linda",26) ); ... etc ... // Output all structs in vector container. for( vector<cart>::const_iterator cit = a.begin(); cit != a.end(); ++cit ) cout << "Name: " << cit->pname << "\tIndex: " << cit->index << endl; // Output a single item, the second object, position 1 in the vector. cout << "Name: " << a[1].pname << "\tIndex: " << a[1].index << endl; // Same as above, except uses "at" cout << "Name: " << a.at(1).pname << "\tIndex: " << a.at(1).index << endl;
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens