Does pair.first return a reference to the first value?

12,292

Solution 1

first is not a function, it is an object itself, a data member of struct pair. The name of an object is an lvalue, equivalent to a reference.

"Lvalue" is a language term denoting something that can go on the left-hand side of an assignment, i.e. a value can be assigned to it, or it has a meaningful address in memory.

The result of a conditional expression is an lvalue if both its alternatives are lvalues of the same type.

For example,

pair< int, int > p;
flag? p.first : p.second = 34; // ok

flag? p.first : 3 = 15; // error: 3 is not an lvalue; 3 = 15 is nonsense

pair< int, short > q;
flag? q.first : q.second = 12; // error: different types

Note, the opposite of "lvalue" is "rvalue," for right-hand side of an assignment. These terms are borrowed from the C language.

Remember: the lvalue of an expression is where it is stored, the rvalue is its content. Which of these an expression meaningfully has decide its value category.

Solution 2

For starters, I think that what you are reading as "needs 1-value" is actually "needs lvalue" (L-value), which in C++ is an expression that (intuitively) represents an actual object rather than something that is a value.

Next, pair.first and pair.second don't yield references to pair.first and pair.second, but rather are the first and second data members inside of pair. You can obtain references to them, but they themselves are not references.

Without seeing the actual code, though, I can't offer any more targeted advice.

Hope this helps!

Share:
12,292
keyert
Author by

keyert

Updated on June 04, 2022

Comments

  • keyert
    keyert almost 2 years

    In the C++ standard library, there is an object called the pair. Pair.first and Pair.second return the first and second values of the pair object, respectively. I want to increment the first value by one under a conditional (my pair is a pair). It's throwing "needs 1-value" when I try to do this. This could be because somewhere along the way I am not passing in a value by reference, but it could also be that .first does not return the first value of the pair by reference. Does anyone know if it does?