Sep 23, 2016 at 2:56am UTC
Can anybody show me how to create a simple vector containing a list of people with their first names, last names, and phone number, with a constructor??
the only way i can create it, is by implementing a structure .
How ever, I read in some article that it is possible to do it without structure. and I am a little bit confused by that
Sep 23, 2016 at 3:04am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
struct MyContact
{
MyContact(const std::string &first, const std::string &last, const std::string &phone_num) :
first_name(first),
last_name(last),
phone_number(phone_num)
{
}
std::string first_name;
std::string last_name;
std::string phone_number;
};
std::vector<MyContact> contact_list;
Last edited on Sep 23, 2016 at 3:05am UTC
Sep 23, 2016 at 3:09am UTC
I still don't see how come i can initialize many contacts in this vector?
is it considered as an array ?
Sep 23, 2016 at 4:07am UTC
Is it considered as an array?
http://www.cplusplus.com/reference/vector/vector/
So this is how you use it :
1 2 3 4 5 6 7 8 9 10 11 12 13 14
std::string first;
std::string last;
std::string phone_num;
int i;
int N = 10;
for (i = 0; i < N; i++)
{
cout << "Enter first name : " ; cin >> first;
cout << "Enter last name : " ; cin >> last;
cout << "Enter phone number : " ; cin >> phone_num;
contact_list.push_back(MyContact(first, last, phone_num));
}
Last edited on Sep 23, 2016 at 4:08am UTC