[英]use std::stable_partition and ::iterator with a vector
[英]Stable partition std::vector by the parity of the element's original position
我想通过容器中元素原始索引的奇偶校验对std::vector
进行分区。 换句话说,我想把它分成两半:第一部分包含所有偶数索引元素,第二部分包含所有奇数索引元素。
元素之间的排序关系无关紧要,重要的是原始向量中的位置。
我想用标准算法和 lambdas 来实现这种效果,最好是在原位。 我可以用常规的for
循环来做到这一点。
让我们假设我们有一个元素向量abcdef
。 所需的分区是acebdf
。 第一个 ( a
)、第三个 ( c
) 和第五个 ( e
) 元素移到前面,而第二个 ( b
)、第四个 ( d
) 和第六个 ( f
) 元素移到后面。
我有一个类似于这个的对象:
struct T {
int x;
};
我能够通过这样的字段值对其进行分区:
std::vector<T> ts {{1}, {2}, {4}, {3}, {6}, {5}};
auto predicate = [](const T& t) {
return t.x % 2 == 1;
};
std::stable_partition(ts.begin(), ts.end(), predicate);
结果是1 3 5 2 4 6
。 我希望分区返回1 4 6 2 3 5
。
我试图将predicate
定义为
auto predicate = [](const std::vector<T>::const_iterator& t)
return t->x % 2 == 1;
};
但它不会编译,而且显然没有任何意义。
为了说明我的问题,我编写了一个for
循环来执行此分区,尽管不是以稳定的方式进行。
for (auto i = ts.begin() + 1, j = ts.begin() + 2; j != ts.end(); i += 1, j += 2) {
std::swap(*i, *j);
}
是否可以使用std
算法实现它,或者我是否需要诉诸标准循环?
在 c++11 中,使用计数器作为索引来验证它是偶数还是奇数。
#include <iostream>
#include <vector>
struct T {
int x;
};
int main()
{
std::vector<T> ts {{1}, {2}, {4}, {3}, {6}, {5}};
int counter =0;
auto predicate = [&counter]() {
++counter;
return (counter % 2 == 1);
};
std::stable_partition(ts.begin(), ts.end(), predicate);
for(auto i: ts)
std::cout << i.x << ", ";
}
Vector 将其数据存储在线性数组中。 你可以使用这些知识。
使 lambda 作为谓词,它捕获指向向量第一项的指针,并通过引用T 来获取其参数,以引用向量的原始存储元素。 然后您可以通过简单的指针算法找出索引是否为偶数/奇数:
struct T {
int x;
};
int main() {
std::vector<T> ts {{1}, {2}, {4}, {3}, {6}, {5}};
auto pred = [beg = &(*ts.begin())](T& elem) {
return (&elem-beg) % 2 == 0;
};
std::stable_partition(ts.begin(), ts.end(), pred);
for (T t : ts)
std::cout << t.x << std::endl;
// 1,4,6,2,3,5
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.