vector<string> a在构造函数中初始化
时间: 2023-09-07 14:15:26 浏览: 38
好的,你可以这样在构造函数中初始化vector<string> a:
```
class MyClass {
public:
MyClass() : a({"hello", "world", "!"}) {}
private:
vector<string> a;
};
```
这样就可以在创建 MyClass 对象时,自动初始化 a 为 {"hello", "world", "!"}。
相关问题
c++初始化vector<string>
可以使用以下方法来初始化 vector<string> :
1. 使用花括号初始化:vector<string> words = {"hello", "world"};
2. 使用构造函数初始化:vector<string> words(3, "hello"); // 创建大小为3,值都为"hello"的vector
3. 使用 push_back() 或 emplace_back() 添加元素:vector<string> words; words.push_back("hello"); words.push_back("world");
需要注意的是,在C++11以后,使用花括号初始化vector是首选方式。
构造函数如何初始化vector<unique_ptr<Student>> vec
假设 `Student` 是一个类,可以使用以下代码初始化 `vector<unique_ptr<Student>> vec`:
```c++
vector<unique_ptr<Student>> vec;
// 添加元素到 vec 中
vec.push_back(make_unique<Student>("John"));
vec.push_back(make_unique<Student>("Jane"));
vec.push_back(make_unique<Student>("Bob"));
```
在上述代码中,我们使用了 `make_unique` 函数来创建 `unique_ptr` 对象并将其添加到 `vec` 中。注意,在使用 `make_unique` 函数时,需要传递 `Student` 类的构造函数所需的参数。这里我们假设 `Student` 类的构造函数接受一个 `const string&` 类型的参数。