【发布时间】:2019-01-27 01:48:10
【问题描述】:
以下代码 sn-p 出现错误;
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
struct tuple {
int x;
int y;
};
int main() {
//srand(time(NULL));
vector<tuple> locations;
int dimentions = 20;
double filledness = 0.65;
while (locations.size() < dimentions * dimentions * filledness) {
tuple point;
point.x = rand() % dimentions;
point.y = rand() % dimentions;
locations.push_back(point);
}
int count = locations.size();
tuple start, end;
start = locations[rand() % count];
end = locations[rand() % count];
cout << count << endl;
for (int i = 0; i < locations.size(); i++) {
cout << locations[i].x << " " << locations[i].y << endl;
}
cout << start.x << start.y << endl;
cout << end.x << end.y;
return 0;
}
向量初始化在我的 main 和上面的结构大纲中。我显然不了解向量。我尝试使结构成为一个类以及用元组* 向量替换元组向量。
有人能解释一下为什么不能以这种方式使用向量吗,
如果您不告诉我如何直接修复错误,我会更愿意。
error: template argument 1 is invalid
vector<tuple> locations;
【问题讨论】:
-
显示的代码没有明显的错误。因此,问题一定出在未显示的代码中。如果您希望有人帮助您,您必须按照创建minimal reproducible example 的说明进行操作。
-
在 C++ 中,结构/类声明需要分号;后。我在您的代码中没有看到任何内容?我认为这不是您的完整代码。
-
上面的代码完全有效。确保将其称为
std::vector和#include <vector>。 -
@SwimMaster 不要称您的类型为
tuple,尤其是在您使用using namespace std;之后。 C++ 标准库中有一个std::tuple。 -
您刚刚发现了why
using namespace std;is bad practice。您的代码在tuple和std::tuple之间存在混淆。帮自己一个大忙,完全忘记using namespace std;是 C++ 语言的一部分。摆脱它,或者永远遇到神秘的编译错误,比如这个。