简体   繁体   English

我如何才能整体访问地图的值

[英]How can I access the values of a map as a whole

I have a map in c++ like this: 我在C ++中有一张这样的地图:

std::map<int, int> points;

I know that I can access the two integers for example in a for loop like this 我知道我可以在这样的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
        }

But I want to know how I can access every point as a whole (and not it's entries like above). 但是我想知道我如何才能整体访问每个点(而不是上面的条目)。

I thought something like this: 我认为是这样的:

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

Actually, I want to do operations on integers of a entry (point) of the map with integers of the following entry (point) of the map. 实际上,我想对地图的一个条目(点)的整数进行操作,并与地图的以下条目(点)的整数进行操作。

I want to do operations on integers of a entry (point) of the map with integers of the following entry (point) of the map. 我想用地图的以下项(点)的整数对地图的项(点)的整数进行操作。

Map is not suited container to perform operation depending on the sequence of elements where you want to modify current element according to previous ones. Map不适合根据您要根据先前元素修改当前元素的元素顺序来执行操作的容器。 For those things you can use a vector or an array of pairs for instance. 对于这些事情,您可以使用向量或成对数组。

You can use foreach loop 您可以使用foreach循环

std::map<int, int> points;

for (auto pair : points)
{
    // pair - is what you need
    pair.second;
    pair.first;
    auto whole_point = pair;

}

I want to do operations on integers of a entry (point) of the map with integers of the following entry (point) of the map 我想使用地图的以下条目(点)的整数对地图的条目(点)的整数进行操作

You can't directly modify the key of a [key,value] pair in a map. 您无法直接修改地图中[key,value]对的键​​。 If you need to do so, you have to erase the pair and insert another one. 如果需要,您必须擦除该对并插入另一对。

If you only need to write the value of a pair, or if you only need to read the pairs, you can do it with a single iterator, like this: 如果只需要写一个对的值,或者只需要读取对,则可以使用单个迭代器来完成,如下所示:

// 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;
}

Live example 现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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