轉 C++ 標準庫 vector list map使用方法

1.List

List將元素按順序儲存在鏈表中. 與 向量(vectors)相比, 它允許快速的插入和刪除,但是隨機訪問卻比較慢.

list對象函數

assign() 給list賦值 
back() 返回最後一個元素 
begin() 返回指向第一個元素的迭代器 
clear() 刪除所有元素 
empty() 如果list是空的則返回true 
end() 返回末尾的迭代器 
erase() 刪除一個元素 
front() 返回第一個元素 
get_allocator() 返回list的配置器 
insert() 插入一個元素到list中 
max_size() 返回list能容納的最大元素數量 
merge() 合併兩個list 
pop_back() 刪除最後一個元素 
pop_front() 刪除第一個元素 
push_back() 在list的末尾添加一個元素 
push_front() 在list的頭部添加一個元素 
rbegin() 返回指向第一個元素的逆向迭代器 
remove() 從list刪除元素 
remove_if() 按指定條件刪除元素 
rend() 指向list末尾的逆向迭代器 
resize() 改變list的大小 
reverse() 把list的元素倒轉 
size() 返回list中的元素個數 
sort() 給list排序 
splice() 合併兩個list 
swap() 交換兩個list 
unique() 刪除list中重複的元素

#include <iostream>
#include <list>
#include <numeric>
#include <algorithm>

using namespace std;

//創建一個list容器的實例LISTINT
typedef list<int> LISTINT;

//創建一個list容器的實例LISTCHAR
typedef list<char> LISTCHAR;

int main(void)
{
    //--------------------------
    //用list容器處理整型數據
    //--------------------------
    //用LISTINT創建一個名爲listOne的list對象
    LISTINT listOne;
    //聲明i爲迭代器
    LISTINT::iterator i;

    //從前面向listOne容器中添加數據
    listOne.push_front (2);
    listOne.push_front (1);

    //從後面向listOne容器中添加數據
    listOne.push_back (3);
    listOne.push_back (4);

    //從前向後顯示listOne中的數據
    cout<<"listOne.begin()--- listOne.end():"<<endl;
    for (i = listOne.begin(); i != listOne.end(); ++i)
        cout << *i << " ";
    cout << endl;

    //從後向後顯示listOne中的數據
    LISTINT::reverse_iterator ir;
    cout<<"listOne.rbegin()---listOne.rend():"<<endl;
    for (ir =listOne.rbegin(); ir!=listOne.rend();ir++) {
        cout << *ir << " ";
    }
    cout << endl;

    //使用STL的accumulate(累加)算法
    int result = accumulate(listOne.begin(), listOne.end(),0);
    cout<<"Sum="<<result<<endl;
    cout<<"------------------"<<endl;

    //--------------------------
    //用list容器處理字符型數據
    //--------------------------

    //用LISTCHAR創建一個名爲listOne的list對象
    LISTCHAR listTwo;
    //聲明i爲迭代器
    LISTCHAR::iterator j;

    //從前面向listTwo容器中添加數據
    listTwo.push_front ('A');
    listTwo.push_front ('B');

    //從後面向listTwo容器中添加數據
    listTwo.push_back ('x');
    listTwo.push_back ('y');

    //從前向後顯示listTwo中的數據
    cout<<"listTwo.begin()---listTwo.end():"<<endl;
    for (j = listTwo.begin(); j != listTwo.end(); ++j)
        cout << char(*j) << " ";
    cout << endl;

    //使用STL的max_element算法求listTwo中的最大元素並顯示
    j=max_element(listTwo.begin(),listTwo.end());
    cout << "The maximum element in listTwo is: "<<char(*j)<<endl;

    return 0;
}

2.vector相關用法

vector的初始化大小和賦初值
(1)vector< 類型 > 標識符 ;
(2)vector< 類型 > 標識符(最大容量) ;
(3)vector< 類型 > 標識符(最大容量,初始所有值);
vector< int > arry(5, 1);
注:定義一個大小爲5的數組,並將每個值都賦爲1;
int i;
for( i = 0; i < 5; i ++ )
cout << arry[i] << " ";
輸出結果爲:1 1 1 1 1
同理定義其他類型的:
vector<char> arry(3, '*');
定義二維的vector:
vector< vector <int>> Arry(10, vector<int>(0));
 
