vector<string> a在构造函数中初始化
时间: 2023-09-07 13:15:26 浏览: 88
好的,你可以这样在构造函数中初始化vector<string> a:
```
class MyClass {
public:
MyClass() : a({"hello", "world", "!"}) {}
private:
vector<string> a;
};
```
这样就可以在创建 MyClass 对象时,自动初始化 a 为 {"hello", "world", "!"}。
相关问题
vector<vector<string>> Matrix(190,vector<string>(190))这个有错吗
从语法上来说,`vector<vector<string>> Matrix(190, vector<string>(190))` 这段代码试图创建一个二维 `vector`,其中每个元素都是一个包含字符串的一维 `vector`,并且初始化所有行都为长度为190的字符串向量。然而,在 C++ 中,直接在构造函数中给这么大范围的数组赋初始值通常不是最佳实践,因为可能会导致性能问题,特别是当内存不足以一次性容纳这么多数据时。
正确的做法应该是先定义一个大小足够的二维向量,然后逐行或逐列添加元素。如果你确实需要预分配这种大小,可以这样做:
```cpp
vector<vector<string>> Matrix;
Matrix.resize(190, vector<string>(190)); // 预分配190x190的空间
```
如果你想在动态地填充内容,可以省略这一行,并在后续循环中添加元素:
```cpp
for (size_t i = 0; i < 190; ++i) {
for (size_t j = 0; j < 190; ++j) {
// 省略了 resize 行,这里添加实际的字符串到矩阵中
Matrix[i][j] = "初始字符串"; // 或者其他操作
}
}
```
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是首选方式。
阅读全文
相关推荐













