gpt4 book ai didi

c++ - 如何从重写的运算符<<迭代 vector 数据成员

转载 作者:太空宇宙 更新时间:2023-11-04 16:28:15 24 4
gpt4 key购买 nike

这是我的测试程序。变量 s1 包含一个 vector ,该 vector 包含用户定义类型的对象。我想重载 << 运算符以很好地打印此 vector ,每行一个元素。

#include <iostream>
#include "myclasses.h"
using namespace std;

int main() {

myclass s1;

s1.add_point(7000, 10);
s1.add_point(8000, 11);
s1.add_point(9000, 12);

cout << s1 << endl;

return 0;

}

这是类定义。基本上它只是另一个用户定义对象的数组。我希望 << 运算符打印所有条目,每行一个。假设“另一个类”具有所需的支持方法。

class myclass {
vector<anotherclass> ps;
public:
void add_point(double, double);
friend ostream &operator<<( ostream &out, const myclass &s );
};

void myclass::add_point(double first, double second) {
ps.push_back(anotherclass(first, second));
}

ostream &operator<<( ostream &out, const myclass &s ) {
vector<anotherclass>::iterator itr;
vector<anotherclass> psp=s.ps; // Why do I need this? Why can't I use s.ps.begin() and s.ps.end() in the for loop directly?
for ( itr=psp.begin() ; itr != psp.end() ; ++itr ) {
cout << "(" << itr->get_first() << "," << itr->get_second() << endl;
}
return out;
}

我已经注释了一行,我需要添加一行才能让它在我的程序中工作。我不知道为什么需要那条线。有人可以给我解释一下吗?

最佳答案

iterator成员类型总是允许您修改引用的对象。因此,您无法获得 iterator来自const &参数如 s .您需要声明局部变量的类型为 vector< anotherclass >::const_iterator .每个容器类都有一个 const_iteratoriterator并行.

您的单行修复起作用的原因是新构建的 vector不是 const ,与构造它的函数参数不同。

在 C++11 中,你可以只使用 auto itr = s.ps.begin()并且永远不要命名迭代器类型。或者只使用 for ( auto const &obj : s.ps )并完全放弃迭代器。

关于c++ - 如何从重写的运算符<<迭代 vector 数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918747/

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