天天看点

C++ Map遍历和插入、其他API

Map遍历和插入

    //有序

    //关联

    //映射

    //键值唯一

    //分配器allocator

map<int, string> MapHello; 
    map<int, string> MapHello1{ {1,"ddd"},{3,"asd"} };

	string ccc = MapHello[3]; //红黑平衡二叉树
	MapHello[3] = "Hello";

    MapHello.insert(make_pair(1, "CCCC"));
	MapHello.insert(pair<int, string>(2, "CCCC")); //插入
	MapHello.insert(map<int, string>::value_type(34, "CCCC"));
    MapHello.insert({ {1,"ddd"},{3,"asd"} });

	//for (const pair<int, string>& Tmp : MapHello)
	for (auto& Tmp : MapHello) //遍历
	{
		if (Tmp.first == 3)
		{
			cout << Tmp.second << endl;
			break;
		}
	}

	//遍历
	for (map<int, string>::iterator It = MapHello.begin(); It != MapHello.end(); It++)
	{
		if (It->first == 3)
		{
			cout << It->second << endl;
			break;
		}
	}

	cout << MapHello[3] << endl;
	cout << MapHello[1] << endl;
           

其他API

string ccc = MapHello.at(8);

	auto c1 = MapHello.equal_range(8); //pair

	MapHello.size();

	MapHello.erase(8);

	auto iterator111 = MapHello.find(8);

	//是否包含这个元素
	if (MapHello.count(7)) //判断是否有
	{
		MapHello.insert(make_pair(7, "IIII"));
	}
           

继续阅读