使用數組對C++ Vector進行初始化
int i[10] ={1,2,3,4,5,6,7,78,8} ;  
///第一種   
vector<int> vi(i+1,i+3); ///從第2個元素到第三個元素  
for(vector <int>::interator it = vi.begin() ; 
it != vi.end() ; it++)  
{  
cout << *it <<" " ;   

vector附帶函數

 1.push_back    在數組的最後添加一個數據
 2.pop_back     去掉數組的最後一個數據
 3.at                 得到編號位置的數據
 4.begin            得到數組頭的指針
 5.end              得到數組的最後一個單元+1的指針
 6.front         得到數組頭的引用
 7.back             得到數組的最後一個單元的引用
 8.max_size      得到vector最大可以是多大
 9.capacity        當前vector分配的大小
 10.size            當前使用數據的大小
 11.resize          改變當前使用數據的大小,如果它比當前使用的大,者填充默認值
v.resize(2*v.size, 99) 將v的容量翻倍(並把新元素的值初始化爲99)
 12.reserve       改變當前vecotr所分配空間的大小
 13.erase          刪除指針指向的數據項
 14.clear           清空當前的vector
 15.rbegin         將vector反轉後的開始指針返回(其實就是原來的end-1)
 16.rend           將vector反轉構的結束指針返回(其實就是原來的begin-1)
 17.empty         判斷vector是否爲空
 18.swap          與另一個vector交換數據

 vector 的數據的存入和輸出:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
 
int main(void)
{
   vector<int> num;   // STL中的vector容器
   int element;
 
   // 從標準輸入設備讀入整數, 
   // 直到輸入的是非整型數據爲止
   while (cin >> element)     //ctrl+Z 結束輸入 
      num.push_back(element);
 
   // STL中的排序算法
   sort(vi.begin() , vi.end()); /// 從小到大  
   reverse(vi.begin(),vi.end()) /// 從大道小 
 
 
   // 將排序結果輸出到標準輸出設備
   for (int i = 0; i < num.size(); i ++)
      cout << num[i] << "\n";
   //也可以這樣做
   
      
   system("pause");
   return 0;
}


對於二維vector的定義 

1)定義一個10個vector元素,並對每個vector符值1-10。

#include<stdio.h>
#include<vector>
#include <iostream>
using namespace std;
int main()
{
 int i = 0, j = 0;
//定義一個二維的動態數組,有10行,每一行是一個用一個vector存儲這一行的數據。
所 以每一行的長度是可以變化的。之所以用到vector<int>(0)是對vector初始化,否則不能對vector存入元素。
 vector< vector<int> > Array( 10, vector<int>(0) ); 
for( j = 0; j < 10; j++ )
 {
  for ( i = 0; i < 9; i++ )
  {
   Array[ j ].push_back( i );
  }
 }
 for( j = 0; j < 10; j++ )
 {
  for( i = 0; i < Array[ j ].size(); i++ )
  {
   cout << Array[ j ][ i ] << "  ";
  }
  cout<< endl;
 }
}


定義一個行列都是變化的數組。 

