STL中是否有解引用迭代器?

时间:2008-12-09 08:47:43

标签: c++ stl iterator

我想知道在STL中是否有一个迭代器在返回之前取消引用指向的对象。在操作聚合指针的容器时,这可能非常有用。以下是我希望能够做到的一个例子:

#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;

int main()
{
  vector<int*> vec;

  int i = 1;
  int j = 2;
  int k = 3;

  vec.push_back(&i);
  vec.push_back(&j);
  vec.push_back(&k);

  copy(deref_iterator(vec.begin()), 
       deref_iterator(vec.end()), 
       ostream_iterator<int>(cout, " ")); // prints "1 2 3"

  return 0;
}

3 个答案:

答案 0 :(得分:11)

尝试Boost的indirect_iterator

indirect_iterator与它包装的迭代器具有相同的类别。例如,indirect_iterator<int**>是随机访问迭代器。

答案 1 :(得分:4)

如果使用Boost是不可能的,编写自定义迭代器并不是那么难。以下是符合InputIterator要求的“解引用迭代器”的示例:

#include <iterator>

template <typename T>
struct PointedType;

template <typename T>
struct PointedType<T*>
{
  typedef T value_type;
};

template <typename InputIterator>
struct DerefIterator
{
  typedef input_iterator_tag iterator_category;
  typedef typename PointedType<
            typename iterator_traits<InputIterator>::value_type>::value_type
            value_type;
  typedef typename iterator_traits<InputIterator>::difference_type
            difference_type;
  typedef value_type* pointer;
  typedef value_type& reference;

  public:
    explicit DerefIterator(const InputIterator& ii)
      : it(ii) {}

    // Returns the object pointed by the object referenced by it
    reference operator*()  const { return **it; }
    pointer   operator->() const { return *it; }

    DerefIterator& operator++()
    {
        ++it;
        return *this;
    }

    DerefIterator operator++(int)
    {
        DerefIterator tmp = *this;
        ++it;
        return tmp;
    }

    bool equals(const DerefIterator<InputIterator> & di) const
    {
        return di.it == it;
    }

  private:
    InputIterator it;
};

// Equality functions

template <typename InputIterator>
inline bool operator==(const DerefIterator<InputIterator>& di1, 
                       const DerefIterator<InputIterator>& di2)
{
  return di1.equals(di2);
}

template <typename InputIterator>
inline bool operator!=(const DerefIterator<InputIterator>& di1, 
                       const DerefIterator<InputIterator>& di2)
{
  return ! (di1 == di2);
}

//Helper function

template <typename InputIterator>
DerefIterator<InputIterator> deref_iterator(const InputIterator& ii)
{
  return DerefIterator<InputIterator>(ii);
}

答案 2 :(得分:4)

假设您的实际用例比整数指针容器复杂一点!

您可以查看增压ptr容器
http://www.boost.org/doc/libs/1_35_0/libs/ptr_container/doc/reference.html

容器包含动态分配的对象(即指针) 但是对对象的所有访问(直接或通过迭代器)都会返回对象的引用。

#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int main()
{
  boost::ptr_vector<int> vec;

  vec.push_back(new int(1));
  vec.push_back(new int(2));
  vec.push_back(new int(3));

  copy(vec.begin(),vec.end(),
       ostream_iterator<int>(std::cout, " ")); // prints "1 2 3 "

  return 0;
}