Reputation: 86
I'm in the process of learning C++/general programming and sometimes experiment with C++11 features while doing exercises written for the older standard.
This exercise involves a vector of pointers to strings.
#include <vector>
#include <string>
#include <iostream>
int main()
{
using std::string ;
using std::vector ;
using std::cout ;
using std::endl ;
vector<string *> v = {new string("Hello") , new string("World")} ;
for (string * x : v) {
cout << *x << " " ;
delete x ;
}
cout << endl ;
}
I had a little difficulty figuring how to use the initialization list with this vector, but this seems to work.
This version also works:
//...
string s1 = "Hello" ;
string s2 = "World" ;
vector<string *> v = {&s1 , &s2} ;
for (string * x : v)
cout << *x << " " ;
//...
It looks cleaner, and from what I've learned so far it seems like the better solution.
But I find myself wondering: is there some other way to initialize the vector without creating the strings ahead of time or having to use delete? What I read suggests the {} list should be usable universally.
And for what it's worth, this gives a rather catastrophic error:
vector<string *> v = {"Hello" , "World"} ;
Upvotes: 2
Views: 5962
Reputation: 361642
Why do you use std::string*
in the first place? Do you have any reason for that? I don't think so.
Use this:
std::vector<std::string> v{"Hello" , "World"};
Now, you don't need to use new
. Such classes are designed precisely because you could avoid using new
yourself.
Also note that there is no '='
between 'v'
and '{'
in the initialization above. This initialization is called uniform initialization introduced by C++11. More examples here.
Upvotes: 12
Reputation: 549
Like Nawaz said, why bother using pointers to strings? Just for the sake of using the -> operator? Make a class that has a few private variables and return them using references. That's a better example of when to use the arrow operator.
Upvotes: 0
Reputation: 92331
But I find myself wondering: is there some other way to initialize the vector without creating the strings ahead of time or having to use delete?
No, to store pointers to something, you have to have this something stored somewhere else. Otherwise there will be no place for the pointer to point to.
That it feels odd is probably because this is an unusual way to store strings. If it wasn't an (artificial) exercise, you could be using a std::vector<std::string>>
and get rid of your problems.
Upvotes: 3