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;
}
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With