C++:谓词协助”改变”元素位置

谓词

谓词是一个可调用的表达式,其返回结果是一个能用做条件的值(通常返回bool类型).标准库算法所使用的谓词分为两类:

  1. 一元谓词:意味着它们只接受单一参数
  2. 二元谓词:意味着它们有两个参数

接受谓词参数的算法对输入序列中的元素调用谓词,因此,元素类型必须能转换为谓词的参数类型。

问题

标准库定义了名为partition的算法,它接收一个谓词。对容器内容进行划分,使得谓词为true的值会派在容器的前半部分,而使谓词为false的值会排在后半部分.算法返回一个迭代器,指向最后一个使谓词为true的元素之后的位置.

编写函数,接收一个string,返回一个bool值,指出string是否有5个或更多字符。使用此函数划分vector容器.打印出长度大于5的元素.

C++.
image-2099

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*************************************************************************
    > File Name: test.10.13.cpp
    > Author: puruidong
    > Mail: 1@w1520.com
    > Created Time: 2014年06月12日 星期四 23时31分40秒
 ************************************************************************/


#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

/******************************
 
    标准库定义了名为partition的算法,它接收一个谓词。对容器内容进行划分,
               
                使谓词为true的值会派在容器的前半部分,而使谓词为false的值会排在后半部分.
    算法返回一个迭代器,指向最后一个使谓词为true的元素之后的位置.
   
    ---题目要求:

    编写函数,接收一个string,返回一个bool值
    ,指出string是否有5个或更多字符。使用此函数划分words
    .打印出长度大于5的元素.


 **********************************/

bool isL(const string &s1)
{
    return s1.size()>=5;
}

void elim(vector<string> &vec)
{
    sort(vec.begin(),vec.end());
    auto re = partition(vec.begin(),vec.end(),isL);
    vec.erase(re,vec.end());
    cout << "\n\n字符串长度大于等于5的元素:" << endl;
    for(const auto &s:vec)
    {
        cout << s << endl;
    }
}


int main()
{
    cout << "---题目要求:\n编写函数,接收一个string,返回一个bool值\n,指出string是否有5个或更多字符。使用此函数划分words\n.打印出长度大于5的元素.\n输入字符串[Linux:ctrl+D停止输入]:" << endl;
    string pa;
    vector<string> vec;
    while(cin >> pa)
    {
        vec.push_back(pa);
    }
    elim(vec);
    return 0;
}

运行截图

C++运行结果
image-2100