此代码用于创建邻接列表(我认为),我想在向量中显示内容
#include<iostream>
#include<vector>
int main() {
int N, M;
fscanf( stdin, "%d%d", &N, &M );
vector< int > graph[ N + 1 ];
int i, u, v;
for ( i = 0; i < M; ++i ) {
fscanf( stdin, "%d%d", &u, &v );
graph[ u ].push_back( v );
}
/*vector<int>iterator::it;
for(it=graph.begin();it!=graph.end();it++)
cout<<*it<<endl;*/
}
我尝试使用代码中注释的行显示输出但它给出了编译错误说:
struct std::iterator used without template parameters
您的帮助将不胜感激....
答案 0 :(得分:0)
您可以在C ++向量中使用索引而不是迭代器。
for(int i=0;i<M;i++)
cout<<graph[i]<<endl;
为了使用迭代器,您必须更正代码,例如:
#include<iostream>
#include<vector>
#include <stdio.h>
using namespace std;
int main() {
int N, M;
fscanf( stdin, "%d%d", &N, &M );
vector<int> graph;
int i, u, v;
for ( i = 0; i < M; ++i ) {
fscanf( stdin, "%d%d", &u, &v );
graph.push_back(u);
graph.push_back(v);
}
vector<int>::iterator it;
for(it=graph.begin();it!=graph.end();it++)
cout<<*it<<endl;
}
你的问题是在你的实例化中创建向量数组。
答案 1 :(得分:0)
#include<iostream>
#include<vector>
int main() {
int N, M;
fscanf( stdin, "%d%d", &N, &M );
std::vector< int > graph[ N + 1 ]; //try to use std::vector<std::vector<int>> - c kind array should have fixed (compilation time) size
int i, u, v;
for ( i = 0; i < M; ++i ) {
fscanf( stdin, "%d%d", &u, &v );
graph[ u ].push_back( v );
}
for ( int i = 0; i <= N; ++i){
std::cout << i << ": ";
for ( std::vector<int>::const_iterator it = graph[i].begin(); it != graph[i].end(); ++it){
std::cout << *it << " ";
}
}
}
//try to use some compilation flag:
//-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wfloat-equa