gpt4 book ai didi

c++ - 通过一对 key 搜索 multimap

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:30 25 4
gpt4 key购买 nike

我有一个具有结构的 multimap

multimap< pair<int,int>, bool >

我插入了数据,它看起来像这样

I is [0] Int is [5] Bool is [0]
I is [0] Int is [100] Bool is [0]
I is [0] Int is [100] Bool is [0]
I is [1] Int is [100] Bool is [0]
I is [1] Int is [100] Bool is [0]
I is [1] Int is [100] Bool is [0]
I is [2] Int is [5] Bool is [0]
I is [2] Int is [100] Bool is [0]
I is [2] Int is [100] Bool is [0]

我需要能够让 map 的迭代器跳转到下一个 I 而无需遍历其他 I

例如,我只想添加不具有相同I 值的Ints。所以它可以去

add 5 + 100 + 5

因为这些将是第一个具有不同I's 的值。我该怎么做呢?

最佳答案

好吧 - 你可以使用 map lower_bound功能 - 您需要向其应用“下一个”主键 - 请参阅:

auto next_key(int key_first)
{
return std::make_pair(key_first + 1, std::numeric_limits<int>::min());
}

所以下一个要搜索的 key 对是(first + 1, INT_MIN)

所以,循环:

for (auto i = data.begin(); 
i != data.end();
i = data.lower_bound(next_key(i->first.first)))
{
std::cout << i->first.second << std::endl;
}

对于此数据:

std::multimap< std::pair<int,int>, bool > data = {
{{0,5},false},
{{0,100},false},
{{0,100},false},
{{1,100},false},
{{1,100},false},
{{1,100},false},
{{2,5},false},
{{2,100},false},
{{2,100},false}
};

你得到:

5
100
5

关于c++ - 通过一对 key 搜索 multimap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33637278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com