[英]sorting vector of pair of vectors
我有以下形式的数据:
vector<pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > > A;
5,((0,9),(1,2))
6, ((0),(8,9))
10,((1,10,15,16),(1,2))
2,((0,2,10),(8,9))
3,((0,1,2),(1,2))
1,((3,4,7),(1,2))
7,((3,4,6),(8,9))
11,((1,51,9,3,2,4,6),(8,9))
这样排序后的输出显示为:
3,((0,1,2),(1,2))
5,((0,9),(1,2))
1,((3,4,7),(1,2))
10,((1,10,15,16),(1,2))
6, ((0),(8,9))
7,((3,4,6),(8,9))
2,((0,2,10),(8,9))
11,((1,51,9,3,2,4,6),(8,9))
那就是我想按向量A的第二对进行排序。这样我就将元素对按第二对向量AEg的第二对向量进行分组,这里我将包含(1,2)和(8 ,9)。 然后,我想根据以下(开始,结束)范围对第二对向量A的第一对向量进行排序。 也就是说,其向量位于(0,0)之间的元素出现在其向量位于(0,1)之间的元素之前。 例如,示例(0,1,2)出现在(0,9)之前,因为它的元素位于(0,2)之间,该元素以上述顺序出现在(0,9)之前...对于其他元素,类似地:
(Start,End)
(0,0),
(0,1),
(1,1),
(0,2),
(1,2),
(2,2),
(0,3),
(1,3),
(2,3),
(3,3),
(0,4),
(1,4),
(2,4),
(3,4),
(4,4),
(0,5),
(1,5),
(2,5),
(3,5),
(4,5),
(5,5),
(0,6),
(1,6),
(2,6),
(3,6),
(4,6),
(5,6),
(6,6),
(0,7),
(1,7),
(2,7),
(3,7),
(4,7),
(5,7),
(6,7),
(7,7),
(0,8),
(1,8),
(2,8),
(3,8),
(4,8),
(5,8),
(6,8),
(7,8),
(8,8),
.
.
(n,n)
我正在使用g ++(Ubuntu / Linaro 4.6.3-1ubuntu5)4.6.3运行C ++。
我尝试通过以下方法解决此问题:首先,我将(1,2)和(8,9)之类的元素组合在一起。 然后,我将这些范围存储在另一个数据结构中。 然后,我遍历这些范围并尝试查看行是否落在所述范围内
您可能具有特别复杂的数据结构,并且要在其上定义超特定且任意的顺序,但是没关系。 关于std::sort
是它完全可以容纳:
std::sort(A.begin(), A.end(), MyComparator);
您只需要编写以下内容:
typedef pair<unsigned, pair<vector<unsigned>, vector<unsigned> > > Elem;
bool MyComparator(const Elem& a, const Elem& b) {
// return true if a should go before b in the sort
// step 1 is apparently to do a vector comparison
for (size_t i = 0; i < a.second.second.size(); ++i) {
if (i == b.second.second.size()) {
return false;
}
else if (a[i] < b[i]) {
return true;
}
else if (a[i] > b[i]) {
return false;
}
}
if (a.second.second.size() < b.second.second.size()) {
return true;
}
// if we got here, the two vectors compare equal
// so onto the next steps 2, 3, ...
// etc.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.