I have the following problem:
#include <vector>
#include <iostream>
using namespace std;
class Mat {
public:
typedef vector<float>::size_type size_type;
Mat (size_type k, size_type m)
:data_(k*m){}
inline vector<float> data() const {return data_;}
vector<float> data_;
};
int main(){
Mat f (6, 10);
cout << f.data().size() << " " << f.data().end() - f.data().begin();
}
the output is 60 122.
I thought the entire vector data_ is moved over and over again, but why are begin() end() invalid after this operation?
You are creating a temporary copy of the vector every time you call
data(). You’re then doing iterator arithmetic on iterators pointing to different copies.Change the signature of
data()toconst vector<float>& data()const;