Thread: Structure in vector

  1. #1
    Registered User
    Join Date
    Jan 2006
    Location
    Latvia
    Posts
    102

    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.

  2. #2
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Yes.

    Code:
    vector<cart> a;
    
    cart thing;// put values in there somewhere
    a.push_back( thing );
    etc. Haven't you tried that before?

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    It works the same as if you stored a string in a vector.

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Vectors
    By naseerhaider in forum C++ Programming
    Replies: 11
    Last Post: 05-09-2008, 08:21 AM
  2. vector of arrays of pointers to structures
    By Marksman in forum C++ Programming
    Replies: 13
    Last Post: 02-01-2008, 04:44 AM
  3. my vector class..easy dynamic arrays
    By nextus in forum C++ Programming
    Replies: 5
    Last Post: 02-03-2003, 10:14 AM
  4. Operators for 3D Vector Mathematics
    By Anarchist in forum C++ Programming
    Replies: 10
    Last Post: 01-31-2003, 07:33 PM
  5. vector static abstract data structure in C?
    By Unregistered in forum C Programming
    Replies: 2
    Last Post: 11-05-2001, 05:02 PM