c++ - 即使我有头文件,代码输入错误

标签 c++ compiler-errors

我尝试运行自己制作的程序,但是由于某种原因,运行该程序时出现错误。错误与cin >> x >> y部分有关。我现在的主要问题是我不知道如何通过人工输入将内容输入 vector 。我遇到的错误是此行有多个标记
-请求y中的y成员,该成员属于非类
输入int
-请求x中的成员x,这是非类的
输入int
提前致谢。

#include <iostream>
#include <vector>

using namespace std;
struct Point {
    int x, y;
};
int manhattan_dist(const Point& p, const Point& q) {
    return abs(p.x - q.x) + abs(p.y - q.y);
}
int main (int argc, char ** argv)
{
    Point x,y;
    Rd("marathon.in");
    Wt("marathon.out");
    int checkpoints;
    vector<Point> points(checkpoints);
    int largestdistance=0;
    int sum=0;
    cin >> checkpoints;
    for (int i=0; i<checkpoints; i++){
        for (int j=0; j<2; j++){
            cin >> x >> y;
        }
    }
    for (int i = 0; i < checkpoints - 1; ++i) {  // stop before c-1, so i and i+1 are valid
        sum += manhattan_dist(points[i], points[i+1]);
    }

    if (sum > largestdistance){
        largestdistance=sum;
    }
    cout << largestdistance << '\n';
    return 0;
}

最佳答案

您可以定义operator>>如何为您的自定义类型工作。为此,您需要重载它。如果您希望将cin中的第一个数字转到Point::x,另一个将其转换为Point::y,则应使用以下代码:

std::istream& operator>>(std::istream& in, Point& p) {
    return in >> p.x >> p.y;
}

然后
Point p;
std::cin >> p;

会工作。然后,您可以将其推回points vector 。看来您正在尝试从stdin中读取一堆要点,并将它们 push vector 中。如果那是 Actor ,那么您需要坐在一个循环中。
std::vector<Point> points;
Point p;
while (std::cin >> p) {
    points.push_back(p);
}

或者,如果应该将checkpoints变量初始化为points vector 的大小
std::vector<Point> points(checkpoints);
for (std::size_t i = 0; i < points.size(); ++i) {
    std::cin >> points[i];
}

关于c++ - 即使我有头文件,代码输入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27476410/

相关文章:

python - 错误 : suffix or operands invalid for `vbroadcastss'

c++ - C++ 'class'尚未声明-将类传递给类

c++ - objectCast 横向转换

c++ - 在Cython中编译C和C++源代码

c++ - 为什么我不能直接在临时对象上调用 operator() ?

c++ - 使用 unix sendmail 发送电子邮件

ios - XCode 未定义引用

c++ - 无法使用 catch (...) 捕获 c++ 异常

c++ - 编写并解决计算此代码中乘法次数的递归?

c++ - OpenMP 通过 std::set 使用迭代器