// 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>}’)|
发布于 2015-03-17 19:53:30
以下是我的第一选择:
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_bound和upper_bound代替equal_range
multimap<string, string> new_map {
map_with_data.lower_bound(string_key),
map_with_data.upper_bound(string_key) };不过,我更喜欢使用equal_range的代码。
演示代码:
#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"));
}结果:
(A, B)
(A, C)https://stackoverflow.com/questions/29108142
复制相似问题