Reputation: 6464
I have written following code snippet but it does not seem to be working.
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;
}
It is throwing an error at the line containing for loop. The error is:
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> >*]
Can anyone help me out?
Upvotes: 12
Views: 71416
Reputation: 3706
C++14 iterators are a lot simpler
for (const auto& pair : edges)
{
std::cout << pair.first;
}
C++17 iterators allow deeper access
for (const auto& [first, sec] : edges)
{
std::cout << first;
}
Upvotes: 17
Reputation: 11
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
Upvotes: 1
Reputation: 310950
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 have to use edges.end()
instead of edges.end
. And inside the body there has to be
cout << it->first;
instead of
cout >> it.first;
To escape such errors you could write simply
for ( const pair<float, pair<int,int> > &edge : edges )
{
std::cout << edge.first;
}
Upvotes: 16
Reputation: 47784
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 ->
}
Also, you might want to add a custom comparator for std::sort
Upvotes: 4