#include<stdio.h>
#include<vector>
#include <iostream>
using namespace std;
void main()
{
 int i = 0, j = 0;
 vector< vector<int> > Array;
 vector< int > line;
 for( j = 0; j < 10; j++ )
 {
  Array.push_back( line );//要對每一個vector初始化,否則不能存入元素。
  for ( i = 0; i < 9; i++ )
  {
   Array[ j ].push_back( i );
  }
 }
 for( j = 0; j < 10; j++ )
 {
  for( i = 0; i < Array[ j ].size(); i++ )
  {
   cout << Array[ j ][ i ] << "  ";
  }
  cout<< endl;

使 用 vettor erase 指定元素

#include <iostream>
#include <vector>

using namespace std;

int   main()
{
    vector<int>   arr;
    arr.push_back(6);
    arr.push_back(8);
    arr.push_back(3);
    arr.push_back(8);

    for(vector<int>::iterator it=arr.begin(); it!=arr.end(); )
    {
        if(* it == 8)
        {
            it = arr.erase(it);
        }
        else
        {
            ++it;
        }
    }

    cout << "After remove 8:\n";

    for(vector<int>::iterator it = arr.begin(); it < arr.end(); ++it)
    {
        cout << * it << " ";
    }
    cout << endl;
    return 0;
}


map用法

1、map簡介

map是一類關聯式容器。它的特點是增加和刪除節點對迭代器的影響很小,除了那個操作節點,對其他的節點都沒有什麼影響。對於迭代器來說,可以修改實值,而不能修改key。

2、map的功能

自動建立Key - value的對應。key 和 value可以是任意你需要的類型。 
根據key值快速查找記錄,查找的複雜度基本是Log(N),如果有1000個記錄,最多查找10次,1,000,000個記錄,最多查找20次。 
快速插入Key - Value 記錄。 
快速刪除記錄 
根據Key 修改value記錄。 
遍歷所有記錄。 
3、使用map

使用map得包含map類所在的頭文件

#include <map> //注意,STL頭文件沒有擴展名.h

map對象是模板類,需要關鍵字和存儲對象兩個模板參數:

std:map<int, string> personnel;

這樣就定義了一個用int作爲索引,並擁有相關聯的指向string的指針.

爲了使用方便,可以對模板類進行一下類型定義,

typedef map<int, CString> UDT_MAP_INT_CSTRING;

UDT_MAP_INT_CSTRING enumMap;

4、在map中插入元素

改變map中的條目非常簡單,因爲map類已經對[]操作符進行了重載

enumMap[1] = "One";

enumMap[2] = "Two";

.....

這樣非常直觀,但存在一個性能的問題。插入2時,先在enumMap中查找主鍵爲2的項,沒發現,然後將一個新的對象插入enumMap,鍵是2,值是一個空字符串,插入完成後,將字符串賦爲"Two"; 該方法會將每個值都賦爲缺省值,然後再賦爲顯示的值,如果元素是類對象,則開銷比較大。我們可以用以下方法來避免開銷:

enumMap.insert(map<int, CString> :: value_type(2, "Two"))

5、查找並獲取map中的元素

下標操作符給出了獲得一個值的最簡單方法:

CString tmp = enumMap[2];

但是,只有當map中有這個鍵的實例時纔對,否則會自動插入一個實例,值爲初始化值。

我們可以使用Find()和Count()方法來發現一個鍵是否存在。

查找map中是否包含某個關鍵字條目用find()方法,傳入的參數是要查找的key,在這裏需要提到的是begin()和end()兩個成員,分別代表map對象中第一個條目和最後一個條目,這兩個數據的類型是iterator.

int nFindKey = 2; //要查找的Key

//定義一個條目變量(實際是指針)

UDT_MAP_INT_CSTRING::iterator it= enumMap.find(nFindKey);

if(it == enumMap.end()) {

//沒找到

}

else {

//找到

}

通過map對象的方法獲取的iterator數據類型是一個std::pair對象,包括兩個數據 iterator->first 和 iterator->second 分別代表關鍵字和存儲的數據

6、從map中刪除元素

移除某個map中某個條目用erase()

該成員方法的定義如下

iterator erase(iterator it); //通過一個條目對象刪除 
iterator erase(iterator first, iterator last); //刪除一個範圍 
size_type erase(const Key& key); //通過關鍵字刪除 
clear()就相當於 enumMap.erase(enumMap.begin(), enumMap.end());

C++ STL map的使用

以下是對C++中STL map的插入,查找,遍歷及刪除的例子:

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

void map_insert(map < string, string > *mapStudent, string index, string x) 
{ 
mapStudent->insert(map < string, string >::value_type(index, x)); 
}

int main(int argc, char **argv) 
{ 
char tmp[32] = ""; 
map < string, string > mapS;

//insert element 
map_insert(&mapS, "192.168.0.128", "xiong"); 
map_insert(&mapS, "192.168.200.3", "feng"); 
map_insert(&mapS, "192.168.200.33", "xiongfeng");

map < string, string >::iterator iter;

cout << "We Have Third Element:" << endl; 
cout << "-----------------------------" << endl;

//find element 
iter = mapS.find("192.168.0.33"); 
if (iter != mapS.end()) { 
cout << "find the elememt" << endl; 
cout << "It is:" << iter->second << endl; 
} else { 
cout << "not find the element" << endl; 
}

//see element 
for (iter = mapS.begin(); iter != mapS.end(); iter ) {

cout << "| " << iter->first << " | " << iter-> 
second << " |" << endl;

} 
cout << "-----------------------------" << endl;

map_insert(&mapS, "192.168.30.23", "xf");

cout << "After We Insert One Element:" << endl; 
cout << "-----------------------------" << endl; 
for (iter = mapS.begin(); iter != mapS.end(); iter ) {

cout << "| " << iter->first << " | " << iter-> 
second << " |" << endl; 
}

cout << "-----------------------------" << endl;

//delete element 
iter = mapS.find("192.168.200.33"); 
if (iter != mapS.end()) { 
cout << "find the element:" << iter->first << endl; 
cout << "delete element:" << iter->first << endl; 
cout << "=================================" << endl; 
mapS.erase(iter); 
} else { 
cout << "not find the element" << endl; 
} 
for (iter = mapS.begin(); iter != mapS.end(); iter ) {

cout << "| " << iter->first << " | " << iter-> 
second << " |" << endl;

} 
cout << "=================================" << endl;

return 0; 
}

轉載自:https://my.oschina.net/gddyl/blog/113744


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章