ReadingLab/Discussion-for-Cpp

练习题10.13的疑问

EnzoFerrari430 opened this issue · 2 comments

c++ primer 第五版中描述的 partition算法谓词为true的值会排在容器的前半部分,false的值会排在容器的后半部分。那么前半部分的是怎么排序的呢。下面的是我的代码和我的测试

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <string>
using namespace std;
bool isBig(const string &s1)
{
    return s1.size() > 4;
}
int main()
{
    string str;
    vector<string> words;
    while(cin>>str)
    {
        words.push_back(str);
    }
    auto end_pos = partition(words.begin(),words.end(),isBig);
    words.erase(end_pos,words.end());
    for(const auto &c: words)
    {
        cout<<c<<' ';
    }
    cout<<endl;
    return 0;
}

我的输入:
c
java
python
c++
ruby
javascript
csharp
matlab
go
scala
swift

我的输出:
swift scala python matlab csharp javascript

pezy commented

那么前半部分的是怎么排序的呢

不保证顺序。

参见:http://en.cppreference.com/w/cpp/algorithm/partition

Reorders the elements in the range [first, last) in such a way that all elements for which the predicate p returns true precede the elements for which predicate p returns false. Relative order of the elements is not preserved.

哦,了解了。多谢