8

我已经编写了以下代码片段,但它似乎不起作用。

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> >*]

谁能帮我吗?

4

4 回答 4

15

循环中至少有三个错误。

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;
}
于 2014-09-01T12:49:12.223 回答
4
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

于 2014-09-01T12:46:00.987 回答
2

C++14 迭代器要简单得多

for (const auto& pair : edges)
{
    std::cout << pair.first;
}

或者

for (const auto& [first, sec] : edges)
{
    std::cout << first;
}
于 2022-01-20T18:08:42.877 回答
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
于 2020-10-06T14:28:13.717 回答