小编Enr*_*nra的帖子

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

我正在学习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 …
Run Code Online (Sandbox Code Playgroud)

c++ pointers vector

2
推荐指数
1
解决办法
5933
查看次数

标签 统计

c++ ×1

pointers ×1

vector ×1