代码之家  ›  专栏  ›  技术社区  ›  Galaxy

如何初始化字符串的std::数组?

  •  0
  • Galaxy  · 技术社区  · 7 年前

    我有一个 std::array<std::string, 4> 用于保存要读入程序的文本文件的路径名。到目前为止,我声明数组,然后分配每个数组 std::string 对象值。

    #include <array>
    #include <string>
    using std::array;
    using std::string;
    ...
    array<string, 4> path_names;
    path_names.at(0) = "../data/book.txt";
    path_names.at(0) = "../data/film.txt";
    path_names.at(0) = "../data/video.txt";
    path_names.at(0) = "../data/periodic.txt";
    

    我使用这种方法是因为我事先知道数组中正好有4个元素,数组的大小不会改变,而且每个路径名都是硬编码的,也不能改变。

    我想在一个步骤中声明并初始化数组及其所有元素。例如,这就是我如何声明一个 int 学生:

    array<int, 10> ia2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};  // list initialization
    

    标准::字符串 ? 创建这些字符串需要调用构造函数。这不是简单的列表初始化一堆 s、 怎么做?

    1 回复  |  直到 7 年前
        1
  •  1
  •   P.W    7 年前

    这可以通过两种方式实现:

    1. 在列表初始化中使用字符串文字

    array<string, 4> path_names = {"../data/book.txt", "../data/film.txt", "../data/video.txt", "../data/periodic.txt"};

    string s1 = "../data/book.txt";
    string s2 = "../data/film.txt";
    string s3 = "../data/video.txt";
    string s4 = "../data/periodic.txt";
    array<string, 4> path_names = {s1, s2, s3, s4};

    如果你想避免在这里复制,你可以使用 std::move :

    array<string, 4> path_names = {std::move(s1), std::move(s2), std::move(s3), std::move(s4)};