【问题标题】:Variable length array of non-POD element type 'set<int>'非 POD 元素类型 'set<int>' 的可变长度数组
【发布时间】:2017-06-19 23:54:56
【问题描述】:

我不知道问题是什么。

#include <iostream>
#include <algorithm>
#include <fstream>
#include <set>
using namespace std;

int main() {
    ifstream infile("meeting.in");
    int FF, NumPaths;
    infile >> FF >> NumPaths;
    int Paths[NumPaths][4];
    set<int> Bessie_Times[FF];
    set<int> Elsie_Times[FF];
    for(int i=0;i<NumPaths;i++)
    {
        infile >> Paths[i][0] >> Paths[i][1] >> Paths[i][2] >> Paths[i][3];
    }
    sort(Paths,Paths+NumPaths);
}

在这些行中,我收到以下错误:

    int Paths[NumPaths][4];

数组类型'int[4]'不可赋值

    set<int> Bessie_Times[FF];

错误1:数组初始化器必须是初始化器列表

错误2:非POD元素类型'set'的变长数组

有人知道这是什么原因吗?我已经研究过,但似乎找不到任何解决问题的方法。我假设我正在尝试使用不应该使用的变量类型,但我找不到这个的实例。

【问题讨论】:

  • VLA 无论如何都是非标准的,我建议使用std::vector&lt;std::set&lt;int&gt;&gt;

标签: c++


【解决方案1】:

g++ 可以很好地编译您的代码(排序除外)。我不知道这是否违反标准。但无论如何,在 c++ 中你应该使用来自 stdlib 的容器:

#include <iostream>
#include <algorithm>
#include <fstream>
#include <set>
#include <array>

using namespace std;

int main()
{
  ifstream infile("meeting.in");
  int FF, NumPaths;
  infile >> FF >> NumPaths;

  std::vector<array<int, 4>> Paths(FF);
  std::vector<set<int>> Bessie_Times(FF);
  std::vector<set<int>> Elsie_Times(FF); 

  for(int i = 0; i < NumPaths; i++)
  {
    infile >> Paths[i][0] >> Paths[i][1] >> Paths[i][2] >> Paths[i][3];    
  }  

  sort(Paths.begin(), Paths.end());

  return 0;
}

不确定排序;也许你需要添加

sort(Paths[i].begin(), Paths[i].end());

内循环

【讨论】:

  • 非常感谢您的反馈!
【解决方案2】:
int Paths[NumPaths][4];//Array type 'int[4]' is not assignable

您正试图静态声明一个长度在编译时未知但仅在运行时已知的数组。您不能这样做,因为 C++ 不允许这样做。但是,您可以在运行时动态声明一个长度已知的数组:

int Paths[NumPaths][4]; // wrong

int *Paths[4]; // right
for (int i = 0; i < 4; i++)
  Paths[i] = new int[NumPaths]; 
set<int> Bessie_Times[FF];//Error 1: Array initializer must be an initializer list Error 2: variable length array of non-POD element type 'set<int>'`

同样,这变成:

set<int> Bessie_Times[FF]; // wrong
set<int> *Bessie_Times = new set<int>[FF]; // right

请注意,您必须记住在程序结束时释放所有动态内存:

delete Paths[][];
delete BessieTimes[];

【讨论】:

  • 您的索引似乎倒退了。
  • 感谢您的帮助!
  • 另外,您需要删除所有 Paths[i]。不过,您确实应该为此使用向量和/或智能指针。
  • 我会赞成这一点,因为它注意到 VLA 不是标准 C++ 并且 new 必须与 delete 匹配,但是我不得不反对它,因为没有提到 new 和 @ 987654329@ 几乎不应该在最终用户的 C++ 代码中使用。 :/ 否则我们还不如继续使用 C,在剩下的时间里,慢慢地修补无穷无尽的内存泄漏。 OP 已经在使用std::set,所以真正的答案就在隔壁:停止手动分配数组,只使用std::vector
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
相关资源
最近更新 更多