Iterating over a vector of a pair

I wrote the following piece of code, but it doesn't seem to work.

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;
}

      

Throws an error on the line containing the loop. Mistake:

error: no match foroperator<’ 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> >*]

      

Can anyone help me?

+3


source to share


2 answers


There are at least three errors in the loop.

for ( vector < pair<float,pair<int,int>> >::const_iterator it = edges.begin() ; itt != edges.end; it++){
        cout >> it.first;
    }

      

First of all, you should use edges.end()

instead edges.end

. And inside the body there should be

    cout << it->first;

      



instead

    cout >> it.first;

      

To avoid such errors, you can simply write

for ( const pair<float, pair<int,int> > &edge : edges )
{
   std::cout << edge.first;
}

      

+10


source


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 -> 
}

      



Alternatively, you can add a custom comparator for std::sort

+3


source







All Articles