Reputation: 913
I have the following data structure:
std::vector<std::pair <std::vector<unsigned>,std::vector<unsigned> > > A;
containing the following data:
((7),(108,109)),
((3),(100,101)),
((9),(111,112)),
((5),(102,103)),
((8),(110)),
((8,2,10),(189)),
((5,7),(121)),
((3,9),(119)),
((10),(114)),
((3,5),(115)),
((3,7),(118)),
((3,10),(120)),
((3,4,5),(122))
Now I want to sort only the first vector from the pair of vectors of A in the following manner. For example, my first vector from the pair of vectors of A is:
(7),
(3),
(9),
(5),
(8),
(8,2,10),
(5,7),
(3,9),
(10),
(3,5),
(3,7),
(3,10),
(3,4,5)
I want to sort A according to the first vector, such that after final sorting my vector becomes:
((3),(100,101)),
((5),(102,103)),
((7),(108,109)),
((8),(110)),
((9),(111,112)),
((10),(114)),
((3,5),(115)),
((3,7),(118)),
((3,9),(119)),
((3,10),(120)),
((5,7),(121)),
((3,4,5),(122)),
**((2,8,10),(189)).**
I know how to sort vectors using std:sort, but I am not sure how to sort vectors of vectors using standard c++ functions. I tried to sort them first by size, and then using bublee sort for the final sorting. Is there some other way to sort these vectors in c++ using standard library function. I am running C++ on ubuntu 12.04 using g++ compiler(g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3).
Upvotes: 4
Views: 581
Reputation: 10415
Basically, what you want to do is:
vector
in the pair<>
.vectors
.You have to write your own comparator function for this.
Code:
bool mySort(const pair<vector<unsigned>,vector<unsigned> > &a , const pair<vector<unsigned>,vector<unsigned> > &b)
{
if (a.first.size() == b.first.size()) {
//If sizes of the vectors are equal
//Sort the graph lexicographically.
return std::lexicographical_compare(a.first.begin(),a.first.end(),b.first.begin(),b.first.end());pair<vector<unsigned>,vector<unsigned> > a
} else {
//Sort by size.
return a.first.size() < b.first.size();
}
}
int main()
{
std::vector<std::pair<std::vector<unsigned>,std::vector<unsigned> > > a;
std::sort(a.begin(),a.end(),mySort);
}
Upvotes: 6