对值读取错误 C++

Pair Value Reading Errors C++

我收到编译器错误:

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;

当尝试从名为 list defined 的映射中读取数据时,迭代器为:

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

列表中的成员插入:

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

我正在使用以下方法从地图中读取值:

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

报错好像是list[0].second.first的return类型不是class类型的int,但是return类型和closestX的值类型完美匹配,我现在碰壁了。假设 list[0] 已初始化并包含有效值。

list[0] 已经是值类型 pair<int, int>,不是迭代器类型。所以你可以写

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

不,错误消息告诉您 list[0].second 不是 class 类型,因此您无法对其执行 .first

请注意 std::map::operator[] 将 return 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