2

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?

1
  • +1 for a complete example & well-composed question. Commented May 4, 2012 at 15:23

1 Answer 1

7

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() to const vector<float>& data()const;

Sign up to request clarification or add additional context in comments.

1 Comment

With debugging versions of the library, this should have crashed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.