简体   繁体   English

我无法遍历作为地图值的向量

[英]I'm not able to iterate through a vector which is a value for a map

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

struct Edge{
    int dest, weight;
};

map<int, vector<Edge> > Edges;

void CreateAdj(int src){
    if(!Edges.count(src)){
        vector<Edge> temp;
        Edges[src] = temp;
    }
}
void AddEdge(int src, int dest, int weight){
    struct Edge temp;
    temp.dest = dest;
    temp.weight = weight;

    Edges[src].push_back(temp);

}
int main(){


int Edges; 
cin >> Edges;
int src, dest, weight;
for(int i = 0; i < Edges; i++){
    cin >> src >> dest >> weight;
    CreateAdj(src);
    CreateAdj(dest);
    AddEdge(src, dest, weight);
    AddEdge(dest, src, weight);
}

int x;
cin >> x;
for(vector<Edge>::iterator it = Edges[x].begin(); it!=Edges[x].end(); ++it){
        cout << it->weight;
    }    
}

I was trying to implement Dikjstra's shortest path.我试图实现 Dikjstra 的最短路径。 For the adjacency list, I created a map where int was key to a vector of the struct Edge, where Edge contains the weight and the destination.对于邻接列表,我创建了一个映射,其中 int 是结构 Edge 向量的关键,其中 Edge 包含权重和目的地。

I have actually made some changes from what I had originally written.我实际上对我最初写的内容做了一些更改。 I though the vector may not be getting initiated at all, so I added the CreateAdj function which created a vector and mapped it in Edges.我虽然向量可能根本没有启动,所以我添加了 CreateAdj 函数,该函数创建了一个向量并将其映射到 Edges 中。

But, I'm not able to iterate through the vector of Edges.但是,我无法遍历 Edges 的向量。

Right now, most variables are global.现在,大多数变量都是全局的。 The error is:错误是:

mainI.cpp:43:60: error: subscripted value is not an array, pointer, or vector

for(vector<Edge>::iterator it = Edges[x].begin(); it!=Edges[x].end(); ++it){

When I made Edges local in int, it gave nothing.当我在 int 中将 Edges 设为本地时,它什么也没给出。 No error, no output.没有错误,没有输出。

int Edges; 
cin >> Edges;
for(vector<Edge>::iterator it = Edges[x].begin(); it!=Edges[x].end(); ++it)

"Edges" is just an integer value(not any vector), so you would not be able to iterate over it. “Edges”只是一个整数值(不是任何向量),因此您将无法对其进行迭代。 integer "Edges" in main would override the map "Edges",which is global. main 中的整数“Edges”将覆盖全局的地图“Edges”。

Moreover, you have not defined any Vector of "Edge" called as "Edges" and you are trying( you are meant) to iterate over map "Edges" ,which is int "Edges" in main.此外,您还没有定义任何称为“边缘”的“边缘”向量,并且您正在尝试(您的意思是)迭代地图“边缘”,它是主要的 int“边缘”。

Please rename you variables and data structures carefully,take care of scopes.请仔细重命名变量和数据结构,注意作用域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM