-
Structure in vector
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.
-
Yes.
Code:
vector<cart> a;
cart thing;// put values in there somewhere
a.push_back( thing );
etc. Haven't you tried that before?
-
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;