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"} ;