user434462
user434462

Reputation: 49

C++ STL Accessing Member of Class with a Set of Pointers

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.

Upvotes: 0

Views: 1142

Answers (3)

themel
themel

Reputation: 8895

Beyond compiling that, you're also in for a surprise because pointer sets aren't sorted by the comparator for the underlying object, so this will likely not do what you think it does.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476970

You need to dereference the iterator, and that itself gives you a pointer, which you need to dereference again:

(*nameIdSet_it)->name
^^^^^^^^^^^^^^^
  this is a pointer

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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:

cout << (*nameIdSet_it)->name << endl;

Upvotes: 5

Related Questions