c++ - 在构造函数的初始化列表上初始化数组或 vector

标签 c++ arrays vector constructor initialization

如何在 C++ 中使用构造函数的初始化列表来初始化(字符串)数组或 vector ?

请考虑这个例子,我想用给构造函数的参数初始化一个字符串数组:

#include <string>
#include <vector>

class Myclass{
           private:
           std::string commands[2];
           // std::vector<std::string> commands(2); respectively 

           public:
           MyClass( std::string command1, std::string command2) : commands( ??? )
           {/* */}
}

int main(){
          MyClass myclass("foo", "bar");
          return 0;
}

除此之外,建议在创建对象时保存两个字符串的两种类型(数组还是 vector )中的哪一种,为什么?

最佳答案

对于 C++11,您可以这样做:

class MyClass{
           private:
           std::string commands[2];
           //std::vector<std::string> commands;

           public:
           MyClass( std::string command1, std::string command2)
             : commands{command1,command2}
           {/* */}
};

对于 C++11 之前的编译器,您需要在构造函数的主体中初始化数组或 vector :

class MyClass{
           private:
           std::string commands[2];

           public:
           MyClass( std::string command1, std::string command2)
           {
               commands[0] = command1;
               commands[1] = command2;
           }
};

class MyClass{
           private:
           std::vector<std::string> commands;

           public:
           MyClass( std::string command1, std::string command2)
           {
               commands.reserve(2);
               commands.push_back(command1);
               commands.push_back(command2);
           }
};

关于c++ - 在构造函数的初始化列表上初始化数组或 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19567348/

相关文章:

C++/OpenGL - 绘制立方体 VBO

python - 总结 Python 中的数组字典

C 尝试在数组中搜索特定数字

C++ move () : what's left in the vector?

c++ - 在 GDB 调试器中显示 cv2 Mat

c++ - c++ 集合中的用户定义数据类型

c++ - 如何输入矩阵样式的 txt 文件而不是为 C++ 定义我自己的 int 二维数组

c++ - 如何在 C++ 中将 CSV 文件读入 vector

c++ - 在 vector C++ 的索引处插入对象

c++ - 如果您通过复制传递 lambda 函数,实际复制的是什么?