push_back on vector<class> ???

Is it possible to use push_back to create instances of a class in a vector, in the same way as you would with a vector<int>?

The following code does not work. Am I missing something obvious, or is it not possible to do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class addressBook {
public:
	string name = "Joe";
	double phone = 5555;
};

int main()
{
	vector<addressBook> entry;
	entry.push_back();
}
Yes it is possible. Your code is not working because you're not push_back'ing anything. You have to give it an object to put at the end of your vector:

1
2
3
4
5
6
7
8
9
10
vector<int> foo;

foo.push_back(); // <- doesn't work, what do you want it to push?
foo.push_back(5);  // <- Ok!

//...

vector<addressBook> bar;
bar.push_back();  // <- doesn't work.  What do you want it to push?
bar.push_back( addressBook() ); // <- Ok!  Will push a default constructed addressBook object. 
Last edited on
It is possible. Either by overloading and copying like Disch posted, storing it as a pointer or using emplace_back() on a C++11 compiler.

1
2
vector<addressBook> bar;
bar.emplace_back(val1, val2, val3);  //All constructor values go here for addressBook. 
Thanks a lot guys.
Topic archived. No new replies allowed.