可以直接初始化vector <string*>而不用new吗?

Enr*_*nra 2 c++ pointers vector

我正在学习C++ /通用编程,有时在为旧标准编写练习时尝试使用C++ 11功能.

此练习涉及指向字符串的指针向量.

#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 ;
}
Run Code Online (Sandbox Code Playgroud)

我有点困难,想知道如何使用这个向量的初始化列表,但这似乎工作.

这个版本也有效:

    //...
    string s1 = "Hello" ;
    string s2 = "World" ;
    vector<string *> v = {&s1 , &s2} ;
    for (string * x : v)
        cout << *x << " " ;
    //...
Run Code Online (Sandbox Code Playgroud)

它看起来更干净,从我到目前为止所学到的,它似乎是更好的解决方案.

但我发现自己想知道:有没有其他方法初始化矢量而不提前创建字符串或不得不使用删除?我读到的内容表明{}列表应该可以普遍使用.

而对于它的价值,这给出了一个相当灾难性的错误:

vector<string *> v = {"Hello" , "World"} ;
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 12

你为什么一开始使用std::string*?你有什么理由吗?我不这么认为.

用这个:

std::vector<std::string> v{"Hello" , "World"};
Run Code Online (Sandbox Code Playgroud)

现在,您不需要使用new.这些课程的设计正是因为你可以避免使用new自己.

另请注意,上面的初始化'='之间'v'和之间都没有'{'.这种初始化称为C++ 11引入的统一初始化.这里有更多例子.