如何使用迭代器作为类成员向量? [英] How do you use iterators for a class member vector?
本文介绍了如何使用迭代器作为类成员向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ostream & operator <<(ostream & os, LongNumber & along)
{
for(std::vector<LongNumber>:: iterator i = (along.container).begin(); i != (along.container).end(); ++i) //this line give me errors
{
os << *i;
}
return os;
}
class LongNumber
{
private:
vector<int> number;
};
error: conversion from to non-scalar type iterator requested
error: no match for operator !=
i不知道出了什么问题。
i have no idea what's wrong.
推荐答案
在类中声明一个容器成员不会使该类成为容器,也不会为该类创建容器。
您的 LongNumber 类没有名为 container 的成员。你必须要写一个访问函数:
Declaring a container member in a class does not make the class a container, nor does it create a container for the class.
Your LongNumber class does not have a member called container. You have to either write an accessor function:
class LongNumber
{
private:
vector<int> number;
public:
vector<int>& container();
};
ostream & operator <<(ostream & os, LongNumber & along)
{
for(std::vector<int>::iterator i = along.container().begin(); i != along.container().end(); ++i)
或使其成为公共会员:
or make it a public member:
class LongNumber
{
public:
vector<int> number;
};
ostream & operator <<(ostream & os, LongNumber & along)
{
for(std::vector<int>::iterator i = along.number.begin(); i != along.number.end(); ++i)
或提供对开始和结束迭代器的访问:
or provide access to the beginning and end iterators:
class LongNumber
{
private:
vector<int> number;
public:
vector<int>::iterator begin()
{
return number.begin();
}
vector<int>::const_iterator begin() const
{
return number.begin();
}
vector<int>::iterator end()
{
return number.end();
}
vector<int>::const_iterator end() const
{
return number.end();
}
};
ostream & operator <<(ostream & os, LongNumber & along)
{
for(std::vector<int>::iterator i = along.begin(); i != along.end(); ++i)
请注意,我已将循环中的类型从 std :: vector< LongNumber> 更改为 std :: vector< int> 此处。上面示例中的代码将遍历沿变量的成员容器的元素。
Note that I've changed the type in the loop from std::vector<LongNumber> to std::vector<int> here. The code in the examples above will iterate over the elements of the member container of your along variable.
这篇关于如何使用迭代器作为类成员向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文