【问题标题】:Cant seem to print list<VERTEX>vertices within a for loop using an iterator? C++似乎无法使用迭代器在 for 循环中打印 list<VERTEX> 顶点? C++
【发布时间】:2015-05-22 16:10:33
【问题描述】:

我遇到了一个问题,我无法打印保存在列表“顶点”顶点中的坐标集。为了解释,“顶点”是一个基本上包含两个坐标的类,这些坐标构成一个顶点(其中两条线形状满足)。问题出在第二个 for 循环中,该循环旨在打印出列表中保存的坐标。任何人都可以帮助我尝试将其打印出来吗?我尝试了很多方法,到目前为止,错误一直给我带来问题.. 代码如下,感谢帮助!

主要内容

int main(){
//obj
Console con;
RandomNumber rand;
Vertex vertex;

//Declarations
list<Vertex>vertices; 
//list<Vertex>::iterator ii;


//set Vertex coords and push into list
for (int i = 0; i <= 8;  i++){
vertices.push_back(Vertex(rand.random(0, 10), rand.random(0, 10)));
}

//iterate through the list outputting a char at each vertex (coords)
for (list<Vertex>::iterator ii = vertices.begin(); ii != vertices.end(); ii++){
    cout << vertices[ii];
}


system("pause");

}

顶点类

#pragma once
class Vertex
{
    int x;
    int y;
public:
    Vertex(int x = 10, int y = 10);
    ~Vertex();
    int getX() const;
    int getY() const;
    void setX(unsigned x);
    void setY(unsigned y);
    bool operator== (const Vertex &p2) const;
};

    #include "Vertex.h"
Vertex::Vertex(int x, int y)
{
    this->x = x;
    this->y = y;
}
Vertex::~Vertex(){}
int Vertex::getX() const {
    return x;
}
int Vertex::getY() const {
    return y;
}
void Vertex::setX(unsigned x) {
    this->x = x;
}
void Vertex::setY(unsigned y) {
    this->y = y;
}
bool Vertex::operator== (const Vertex &point) const {
    return (this->x == point.getX()) && (this->y == point.getY());
}

【问题讨论】:

标签: c++ for-loop iterator variable-assignment


【解决方案1】:
//iterate through the list outputting a char at each vertex (coords)
for (list<Vertex>::iterator ii = vertices.begin(); ii != vertices.end(); ii++){
    cout << vertices[ii];
}

这本质上是错误的。您需要使用迭代器,就像它是指向列表中第 ii 个对象的指针一样。

for (list<Vertex>::iterator ii = vertices.begin(); ii != vertices.end(); ii++){
    cout << ii->getX() << ',' << ii->getY(); 
    // if you have an overload for 'operator <<(std::ostream&, Vertex)' you can also do 
    cout << *ii 
}

【讨论】:

  • 谢谢,这解决了我的问题!也感谢其他人的建议!
【解决方案2】:

&lt;&lt; 运算符不适用于自定义类型。您需要指定&lt;&lt; 运算符在遇到Vertex 类时的行为方式。

您需要生成一个能够理解您的顶点类的签名。取如下函数:

std::ostream& operator<<(std::ostream &os, const Vertex &vertex) {
    os << "Node: [" << vertex.getX() << ", " << vertex.getY() << "]";
    return os;
}

这将允许您使用您编写的代码。

【讨论】:

    【解决方案3】:

    你需要给你的类添加一个函数:

    声明:

    friend std::ostream& operator <<(std::ostream &os,const Vertex &obj);
    

    和实施:

    std::ostream& operator<<( std::ostream &os,const Vertex &obj )
    {
        os << << obj.getX() << ',' << obj.getY();
        return os;
    }
    

    这将声明 here.

    您还必须将迭代更改为:

    for (list<Vertex>::iterator ii = vertices.begin(); ii != vertices.end(); ii++){
        cout << *ii;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 2020-08-09
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多