Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a vector<string *> be initialized directly without new?

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"} ;
like image 554
Enra Avatar asked Jul 29 '26 17:07

Enra


2 Answers

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.

like image 109
Nawaz Avatar answered Aug 01 '26 08:08

Nawaz


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.

like image 38
Bo Persson Avatar answered Aug 01 '26 07:08

Bo Persson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!