gpt4 book ai didi

c++ - 为什么我不能将此对象推送到我的 std::list 中?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:33:11 26 4
gpt4 key购买 nike

刚开始用 C++ 编程。

我创建了一个 Point 类、一个 std::list 和一个迭代器,如下所示:

class Point { 
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};

std::list <Point> pointList;
std::list <Point>::iterator iter;

然后我将新点推送到 pointList。

现在,我需要遍历 pointList 中的所有点,所以我需要使用迭代器进行循环。这就是我搞砸的地方。

for(iter = pointList.begin(); iter != pointList.end(); iter++)
{
Point currentPoint = *iter;
glVertex2i(currentPoint.x, currentPoint.y);
}

<罢工>


更新

你们是对的,问题不在于我迭代列表。看来问题出在我试图将某些内容推送到列表时。

确切错误:

mouse.cpp: In function void mouseHandler(int, int, int, int)':
mouse.cpp:59: error: conversion from
Point*' to non-scalar type `Point' requested

这些行是:

 if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
Point currentPoint = new Point(x, y);
pointList.push_front(currentPoint);

}

Point* 到非标量类型 Point 之间的转换是什么?我只是想创建新点并将它们推到此处的列表中。

最佳答案

那应该是一段有效的代码。

#include <iostream>
#include <list>

class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};

int main()
{
std::list<Point> points;

points.push_back(Point(0, 0));
points.push_back(Point(1, 1));
points.push_back(Point(2, 2));

std::list<Point>::iterator iter;

for(iter = points.begin(); iter != points.end(); ++iter)
{
Point test = *iter;
std::cout << test.x << ", " << test.y << "; ";
}
std::cout << std::endl;

return 0;
}

使用这段代码:

jasons-macbook41:~ g++ test.cpp
jasons-macbook41:~ ./a.out
0, 0; 1, 1; 2, 2;
jasons-macbook41:~

尽管我不会像您的代码那样创建 Point 的临时拷贝。我会像这样重写循环:

for(iter = points.begin(); iter != points.end(); ++iter)
{
std::cout << iter->x << ", " << iter->y << "; ";
}

迭代器在语法上类似于指针。

编辑:鉴于您的新问题,请从构造线中删除"new"。这是创建指向 Point 的指针,而不是堆栈上的 Point。这是有效的:

Point* temp = new Point(0, 0);

或者这个:

Point temp = Point(0, 0);

你最好选择后者。

关于c++ - 为什么我不能将此对象推送到我的 std::list 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/535223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com