【问题标题】:Searching through a multimap with a pair for a key使用一对键在多重映射中搜索
【发布时间】:2016-02-11 18:15:26
【问题描述】:

我有一个具有结构的多图

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]

我需要能够有一个迭代器,以便地图跳转到下一个 I,而无需遍历其他 I

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

加 5 + 100 + 5

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

【问题讨论】:

  • 考虑将您的数据定义更改为std::map&lt;int,std::multimap&lt;int,bool&gt;&gt;。这样你的任务就很简单了

标签: c++ stl iterator multimap


【解决方案1】:

嗯 - 你可以使用 map lower_bound 函数 - 你需要应用到它的“下一个”主键 - 见:

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

所以下一个要搜索的密钥对是(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

【讨论】:

    猜你喜欢
    • 2014-10-26
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    相关资源
    最近更新 更多