如何访问整个地图的值

How can I access the values of a map as a whole

本文关键字:地图 何访问 访问      更新时间:2023-10-16

我在 c++ 中有一个这样的映射:

std::map<int, int> points;

我知道我可以访问两个整数,例如在这样的 for 循环中

for (auto map_cntr = points.begin(); map_cntr != points.end(); ++map_cntr)
{
int A = map_cntr->first; // key
int B = map_cntr->second; // val
}

但是我想知道如何从整体上访问每个点(而不是像上面那样的条目(。

我是这样想的:

for (auto map_cntr = points.begin(); map_cntr != points.end(); ++map_cntr)
{
auto whole_point = points.at(map_cntr);
}

实际上,我想对地图条目(点(的整数进行操作,其中包含地图的以下条目(点(的整数。

我想对地图条目(点(的整数进行操作 具有地图的以下条目(点(的整数。

Map不适合容器执行操作,具体取决于要根据以前的元素修改当前元素的元素序列。 例如,对于这些事情,您可以使用向量或对数组。

您可以使用 foreach 循环

std::map<int, int> points;
for (auto pair : points)
{
// pair - is what you need
pair.second;
pair.first;
auto whole_point = pair;
}

我想用地图的以下条目(点(的整数对地图条目(点(的整数进行操作

您不能直接修改映射中 [键,值] 对的键。如果需要这样做,则必须擦除该对并插入另一个。

如果你只需要写入一对的值,或者如果你只需要读取对,你可以使用单个迭代器来完成,如下所示:

// assuming the map contains at least 1 element.
auto it = points.begin();
std::pair<const int, int>* currentPoint = &(*it);
it++;
for (; it != points.end(); ++it) {
auto& nextPoint = *it;
// Read-only: currentPoint->first, nextPoint.first
// Read/write: currentPoint->second, nextPoint.second
currentPoint = &nextPoint;
}

现场示例