我编写了以下代码片段,但它似乎无法正常工作。
int main(){
int VCount, v1, v2;
pair<float, pair<int,int> > edge;
vector< pair<float, pair<int,int> > > edges;
float w;
cin >> VCount;
while( cin >> v1 ){
cin >> v2 >> w;
edge.first = w;
edge.second.first = v1;
edge.second.second = v2;
edges.push_back(edge);
}
sort(edges.begin(), edges.end());
for ( vector < pair<float,pair<int,int>> >::const_iterator it = edges.begin() ; itt != edges.end; it++){
cout >> it.first;
}
return 0;
}
在包含for循环的行中抛出错误。错误是:
error: no match for ‘operator<’ in ‘it < edges.std::vector<_Tp, _Alloc>::end [with _Tp = std::pair<float, std::pair<int, int> >, _Alloc = std::allocator<std::pair<float, std::pair<int, int> > >, std::vector<_Tp, _Alloc>::const_iterator = __gnu_cxx::__normal_iterator<const std::pair<float, std::pair<int, int> >*, std::vector<std::pair<float, std::pair<int, int> > > >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::const_pointer = const std::pair<float, std::pair<int, int> >*]
任何人都可以帮助我吗?
答案 0 :(得分:10)
循环中至少有三个错误。
for ( vector < pair<float,pair<int,int>> >::const_iterator it = edges.begin() ; itt != edges.end; it++){
cout >> it.first;
}
首先,您必须使用edges.end()
而不是edges.end
。在体内必须有
cout << it->first;
而不是
cout >> it.first;
要逃避此类错误,您只需编写
即可for ( const pair<float, pair<int,int> > &edge : edges )
{
std::cout << edge.first;
}
答案 1 :(得分:3)
for ( vector < pair<float,pair<int,int>> >::const_iterator it = edges.begin() ;
it != edges.end () ; // Use (), and assuming itt was a typo
it++)
{
cout << it->first; // Use ->
}
此外,您可能希望为std::sort
答案 2 :(得分:0)
vector<pair<int,int>>v; // <-- for this one
for(int i=0;i<n;i++){
int x,y;
cin>>x>>y;
v.push_back(make_pair(x,y));
}
sort(v.begin(),v.end(),compare);
for( vector<pair<int,int>>::iterator p=v.begin(); p!=v.end(); p++){
cout<<"Car "<<p->first<<" , "<<p->second<<endl;
}
cout<<endl;
// you can also write like this
for(auto it:v){
cout<<"Car "<<it.first<<" , "<<it.second<<endl;
}
cout<<endl;
// you can also write like this
for(pair<int,int> it2:v){
cout<<"Car "<<it2.first<<" , "<<it2.second<<endl;
}
// now you can code for your one by taking reference from this ok