標籤: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來實現鄰接鏈表的筆記