Tutorial :C++: First element of vector “corrupting”



Question:

I have a class (foo) that contains a vector.

If i try iterating over the elements in the vector like so:

for(vector<random>::iterator it = foo.getVector().begin();          it != foo.getVector().end(); ++it) {    cout << (*it) << endl;    }  

The first element is always corrupted and returns garbage data.

However, if do something like:

 vector<random> v = foo.getVector();   for(vector<random>::iterator it = v.begin();              it != v.end(); ++it) {        cout << (*it) << endl;     }  

Everything appears to be working fine. Is there a "gotcha" that I do not know about?

I've also tried doing cout << foo.getVector()[0] << endl; outside of the loop but that appears to be working ok.

Thanks.

Edit:

Here's my header file:

#ifndef HITS  #define HITS    #include <vector>  #include "wrappers.h"    class Hits {        public:          Hits();          std::vector<word_idx_value> getVector() {return speech_hits;}          const std::vector<word_idx_value> getVector() const {return speech_hits;}          void add(const word_idx_value&);          Hits &operator+=(const Hits&);      private:          std::vector<word_idx_value> speech_hits;  };    





        
Previous
Next Post »