我们可以制作向量的向量吗?

有人可以制作一个充满矢量的矢量吗?

例如,您创建一个向量,用于存储所有元素。然后,您创建一个新向量,其中填充了前一个向量的倍数。如果你明白我的意思。

类似于下面的内容,尽管我很确定这不是它的工作原理。

vector <string> v { First, Second, Third, GPA, Name };
vector <string> newVect { v };

回答

你可以,但你需要相应地声明类型:

// Define a vector of string
std::vector<std::string> example { "One", "Two", "Three" };

// Define a vector of (vector of string) wrapping another vector of string
std::vector<std::vector<std::string>> nested { example };

请记住,C ++是强类型的含义std::vector<std::string>可包含std::string唯一 std::stringstd::vector<std::string>在那里嵌套 a是无效的。

这具有复制 example到 new的效果std::vector,所以这不是最有效的。幸运的是,您也可以一次性定义它:

// Define a vector of (vector of string) directly
std::vector<std::vector<std::string>> nested { { "One", "Two", "Three" } };

要使用它并显示条目,您还需要一个嵌套循环,因为结构规定:

// Iterate over the vector (of vector of string)
for (auto&& outer : nested) {
  // Iterate over the vector (of string)
  for (auto&& inner : outer) {
    std::cout << inner << std::endl;
  }
}

  • @PierreBaret That was a problem, but was addressed in C++11.

以上是我们可以制作向量的向量吗?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>