Загвоздка в том, что есть две функции, которые вы можете использовать.
template< class BidirectionalIterator, class UnaryPredicate >
BidirectionalIterator partition( BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate p );
template< class BidirectionalIterator, class UnaryPredicate >
BidirectionalIterator stable_partition( BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate p );
Функции partition() и stable_partition() реорганизовать элементы коллекции таким образом, чтобы все элементы, для которых предикат p возвращает true, будет предшествовать всем тем, для которых p возвращает false. Это означает, что элементы будут разделены на два диапазона:
• [во-первых, return_value)
• [возвращаемое_значение, последнее)
где return_value
— это итератор, возвращаемый любой из функций. Последовательность элементов в результирующих группах такова, где partition()
и stable_partition()
различаются.
partition()
не гарантирует какой-либо конкретный порядок в диапазонах.
stable_partition()
сохранит относительный порядок элементов до разделения. Это означает, что если есть два элемента a и b, и a предшествует b, и если они оба принадлежат к одной и той же группе после разделения, элемент a все равно будет предшествовать элементу b.
Вот пример кода:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool IsOdd(int i) {
return (i & 1); //use !(i & 1); if you want to place even elements first in the vector
}
int main() {
vector<int> v;
// set some values and shuffle them:
for (int i = 1; i<10; ++i)
v.push_back(i);
random_shuffle(v.begin(), v.end());
cout << "All elements:";
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
cout << ' ' << *it;
cout << endl;
//sort the vector
cout << "Sorted vector:";
sort(v.begin(), v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
cout << ' ' << *it;
cout << endl;
//change to partition and see the difference
vector<int>::iterator bound = stable_partition(v.begin(), v.end(), IsOdd);
// print content:
cout << "odd elements:";
for (std::vector<int>::iterator it = v.begin(); it != bound; ++it)
cout << ' ' << *it;
cout << endl;
cout << "even elements:";
for (vector<int>::iterator it = bound; it != v.end(); ++it)
cout << ' ' << *it;
cout << endl;
cout << "Sorted odd-even vector:";
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
cout << ' ' << *it;
cout << endl;
return 0;
}
Выход:
All elements: 5 6 2 1 9 4 7 8 3
Sorted vector: 1 2 3 4 5 6 7 8 9
odd elements: 1 3 5 7 9
even elements: 2 4 6 8
Sorted odd-even vector: 1 3 5 7 9 2 4 6 8
Я надеюсь, что это поможет для понимания.
person
BugShotGG
schedule
26.02.2016
n
, затем используетеnum
- person emartel   schedule 16.11.2012&
с 1(value & 1)
вместо выполнения операции по модулю (%
). - person emartel   schedule 16.11.2012& 1
должно быть оптимальнее, чем% 2
. Несмотря на то, что Visual Studio будет генерировать для обоихmov byte ptr [isOdd],1
, я не думаю, что каждый компилятор будет это делать. Также, поскольку речь идет о сортировке, скорость этой операции следует считать критичной. - person emartel   schedule 16.11.2012value % 2
будет 0 для четного и 1 для нечетного, простая замена% 2
на& 1
как вvalue & 1
будет 0 для четного и 1 для нечетного - person emartel   schedule 16.11.2012h * 127
был быстрее, чем(h << 7) - h
, на машине, не имеющей аппаратного разделения.) - person James Kanze   schedule 16.11.2012