使用c++向量的有向图的邻接列表表示



我是个新人。我遇到了一个c++向量及其迭代器的问题。我尝试过表示有向图的邻接列表,但是失败了。这是我的代码:`

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int Node,Edge,node1,node2,cost;
    vector<int>nodes[100],costs[100];
    vector<int>::iterator it;
    cout<<"Enter numbers of nodes: "<<endl;
    cin>>Node;
    cout<<"Enter numbers of edges: "<<endl;
    cin>>Edge;
    for(int i=0;i<Edge;i++){
        cout<<i+1<<"th edge's Node1: ";
        cin>>node1;
        cout<<i+1<<"th edge's Node2: ";
        cin>>node2;
        cout<<"Cost from "<<node1<<" to"<<node2<<": ";
        cin>>cost;
        cout<<endl;
        nodes[node1].push_back(node2);
        costs[node1].push_back(cost);
    }
    for(it=nodes.begin();it<nodes.end();it++){
        for(int i=0;i<nodes[it].size();i++){
            cout<<nodes[it][i]<<" ";
        }
        cout<<endl;
    }
    return 0;
}

`

您应该告诉我们您遇到的编译错误。

试图立即编译代码显示循环中存在不一致:

for(it=nodes.begin();it<nodes.end();it++)

以及关于CCD_ 1的以下用途。事实上,您在索引中使用it,就好像它是int一样。但您已经将其声明为迭代器:

vector<int>::iterator it;  // you say it is an iterator that iterates through integers in ONE vector

非混合访问和迭代器是两个不同的概念。

解决方案1:使用索引

只需使用类型为int(或更好的size_t)的索引:

...
const size_t maxnodes=100; 
vector<int>nodes[maxnodes],costs[maxnodes];
// + remove the definition of it
...
for(size_t it=0;it<maxnodes;it++) {
...

解决方案2:使用迭代器,但正确

让编译器为迭代器定义正确的类型,然后取消对迭代器的引用(即将其当作指针处理):

// remove the definition of the it at the begin of main
...  // rest of code unchanged except for the loop
for(auto it=begin(nodes);it!=end(nodes);it++){  // attention at the condition
    for(int i=0;i<it->size();i++){
        cout<<(*it)[i]<<" ";
    }
    cout<<endl;
}

这里是的现场演示

解决方案3:使用舒适的范围

忘记迭代器,让编译器为您处理任务:

for(auto& n : nodes) {  // note the &, to get the original element and not a clone of it
    for(int i=0;i<n.size();i++){
        cout<<n[i]<<" ";
    }
    cout <<endl;
}

这里是另一个现场演示。

你会立即意识到,你也可以使用的范围来处理内部循环:

    for(int& target : n) {  // when reading the code outloud, say " in " instead of ":"
        cout<<target<<" ";
    }

最后备注

您应该始终验证用户的数据输入,尤其是当您将其用作索引时,要确保它在有效范围内。

最新更新