【问题标题】:array intilization needs curly braces数组初始化需要花括号
【发布时间】:2017-06-30 01:10:45
【问题描述】:

以下代码给出错误数组intilization需要花括号

如果我想创建二维数组并将其添加到向量中而不是怎么做?

vector<char[4][4]> testCases;
for(double i =0;i<noOFTestCase;i++)
{
    char arr[4][4];
    for(int j=0;j<4;j++)
    {
        cin>>(arr[j]);
    }
    testCases.push_back(arr);
}

【问题讨论】:

  • 您不能将数组作为向量元素 - 数组不可复制也不可移动。您可以定义一个以数组为唯一成员的结构,然后将其放入向量中。
  • 或者使用std::array,相当于同样的事情。

标签: arrays c++11 vector


【解决方案1】:

正如 Ramzah Rehman 所提到的,您可以在向量中放入什么是有限制的。它们必须定义了复制构造函数和初始化构造函数语义。

如果不定义复制和/或初始化构造函数(和析构函数),当向量类添加/删除或移动项目时,对象中的数据将是随机的。

你可以做的是用你的 testCases 作为属性创建一个类,并编写适当的构造函数。

您可以尝试使用字符串向量的向量,因为字符串类已经实现了可复制语义。

例如:

#include <vector>
#include <iostream>
#include <cstdlib>

using namespace std;

template<int N> class TestCase : public vector<string>
{
  public:
  TestCase() { resize(N); }
  static const int size() { return N; }
};

typedef TestCase<4> MyTestCase;

int main()
{
  vector<MyTestCase> testCases;

  for(int i =0;i<noOfTestCases;i++)
  {
    MyTestCase arr;

    for(int j=0;j< MyTestCase::size();j++)
    {
      std::cin>>(arr[j]);
    }
    testCases.push_back(arr);
  }
}

【讨论】:

    【解决方案2】:

    向量不能将数组作为数据成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多