【问题标题】:Vector of tuple structs元组结构的向量
【发布时间】: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 &lt;vector&gt;
  • @SwimMaster 不要称您的类型为tuple,尤其是在您使用using namespace std; 之后。 C++ 标准库中有一个std::tuple
  • 您刚刚发现了why using namespace std; is bad practice。您的代码在tuplestd::tuple 之间存在混淆。帮自己一个大忙,完全忘记using namespace std; 是 C++ 语言的一部分。摆脱它,或者永远遇到神秘的编译错误,比如这个。

标签: c++ templates vector


【解决方案1】:

你的错误的原因是这个结构:

struct tuple {
    int x;
    int y;
};

1) 当标准库中存在 std::tuple 时,您将类型称为 tuple,并且

2) 您使用了using namespace std;,因此在您的代码中提及tuple 可能与std::tuple 发生冲突。

如果您将结构重命名为 my_tuple 或类似名称,您现在遇到的错误应该得到纠正。

【讨论】:

  • 保存,因为这是为什么using namespace std; 是一个糟糕的想法的完美案例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-05
  • 1970-01-01
  • 2013-11-16
  • 1970-01-01
  • 2015-09-08
相关资源
最近更新 更多