【问题标题】:Iterating over keys/values of a std::vector and other containers in C++ (MWE)在 C++ (MWE) 中迭代 std::vector 和其他容器的键/值
【发布时间】:2013-07-24 18:23:17
【问题描述】:

我将下面的代码基于以下非常有用的帖子。 Iterating over keys/values 这件事适用于 std::maps (ValueGetter 需要调整)但为什么以下代码也不适用于 std::vector ? 我将代码放在一个类SpecialList 中,然后我可以从不同的容器继承...问题在于最后访问(*it)。我不明白为什么这不能编译? (MWE)

#include <functional>
#include <map>
#include <boost/iterator/transform_iterator.hpp>


class A{
public:
    A(int i):a(i){}
    int a;
};

template <typename T>
struct ValueGetterVec : std::unary_function<typename  std::vector<T>::iterator::value_type,
                                            typename std::vector<T>::iterator::value_type>
{
    const typename std::vector<T>::iterator::value_type& operator()
     (const typename std::vector<T>::iterator::value_type & p) const
    { return p;}
};

class SpecialList : public std::vector< A* > {
    public:

    typedef boost::transform_iterator< ValueGetterVec<iterator>, iterator>     
    value_iterator;

    value_iterator beginValueIterator()
    {
        return value_iterator(this->begin(), ValueGetterVec<iterator>() );
    }

    value_iterator endValueIterator()
    {
        return value_iterator(this->end(), ValueGetterVec<iterator>() );
    }

};

SpecialList list;
list2.push_back(new A(1));
list2.push_back(new A(2));
 {
    SpecialList::value_iterator it;

    for(it = list.beginValueIterator(); it != list.endValueIterator(); it++){
        std::cout << (*it)->a << std::endl;
    }
}

【问题讨论】:

    标签: iterator stdvector boost-iterators


    【解决方案1】:

    发现错误: 代替 ValueGetterVec&lt;iterator&gt; ==> ValueGetterVec&lt;A*&gt;

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多