6

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.

2
  • cannot convert from 'const float' to 'float &' from Visual C++
    – jira
    Dec 20, 2013 at 20:26
  • 2
    Use const T&. Your method is const, and therefore _vector is const, and at() returns const T&
    – user3458
    Dec 20, 2013 at 20:26

2 Answers 2

8

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).

4
  • Thanks. Unfortunately it doesn't make a difference. Still the same error.
    – jira
    Dec 20, 2013 at 20:41
  • @jira This may have to do with the compiler then: the code compiles perfectly with Gnu's compiler (see link to the demo). If that's the compiler, am not sure how to get around that without a hack. Another suggestion might be changing the return type to T from T& - it shouldn't make a difference for floats and other primitives. Dec 20, 2013 at 20:44
  • 1
    @jira If you are still getting the error after this change, you are likely trying to change the result: t.GetElement(0) += 1. If you want to be able to modify the elements, you need a non-const overload of this function as well. Dec 20, 2013 at 20:51
  • Looks like I must have a load of these const related problems in my code. Whenever I change something some other error pops up somewhere else ... Anyway, I'm going to accept this answer as it addresses my original question
    – jira
    Dec 20, 2013 at 20:56
5

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.