简体   繁体   中英

Pair Value Reading Errors C++

I am getting the compiler error:

error: request for member 'first' in 'list.std::map::operator[], std::less, std::allocator > > >((* &0.0)).std::pair::second', which is of non-class type 'int' int closestX = list[0].second.first;

when trying to read data from a map called list defined and with iterator as:

map<double, pair<int, int>> list;
map<double, pair<int, int>>::iterator it = list.begin();

Members in list are inserted with:

list.insert(it, pair<double, pair<int, int>>(findDistance(posr,posc,j, i), pair<int, int>(j, i)));

I am reading the value from the map using:

int closestX = list[0].second.first;
int closestY = list[0].second.second;

The error seems to indicate that the return type of list[0].second.first is non class type int, but that return type matches perfectly with the value type of closestX, and I have now hit a wall. Assume list[0] is initialized and holds a valid value.

list[0] is already of value type pair<int, int> , not of the iterator type. So you could write

int closestX = list[0].first;
int closestY = list[0].second;

The error seems to indicate that the return type of list[0].second.first is non class type int

No, the error message is telling that list[0].second is not class type so you can not perform .first on it.

Note that std::map::operator[] will return the mapped_type .

Returns a reference to the value that is mapped to a key equivalent to key.

list                 => map<double, pair<int, int>>
list[0]              => pair<int, int>
list[0].second       => int
list[0].second.first => failed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM