C ++: the first element of vector "corruption"

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

If I try iterating over elements in a vector like this:

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

}

The first element is always corrupt and returns garbage data.

However, if something like:

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

 }

Everything is working fine. Is there a "gotcha" that I don’t know about?

I also tried to do cout <foo.getVector () [0] <enp; out of loop, but it seems to be working fine.

Thanks.

Edit:

Here is 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;
};

#endif
+3
source share
5 answers
for(vector<random>::iterator it = foo.getVector().begin();

, foo.getVector(), , ; foo.getVector().begin();. , .

foo.getVector(); v (v = foo.getVector();), v, . , v .

+9

getVector() . getVector (begin() end()) , begin() end() . . != undefined.

+7

getVector() , , , . , , . - const.

+2

getVector(). .

class Hits
{
    public:
    std::vector<word_idx_value>&   getVector() {return speech_hits;}
    //                         ^
    //                      Add the & to return by reference.

    // You may also want a const version at some point.
    std::vector<word_idx_value> const&   getVector() const {return speech_hits;}

, . . begin() , , , , begin(), .

+1

getVector, : std::vector <word_idx_value > & getVector() {return speech_hits;}

0

Source: https://habr.com/ru/post/1708239/


All Articles