简体   繁体   English

C ++ STL通过一组指针访问类的成员

[英]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. 我不明白为什么我不能在迭代器上使用箭头运算符来访问set元素指向的对象的名称字段。

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;

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

除了进行编译之外,您还会感到惊讶,因为指针集没有由比较器对基础对象进行排序,因此这可能不会做您认为的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM