温故而知新——map

map  :关联式容器,使用时是以属性值对的方式进行使用,例如:<key,value>。map key值唯一,相同的key值插入时只会保留一个。除此之外,map的特点还包括:
1、map底层是一个红黑树,插入记录时根据对记录进行排序。
2、使用find方法进行查找时,时间复杂度为LOG(N)
3、修改记录时根据key值进行修改。
5、可以对key值进行修改,具体的方法是.......不表,一般没必要。

#include <iostream>
#include <map>
using namespace std;
struct classcomp {
	bool operator() (const char& lhs, const char& rhs) const{
		return lhs>=rhs;
	}
};
int main(int argc, char *argv[]) {
	std::map<char,int> foo,bar;
	// map 初始化、交换和遍历
	foo['x']=100;
	foo['y']=200;

	bar['a']=11;
	bar['b']=22;
	bar['c']=33;

	foo.swap(bar);
	std::cout << "foo contains:
";
	for (std::map<char,int>::iterator it=foo.begin(); it!=foo.end(); ++it){
		std::cout << it->first << " => " << it->second << '
';
	}

	std::cout << "bar contains:
";
	for (std::map<char,int>::iterator it=bar.begin(); it!=bar.end(); ++it){
		std::cout << it->first << " => " << it->second << '
';
	}
	//map key使用函数
	std::cout<<"use comp funcation to initialize the map:...."<<std::endl;
	std::map<char,int,classcomp> first;
	first.insert(std::make_pair('a',100));
	first.insert(std::make_pair('y',200));
	for (std::map<char,int>::iterator it=first.begin(); it!=first.end(); ++it){
		std::cout << it->first << " => " << it->second << '
';
	}
	return 0;	
}

 结果如下:

原文地址:https://www.cnblogs.com/newzol/p/6565239.html