jira
jira

Reputation: 3944

function returning reference to a vector element

I cannot figure out how to return a reference to a vector element. The [] and at() are returning reference, no?

But when I try the following, it won't compile.

I'm using Visual C++ and it gives cannot convert from 'const float' to 'float & error.

T& GetElement(size_t x) const {
    return _vector.at(x);
}

GetElement is a method, and _vector is a member variable.

Upvotes: 7

Views: 12431

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

This does not compile because you are trying to return a non-constant reference to an element of the vector, which is itself const.

The reason the vector is const is that your member function is declared const:

T& GetElement(size_t x) const // <<== Here

This const-ness marker gets propagated to all members, including the _vector.

To fix this problem, add const to the type of the reference being returned (demo).

Upvotes: 9

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

You haven't shown your error, but as a guess, it looks like _vector is a member (from the _ prefix you've given it) and you're in a const member function, so at will return a const reference. So you probably need:

const T& GetElement(size_t x) const {
    return _vector.at(x);
}

Upvotes: 5

Related Questions