Class/Struct in a Vector...

This is a discussion on Class/Struct in a Vector... within the C++ Programming forums, part of the General Programming Boards category; I'm trying to put a struct or a class into a vector... it seems to work alright but I would ...

  1. #1
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204

    Thumbs up Class/Struct in a Vector...

    I'm trying to put a struct or a class into a vector... it seems to work alright but I would like to know how to use functions/variables from the class.

    Code:
    struct test
    {
    	int aaa;
    };
    
    int main()
    {
    	vector<test> vec;
    	test str;
    	str.aaa=12;
    	vec.push_back(str);
    	cout<<vec[vec.size()].aaa;
    }
    This attempt compiles but comes up with 6 digit numbers when I expect it to be 12. So how do you put a class into a vector and retrieve the information?

    Thanks

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,893
    The problem is that vec[vec.size()] accesses an element that does not exist (it is one past the last element in the array).

    What you really want to write is:
    Code:
    cout << vec[0].aaa;
    Or if you want the most recently pushed element:
    Code:
    cout << vec.back().aaa;
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,659
    Code:
        cout<<vec.size() << endl;
        cout<<vec[vec.size()-1].aaa << endl;
    Just like arrays, subscripts start at 0.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Not stupid, just stupider yaya's Avatar
    Join Date
    May 2007
    Location
    Earthland
    Posts
    204
    Ah! Thankyou both alot!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can some one please tell me the cause of the error ?
    By broli86 in forum C Programming
    Replies: 8
    Last Post: 06-26-2008, 08:36 PM
  2. syntax help?
    By scoobygoo in forum C++ Programming
    Replies: 1
    Last Post: 08-07-2007, 10:38 AM
  3. Vector class
    By Desolation in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2007, 05:44 PM
  4. Need some help/advise for Public/Private classes
    By nirali35 in forum C++ Programming
    Replies: 8
    Last Post: 09-23-2006, 12:34 PM
  5. Certain functions
    By Lurker in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2003, 12:26 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21