std::map ——-stl

來源:互聯網
上載者:User

1. map中的元素其實就是一個pair.
2. map的鍵一般不能是指標, 比如int*, char*之類的, 會出錯. 常用的就用string了,int也行.
3. map是個無序的容器, 而vector之類是有序的. 所謂有序無序是指放入的元素並不是按一定順序放進去的, 而是亂序, 隨機存放的(被映射後近似隨機存放).所以遍曆的時候有些效率差別.
4. 判斷有沒有找到該鍵的內容可以這樣:
std::map<std::string,Record>::const_iterator cIter;
cIter = stdfile.m_map.find(s);
if (cIter == stdfile.m_map.end()) // 沒找到就是指向END了  
{
m_vecMoreFile.push_back(s);
}
如果鍵的內容是指標的話, 應該用NULL指標也可以判斷了.
5. 遍曆:
std::map<std::string,Record>::iterator iter;
for (iter = m_map.begin(); iter != m_map.end(); iter++)
{
std::string s = iter->second.filename;
}
由於map內容可以相當一個PAIR, 那就簡單了, 用iter->second就可以取得值了.

可順便轉個其它的幾種用法:
1 標頭檔
#include <map>

2 定義
map<string, int> my_Map;
或者是typedef map<string, int> MY_MAP;
MY_MAP my_Map;

3 插入資料
(1) my_Map["a"] = 1;
(2) my_Map.insert(map<string, int>::value_type("b",2));
(3) my_Map.insert(pair<string,int>("c",3));
(4) my_Map.insert(make_pair("d",4));

4 尋找資料和修改資料
(1) int i = my_Map["a"];
my_Map["a"] = i;
(2) MY_MAP::iterator my_Itr;
my_Itr.find("b");
int j = my_Itr->second;
my_Itr->second = j;
不過注意,鍵本身是不能被修改的,除非刪除。

5 刪除資料
(1) my_Map.erase(my_Itr);
(2) my_Map.erase("c");
還是注意,第一種情況在迭代期間是不能被刪除的,道理和foreach時不能刪除元素一樣。

6 迭代資料
for (my_Itr=my_Map.begin(); my_Itr!=my_Map.end(); ++my_Itr) {}

7 其它方法
my_Map.size() 返回元素數目
my_Map.empty() 判斷是否為空白
my_Map.clear() 清空所有元素
可以直接進行賦值和比較:=, >, >=, <, <=, != 等等

遍曆:

#include<iostream>
#include <map>
using namespace std;

int main(){
 map<int,int>M;
 M[1]=2;
 M[2]=3;
 map<int,int>::iterator iter;
 for (iter = M.begin(); iter != M.end(); iter++)
 {
  cout<<iter->first<<" "<<iter->second<<endl;
 }
 return 0;
}

總結:

       find();

       erase();

       std::map<std::string, int> map;

       map[std::string] = int;

       第一個參數

 

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/feiyun1987/archive/2009/07/07/4328731.aspx

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.