Humam Helfawi
Humam Helfawi

Reputation: 20274

calling begin and end on vector returned by member function

I have this class:

class foo{
public:
    const std::vector<int> get_v() const{
         return v_;
    }
private:
    std::vector<int> v_
};

Can I use it like this?

int main(){
    foo f;
    some_non_inplace_std_function(f.get_v().cbegin(),f.get_v().cend());
}

Will the first f.get_v() point to the same vector of the second f.get_v() ?

Upvotes: 0

Views: 100

Answers (4)

Rishi
Rishi

Reputation: 1395

const std::vector<int> get_v() const{
     return v_;
}

You are returning a copy of the vector v_. You may want to return reference to the v_

const std::vector<int>& get_v() const{
     return v_;
}

Upvotes: 4

Chen OT
Chen OT

Reputation: 3614

You should change to return reference like

const std::vector<int>& get_v() const {
     return v_;
}

Upvotes: 2

juanchopanza
juanchopanza

Reputation: 227438

get_v() returns by value, so each time you call it you get a new copy of the original. That means that the begin and end iterators obtained from different calls to get_v() do not belong to the same sequence.

If you really intend to return by value, then you need to copy the result in order to use the iterator pair:

auto v = f.get_v();
some_non_inplace_std_function(v.cbegin(), v.cend());

Otherwise, you can return by reference, or return iterators or an iterator range object directly from foo.

const std::vector<int>& get_v() const{ ... }

or

struct foo{
    std::vector<int>::const_iterator begin() const{ return v_.begin(); }
    std::vector<int>::const_iterator end() const{ return v_.end(); }
 ....
private:
    std::vector<int> v_
};

Upvotes: 6

MikeMB
MikeMB

Reputation: 21156

No you making a new copy each time you are calling get_v. To solve this you could return a const reference:

 const std::vector<int>& get_v() const { return v_; }

Upvotes: 3

Related Questions