I have a class, for example, Point
:
class Point {
public:
double x, y;
};
And I have some container, for example PointCloud
, that wraps inside std::vector<Point*>
:
class PointCloud {
public:
typedef std::vector<Point*>::const_iterator iterator;
iterator begin();
iterator end();
private:
std::vector<Point*> _point
};
Now I can use my class this way:
PointCloud cloud;
for(auto point : cloud) {
std::cout << point->x << std::endl;
}
I want to implement begin()
and end()
so my iterators return references instead of pointers and I could write my code that way:
PointCloud cloud;
for (auto point : cloud) {
std::cout << point.x << std::endl;
}
Note: operator .
instead of ->
operator
I have some reasons to do this thing:
compatibility: Firstly I write my class with
std::vector<Point> _point
and if I change my mind in the future and replace it withstd::vector<Point*> _point
and users of my class won't need to change something in their code.it's just safer to work with references.
There is no need to type
->
instead of.
.
I work with references instead of pointers.
Is it a right thing to do? An if yes, what would be the best way to implement it?
Finally I found the correct solution: boost::indirect_iterator http://www.boost.org/doc/libs/1_57_0/libs/iterator/doc/indirect_iterator.html
#include <memory>
#include <vector>
#include <iostream>
#include <boost/iterator/indirect_iterator.hpp>
class Point {
public:
Point(double x, double y) : x(x), y(y) {};
double x, y;
};
class PointCloud {
public:
using point_vector = std::vector<std::unique_ptr<Point>>;
using const_iterator = boost::indirect_iterator<point_vector::const_iterator>;
const_iterator begin() { return _points.begin(); }
const_iterator end() { return _points.end(); }
void insert(double x, double y) { _points.emplace_back(new Point(x, y)); }
private:
point_vector _points;
};
int main()
{
PointCloud points;
points.insert(2, 3);
points.insert(4, 5);
for (auto &point : points)
std::cout << point.x << ' ' << point.y << std::endl;
return 0;
}