如何在c++中使用映射

How to use maps in c++?

本文关键字:映射 c++      更新时间:2023-10-16

我读过c++中的映射,我知道它们的作用,但我不知道如何使用它们。
如果我有n个数字,并且每个数字都分配了一定数量的苹果(例如"x1=5"有4个苹果,"x2=-2"有7个苹果等),我如何对这些数字进行排序并相应地求和苹果的数量,以便x1仍然拥有相同数量的苹果,尽管它在排序数据结构中的位置(我认为是映射)会改变?

我不太明白你的问题,但你可以这样说:

std::map<int, int> map;
map[5] = 4; // x1 = 5 has 4 apples.
map[-2] = 7; // x2 = -2 has 7 apples.
//to find the value of x1 : 
int x1 = map[5];

std::map中的项总是按键排序,所以您不必手动排序。

赋值后的和。

std::map<int,int>::iterator it;
int total = 0;
for(it i = map.begin(); i != map.end(); ++i)
{
    total+=it->second;
}