關於如何利用vector來實現鄰接鏈表的筆記

來源:互聯網
上載者:User

標籤:style   blog   io   color   ar   os   使用   for   sp   

使用標準模板庫(STL)中的標準模板 std::vector,可以讓我快速的使用鄰接鏈表。一些基本的用法如下:

 

#include <iostream>#include <stdio.h>     #include <vector>using namespace std;struct Edge{      //定義結構體,用來表示一條邊    int nextNode; //下一個結點的編號    int cost;     //該邊的權重};int main()   //利用vector來實現鄰接鏈表中的應用{    vector<Edge> edge[10];  //定義一個數組,數組中的元素是向量    for(int i=0;i<=9;i++){  //初始化        edge[i].clear();    }    Edge temp1;    temp1.nextNode=3;    temp1.cost=39;    edge[1].push_back(temp1);   //將該邊加入到結點1的單鏈表中    Edge temp2;    temp2.nextNode=4;    temp2.cost=24;    edge[1].push_back(temp2);   //將該邊加入到結點1的單鏈表中    Edge temp3;    temp3.nextNode=5;    temp3.cost=16;    edge[1].push_back(temp3);   //將該邊加入到結點1的單鏈表中    edge[1].erase(edge[1].begin()+2,edge[1].begin()+3);  //刪除與結點1相鄰的結點,                                                         //參數為(vector.begin()+i,vector.begin()+i+1)                                                         //i為要刪除的結點編號(相當於數組下標)                                                         //比如此時要刪除與結點1相鄰的第3個結點(從0開始)    for(int i=0;i<=edge[1].size()-1;i++){   //遍曆與結點1相鄰的所有結點        int nextNode=edge[1][i].nextNode;   //到這兒就相當於2維數組了        int cost=edge[1][i].cost;        printf("%d %d\n",nextNode,cost);    }    return 0;}

 

關於如何利用vector來實現鄰接鏈表的筆記

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.