Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a dereference_iterator in the STL?

Tags:

c++

iterator

stl

I was wondering if there is an iterator in the STL that dereferences the object pointed before returning it. This could be very useful when manipulating containers aggregating pointers. Here's an example of what I would like to be able to do:

#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;
}
like image 641
Luc Touraille Avatar asked Dec 09 '08 08:12

Luc Touraille


2 Answers

Try Boost's indirect_iterator.

An indirect_iterator has the same category as the iterator it is wrapping. For example, an indirect_iterator<int**> is a random access iterator.

like image 160
James Hopkin Avatar answered Oct 13 '22 01:10

James Hopkin


Assuming your actual use case is a bit more complex than a container of integer pointers!

You could check out the boost ptr containers
http://www.boost.org/doc/libs/1_35_0/libs/ptr_container/doc/reference.html

The containers contain dynamically allocated objects (ie pointers).
But all access to the objects (direct or via iterator) returns a reference to the object.

#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;
}
like image 44
Martin York Avatar answered Oct 13 '22 00:10

Martin York