初始化C++字符串向量的向量

Initialize a vector of vector of strings in C++

本文关键字:向量 字符串 C++ 初始化      更新时间:2023-10-16

我正在尝试在C++中做一个字符串向量向量,但我没有得到它;这是我的代码的样子:

#include <vector>
#include <string>
int main() {
    std::vector<std::vector<std::string>> foo =
        {
            std::vector<std::string> ex,
            std::vector<std::string> bar,
        };
    }

尝试使用 GCC 编译它时,给了我以下输出:

example.cpp: In function ‘int main()’:
example.cpp:6:28: error: expected primary-expression before ‘ex’
 std::vector<std::string> ex,
                        ^~
example.cpp:6:28: error: expected ‘}’ before ‘ex’
example.cpp:5:2: note: to match this ‘{’
{
^
example.cpp:6:28: error: could not convert ‘{<expression error>}’ from                                                            ‘<brace-enclosed initializer list>’ to ‘std::vector<std::vector<std::__cxx11::basic_string<char> > >’
std::vector<std::string> ex,
                        ^~
example.cpp: At global scope:
example.cpp:9:1: error: expected declaration before ‘}’ token
}
^

任何帮助将不胜感激。谢谢!

另一种方式:

#include <string>
#include <vector>
int main()
{
  std::vector<std::vector<std::string>> foo(2);
}

将名称放在初始化器列表中:

#include <vector>
#include <string>
int main() {
    std::vector<std::vector<std::string>> foo =
    {
        std::vector<std::string>{}, // <- no name + added curly braces
        std::vector<std::string>{}  // <- no comma
    };
}