Vector Accounts

This is a discussion on Vector Accounts within the C++ Programming forums, part of the General Programming Boards category; This is toonlover again, and I am currently messing with dynamic arays, in other words, vectors. I am trying to ...

  1. #1
    Registered User
    Join Date
    May 2005
    Location
    Texas
    Posts
    103

    Vector Accounts

    This is toonlover again, and I am currently messing with dynamic arays, in other words, vectors. I am trying to make an account vector, that increases for how many users register. Here is some code, yet i really don't know how to access the members of this sturcture:
    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    typedef struct _acc
    {
    	int id;
    	int password;
    	char name[];
    }acc;
    
    
    int main()
    {
    	vector<acc> vacc(4);
    	system("PAUSE");
    	return 0;
    }
    I really don't know how access the members of acc in which are id,password,and name. Can someone help me how to do this? Thankyou in advance !

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,793
    Well, you use the same basic syntax as with normal arrays.

    vacc[0].id is the id field for the first acc struct. vacc[2].name is the name field for the third acc struct.

    Note: Be carefull with how you handle the name field. The STL containers make extensive use of copy constructors. Since name is basically a pointer there could be issues with a copy of a pointer being made while inserting an instance of this struct into the vector and the original being deleted or going out of scope somewhere else which would also invalidate the copy of the address stored in the container. This might leave someone with hard to track bug. This is dealt with by the use of custom copy constructors for any class/struct objects that use pointers and dynamic memory allocation.
    "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

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    In C++, you don't need to typedef the struct. In addition, you should just use the C++ string class in your struct to avoid the problems mentioned by hk_mp5kpdw with holding objects with dynamically allocated memory in an array or vector.
    Code:
    struct acc
    {
    	int id;
    	int password;
    	string name;
    };

Popular pages Recent additions subscribe to a feed

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