What is the best way to create a Vector of objects?

Currently my code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
vector<S> v;

S s1("Jon");
S s2("Mike");
S s3("Kim");
S s4("Steve");
S s5("Kevin");

v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
v.push_back(s5);


My program will create 5 objects every time, whats the most efficient way to do the above? I'm sure how I'm doing it is not.

I need to be able to call the object from the vector.

Thanks in advance.
1
2
3
4
5
6
7
8
9
// Requires C++11 or later.
vector<S> v
{
	{"Jon"},
	{"Mike"},
	{"Kim"},
	{"Steve"},
	{"Kevin"}
};
Last edited on
Interesting! Tho your code gives an error on line 3.
Thanks for not telling is what the error is. Withholding information really is the best way to get help with solving your problem.
Its not really a problem, more like I'm just asking what is the most efficient syntax!

 
error C2143: syntax error : missing ';' before '}'


And thats after I modified the above code to this:

1
2
3
4
5
6
7
8
vector<S> v
{
	"Jon",
	"Mike",
	"Kim",
	"Steve",
	"Kevin"
};


works as written: http://coliru.stacked-crooked.com/a/5071b4479eb891df -- perhaps you're using C++98 instead of C++11 or newer?
Topic archived. No new replies allowed.