用std::map制作映射表 将重复国家去除,怎么实现呀!主要应用于制作专题图数据冗余
对于 rb_tree 的数据结构,我们有几个问题:
1. 为什么 rb_tree 没有包含 allocator 成员?
2. 为什么 iterator 可以 pass-by-value?
3. 为什么 header 要有 left 成员,并指向 left most 节点?
4. 为什么 header 要有 right 成员,并指向 right most 节点?
5. 为什么 header 要有 color 成员,并且固定是红色?
6. 为什么要分为 rb_tree_node 和 rb_tree_node_base 两层结构,引入 node 基类的目的是什么?
7. 为什么 iterator 的递增递减是分摊(amortized)常数时间?
8. 为什么 muduo 网络库的 Poller 要用 std::map<int, Channel*> 来管理文件描述符?
我认为,在面试的时候能把上面前 7 个问题答得头头是道,足以说明对 STL 的 map/set 掌握得很好。下面一一解答。
问题回答:
要用C++的std::map来制作映射表,并且去除重复的国家,可以按照以下步骤:
std::map<std::string, int> country_map;
这里的std::string表示国家名称的数据类型,int表示对应的值的数据类型,可以根据实际情况调整。
country_map.insert(std::make_pair("China", 100));
country_map["USA"] = 80;
这里的值可以是任意类型,比如数字、字符串等等。
if(country_map.count("China")) {
//已经存在,进行修改操作
country_map["China"] = 120;
} else {
//不存在,添加新的记录
country_map.insert(std::make_pair("China", 120));
}
这里的count函数返回指定键的数量,如果为0表示不存在,否则表示存在。
for(std::map<std::string, int>::iterator it = country_map.begin(); it != country_map.end(); it++) {
std::cout << it->first << ": " << it->second << std::endl;
}
这里的iterator类型需要根据map对象的键和值类型进行调整。
auto it = std::find_if(country_map.begin(), country_map.end(), [](std::pair<std::string, int> const& p) {
return p.second > 90;
});
if(it != country_map.end()) {
std::cout << "Found " << it->first << " with value " << it->second << std::endl;
}
这里的lambda表达式指定了比较的规则,可以根据实际情况自定义。
country_map.clear();
以上是使用std::map制作映射表并去除重复国家的方法,可以根据实际情况进行调整和优化。