首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将multimap的子集复制到新的multimap中

将multimap的子集复制到新的multimap中
EN

Stack Overflow用户
提问于 2015-03-17 19:35:54
回答 1查看 1.6K关注 0票数 1
代码语言:javascript
复制
// this has data from elsewhere, just showing its the same type
multimap<string,string> map_with_data;
string string_key = "some_string";

// not working:
multimap<string,string> new_map;

new_map = map_with_data[string_key];

我希望返回一个只带键string_key的密钥对的multimap。做这个的正确方法是什么,或者这种直接复制的方法甚至是可能的?

我得到了:error: no match for ‘operator[]’ (operand types are ‘std::multimap<std::basic_string<char>, std::basic_string<char> >’ and ‘std::string {aka std::basic_string<char>}’)|

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-17 19:53:30

以下是我的第一选择:

代码语言:javascript
复制
auto r = map_with_data.equal_range(string_key);

multimap<string, string> new_map(r.first, r.second);

这将使用指定的键查找现有映射中的所有项,然后从这些迭代器初始化新映射。如果在现有的映射中没有带有该键的项,您将得到map_with_data.end()和r.first,因此您的new_map最终将为空(正如您可能预期的那样)。

如果你真的愿意的话,你可以用lower_boundupper_bound代替equal_range

代码语言:javascript
复制
multimap<string, string> new_map {
    map_with_data.lower_bound(string_key), 
    map_with_data.upper_bound(string_key) };

不过,我更喜欢使用equal_range的代码。

演示代码:

代码语言:javascript
复制
#include <map>
#include <string>
#include <iostream>
#include <iterator>

using namespace std;

namespace std {
    ostream &operator<<(ostream &os, pair<string, string> const &p) {
        return os << "(" << p.first << ", " << p.second << ")";
    }
}

int main() {

    multimap<string, string> map_with_data {
        {"A", "B"},
        {"A", "C"},
        {"B", "B"},
        {"B", "C"}
    };

    auto r = map_with_data.equal_range("A");

    multimap<string, string> new_map(r.first, r.second);

    copy(new_map.begin(), new_map.end(), 
        ostream_iterator<pair<string, string>>(std::cout, "\n"));
}

结果:

代码语言:javascript
复制
(A, B)
(A, C)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29108142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档