如何使用C STD :: SET中的迭代器访问成员功能
How to access member function with iterator in C++ std::set
我正在尝试通过c std ::设置并访问成员函数。但是我以下代码不起作用。
#include <iostream>
#include <set>
using namespace std;
class A;
std::set<A> m_vector;
std::set<A>::iterator iter = m_vector.begin();
class A
{
public:
int age;
A()
{
cout << "enter age" << endl;
cin >> age;
}
int getAge()
{
return age;
}
private:
};
void addNewVoter()
{
m_vector.insert(A());
}
int main()
{
addNewVoter();
addNewVoter();
addNewVoter();
for (size_t i = 0; i < m_vector.size(); i++)
{
cout << (*iter)->getAge(); /* Here is the mistake. I can't invoke this.*/
iter++;
}
}
我的问题是,如何使用迭代器调用成员函数?
在准备遍历时初始化iter
。另外,由iter->getAge()
或(*iter).getAge()
。
#include <iostream>
#include <set>
using namespace std;
class A;
std::set<A> m_vector;
std::set<A>::iterator iter;
/* other codes */
int main()
{
addNewVoter();
addNewVoter();
addNewVoter();
iter = m_vector.begin();
while( iter != m_vector.end() )
{
cout << iter->getAge();
iter++;
}
}
您的代码段中需要进行三个更改。std ::内部实现了红色黑色二进制树,并且需要运营商重载以进行比较。
因此,您的课程应该具有附加功能:
bool operator <(const A& other) const
{
return age < other.age;
}
然后,当您调用getage()函数系统传递A的const对象时,您的getage函数应为const函数。
int getAge() const
^^^^^
{
return age;
}
第三个,您应该使用以下语法之一调用getage函数。(*iter).getAge()
或iter->getAge()
;不要混合。
demo
第一次编辑:
假设您至少知道如何通过指针调用该成员功能。答案是iter->getAge()
或(*iter).getAge()
-在评论中。
然后您正在这样做:
std::set<A> my_set;
auto it = my_set.begin();
// some inserts
std::cout << it->getAge() << std::endl;
这是未定义的行为。您不取消开始迭代器最初是从空容器中获取的。
只是使用此,而是:
for (auto it = my_set.begin(); it != my_set.end(); ++it)
std::cout << it->getAge() << std::endl;
或基于范围的for
...
如您所见,
,我拒绝使用您的命名惯例,因为它们不好且具有误导性。
相关文章:
- 如何通过迭代器访问向量中的嵌套对?
- 有关使用矢量迭代器访问对象方法的问题
- C++中的 2D 迭代器访问
- 如何使用C STD :: SET中的迭代器访问成员功能
- 尝试使用矢量迭代器访问对象
- 使用迭代器访问元素
- 使用C++迭代器访问元素
- 使用矢量迭代器访问方法
- 嵌套迭代器访问
- 使用迭代器访问结构元素
- 使用迭代器访问向量的特定点
- 如何从 STL 列表中的迭代器访问指向结构的指针而不是其元素
- 通过迭代器访问字符串向量中的字符
- C++-映射迭代器访问导致segfault
- C++:从只能通过迭代器访问的数据类型中高效地提取元素子集
- 向量索引访问与迭代器访问的效率
- 仅使用迭代器访问c++stl映射
- C++工厂制造和多态性 ->调用由映射迭代器访问的实例的子类的虚拟方法
- 那么,是否可以像使用指针一样使用迭代器访问二维向量中的所有元素呢?
- 使用迭代器访问映射的特定键的最有效方法