This is a simplified instance of actual code. The goal was to provide access to container elements via range-based loops BUT have the elements changed on-the-fly (here ints are squared) without exposing the change.
The code works but seems overly complicated and unreadable. What simplification did I miss?
#include <vector>
#include <iostream>
using ivec_t = std::vector<int>;
class A {
ivec_t vec;
public:
A(const ivec_t& v) : vec(v) {}
class sq_class {
class iter {
ivec_t::iterator ivit;
public:
iter(ivec_t::iterator the_ivit) : ivit(the_ivit) {}
bool operator!=(const iter& other) { return ivit != other.ivit; }
iter& operator++() { ++ivit; return *this; }
int operator*() { return (*ivit)*(*ivit); } // <-------------------
};
ivec_t ivec;
public:
sq_class(ivec_t& the_ivec) : ivec(the_ivec) {}
iter begin() { return iter(ivec.begin()); }
iter end() { return iter(ivec.end()); }
};
sq_class squares() { return sq_class(vec); }
};
main()
{
A a({1,2,4});
// expected output: 1, 4, 16,
for (auto item : a.squares())
std::cerr << item << ", ";
std::cerr << "\n";
}
Aucun commentaire:
Enregistrer un commentaire