Klausstaler
Klausstaler

Reputation: 41

Get object from vector by value

This seems like a dumb question, but I just want to verify it. If I want to get an object in a vector by value, I can use [], correct? If I want it by reference, I need to use myvector.at(), right? Is there a way to return an item by value? As an example:

std::vector<Foo> foos;
foos.push_back(Foo());
Foo f1 = foos[0]; // by value
Foo f2 = foos.at(0); // by reference

Upvotes: 3

Views: 163

Answers (1)

pmfl
pmfl

Reputation: 2089

That's not correct. Both vector::operator[] and vector::at return references to the object at requested index. In case of vector::at, out of bound errors are implicitly checked and exception is raised. vector::operator[] is similar to an array access.

Upvotes: 2

Related Questions