C++ map用法


C++ map用法

map是STL的一個關聯容器,它提供一對一(其中關鍵字只能在map中出現一次)的數據處理能力。

  1. 必須引入
#include<map>
  1. map的定義

    map<type1name, type2name> maps;//第一個是鍵的類型,第二個是值的類型

    map<string, int> maps;
    
    //也可以這樣,需要C++11及以后支持
    ::map<int, string> maps = {
    		{2323, "sdff"},
    	{23322, "sdfsf2"},
    	{23211, "sdfsf"}
    	};
    
  2. map容器內元素的訪問

    • 通過下標進行訪問

      如: maps["c"] = 4;

    • 通過迭代器進行訪問

      map可以使用it->first來訪問鍵,使用it->second訪問值

      #include <iostream>
      #include<map>
      #include<string>
      using namespace std;
      
      int main()
      {
      	::map<char, int> maps;
      	maps['d'] = 10;
      	maps['e'] = 20;
      	maps['a'] = 30;
      	maps['b'] = 40;
      
      	for (auto it = maps.begin(); it != maps.end(); it++)
      	{
      		cout << it->first << ":" << it->second << endl;
      	}
      	int c = ::getchar();
      }
      
  3. map的常用用法

    • maps.insert()插入

      #include <iostream>
      #include<map>
      #include<string>
      using namespace std;
      
      int main()
      {
      	// 定義一個map對象
      	::map<int, string> maps;
      	
      	// 用insert函數插入pair
      	maps.insert(::make_pair<int, string>(11, "sdf"));
          
      	auto res = maps.insert(std::make_pair<int, string>(2323, "sdfs"));
      	if (res.second) //插入成功
      	{
      
      	}
      	// 用insert函數插入value_type數據
      	maps.insert(::map<int, string>::value_type(22, "sdf3"));
      
      	maps[123] = "sdfsfsdf";
      	maps[33] = "測試";
      	for (auto it = maps.begin(); it != maps.end(); it++)
      	{
      		cout << it->first << ":" << it->second << endl;
      	}
      	int c = ::getchar();
      }
      
    • maps.find()查找一個元素

      #include <iostream>
      #include<map>
      #include<string>
      using namespace std;
      
      int main()
      {
      	// 定義一個map對象
      	::map<int, string> maps;
      	
      	// 用insert函數插入pair
      	maps.insert(::make_pair<int, string>(11, "sdf"));
      
      	// 用insert函數插入value_type數據
      	maps.insert(::map<int, string>::value_type(22, "sdf3"));
      
      	maps[123] = "sdfsfsdf";
      	maps[33] = "測試";
      	
      	auto f = maps.find(123);
      	if (f != maps.end()) //如果不等於end(),則表示找到了
      	{
      		cout << f->first << ":" << f->second << endl;
      	}
      	int c = ::getchar();
      }
      
    • maps.clear()清空

    • maps.erase()刪除一個元素

      //迭代器刪除
      	auto it = maps.find(123);
      	if (it != maps.end())
      	{
      		maps.erase(it);
      	}
      	
      	//關鍵字刪除
      	int n = maps.erase(123); //如果刪除了返回1,否則返回0
      
      	// 用迭代器范圍刪除
      	maps.erase(maps.begin(), maps.end());
      
    • maps.size()長度

    • maps.begin()返回指向map頭部的迭代器

    • maps.end()返回指向map末尾的迭代器

    • maps.rbegin()返回指向map尾部的逆向迭代器

    • maps.rend()返回指向map頭部的逆向迭代器

    • maps.empty()判斷是否為空

    • maps.swap()交換兩個map


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM