Reputation: 5553
With respect to the following code segment:
struct Pair{
string name;
double val;
}
vector<Pair> pairs;
double& value(const string& s)
{
for (int i=0; i<pairs.size(); i++)
if (s==pairs[i].name) return pairs[i].val;
Pair p = {s,0};
pairs.push_back(p);
return pairs[pairs.size()-1].val;
}
The author states
For a given argument string, value() finds the corresponding floating-point object (not the value of the corresponding floating-point object); it then returns a reference to it.
What's the differce between "floating-point object" and its value?
Upvotes: 2
Views: 106
Reputation: 56956
The function value
doesn't return a number (eg. 3.1415 or 42) but a reference to a variable (the technical term is lvalue). It returns a handle for you to access the actual object storing the number (in particular you can read the number), and even modify it.
To wit:
value("foo") = 42.314;
will modify the Pair
object whose name
field is "foo"
.
If now you do
std::cout << value("foo") << "\n";
it will print 42.314
.
Upvotes: 0
Reputation: 49251
The object is the actual memory block that contains the value.
So if you get the reference you could replace its value, which is still stored in the original vector.
And of course if you'd just get the value (by changing the return value to double without the &) you wouldn't be able to change the actual value in the vector.
Upvotes: 5
Reputation: 9029
double& value(const string& s)
<- it's hidden here. &
marks reference, not the value of variable (if you don't know what reference is - it's like const, not-null pointer).
Upvotes: 1