I have a set of pointers to objects of the following class:
class name_id {
public:
name_id(string name_a, int id_a) { name = name_a; id = id_a; }
string name;
int id;
bool operator<(name_id &);
};
Later, after populating the set, I pass this set to a function and try to access the name field of each object:
void print_by_rank(set<name_id *> &nameIdSet, map<int, int> &votesMap)
{
vector<string> names;
vector<string>::iterator names_it;
set<name_id *>::iterator nameIdSet_it;
for(nameIdSet_it = nameIdSet.begin(); nameIdSet_it != nameIdSet.end(); ++nameIdSet_it)
//names.push_back(nameIdSet_it->name);
cout << nameIdSet_it->name << endl;
}
However, neither of the bottom two lines will compile. I receive the following message:
g++ -o bobwinner bobwinner.cpp
bobwinner.cpp: In function 'void print_by_rank(std::set<name_id*, std::less<name_id*>, std::allocator<name_id*> >&, std::map<int, int, std::less<int>, std::allocator<std::pair<const int, int> > >&)':
bobwinner.cpp:68: error: request for member 'name' in '* nameIdSet_it.std::_Rb_tree_const_iterator<_Tp>::operator-> [with _Tp = name_id*]()', which is of non-class type 'name_id* const'
I do not understand why I cannot use the arrow operator on an iterator to access the name field of the object to which the set element points.
You need to dereference the iterator to get the pointer. You then need to dereference the pointer to get at the object itself. So you probably want: