-4

I'm trying to enter data as a list of integer pairs, sort pairs by the first pair value, then the second value, and then output the sorted pair values;

#include <list>
#include <iostream>
#include <algorithm>
//experiment with list sort of pair
using namespace std;
int main (int argc, char* argv[]){
    int N,x,y;
    list< pair<int,int> >::iterator it;
    list< pair<int,int> > a; 
    cout<<" number of pairs?"<<endl;
    cin >> N;
    cout<<"enter pairs, with space between 1st and second of pair"<<endl;
    for(int i=0;i<N;++i) {
        cin >> x >> y;
        a.push_back(make_pair(x,y)); 
    }
    cout<<"sorted pairs;"<<endl;
    sort(a.begin(),a.end()); // Sorts first the x, then the y-coordinate
    for (it=a.begin(); it!=a.end(); ++it) {
        cout << " " << (*it).first << " " << (*it).second << endl;
    }
    return 0;
}
  • 5
    What's wrong with your code? – chris Nov 09 '13 at 04:04
  • 1
    By the way, it would work with a vector, and you should probably be using one anyway. – chris Nov 09 '13 at 04:06
  • I have a version with vector, and it worked. I was looking at using list as I was thinking of an application where I would be doing insertions and deletions. I thought list would be more efficient than vector for this. – Stuart Anderson Nov 09 '13 at 05:08

1 Answers1

5

std::sort, from the <algorithm> header, only works with random-access iterators, which std::list does not have. But std::list does have its own sort member function, which uses a different algorithm.

a.sort();
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274