I have an object that contains a vector. I want to iterate over that object, getting hold of the elements in that vector. This is fine as long as I'm only reading. Writing is another story.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
#include <vector>
using std::vector;
class data_vector {
private:
vector<float> coefficients;
public:
data_vector() : coefficients( vector<float>(5,1.) ) {};
void trace() { cout << coefficients[0] << endl; };
private:
int seek{0};
public:
data_vector &begin() { seek = 0; return *this; };
data_vector &end() { seek = coefficients.size(); return *this; };
bool operator!=( const data_vector &test ) const {
return seek<test.seek; };
void operator++() { seek++; };
float &operator*() { return coefficients.at(seek); };
};
int main() {
data_vector
outdata;
outdata.trace();
for ( float &d : outdata )
d = 2. ;
outdata.trace();
return 0;
}
I thought the loop would alter the object 1. I'm using a reference to the iterator object 2. the dereference function yields a reference, but it doesn't:
clang++ -std=c++17 -o tester test.cxx && ./tester
1
1