4

C++ STL :std::partition_copy,std::back_inserter,std::unary_function

 3 years ago
source link: https://www.lpime.cn/article/102
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

partition_copyback_inserterunary_function

C++ STL :std::partition_copy,std::back_inserter,std::unary_function

std::back_inserter: 能用于添加元素到容器尾端的 std::back_insert_iterator ,预期相似的std::front_inserter,std::inserter;

std::partition_copy:把数据根据需求分成两块数据;

std::unary_function:用于创建拥有一个参数的函数的基类。

以上三个新增特性可以点开查看详情,我只是在此搬运一下,让自己知道的更多,以便解决问题,这种方式通过某种方式分割数组或者数据非常方便。

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
#include <string>

using namespace std;

struct Compare : std::unary_function<int, bool>
{
    Compare(std::string&& str)
    {
        cout << str << endl;
    }
    bool operator()(int i)
    {
        return i > 5;
    }
};


int main()
{
    /*int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
    int true_arr[5] = { 0 };
    int false_arr[5] = { 0 };*/

    std::vector<int> arr = { 1,2,3,4,5,6,7,8,9,10 };
    std::vector<int> true_arr{};
    std::vector<int> false_arr{};

    std::string test = "sss";

    std::partition_copy(arr.begin(), arr.end(), std::back_inserter(true_arr), std::back_inserter(false_arr), Compare(std::move(test)));

    /*std::partition_copy(std::begin(arr), std::end(arr), std::begin(true_arr), std::begin(false_arr),
        [](int i) {return i > 5; });*/

    std::cout << "true_arr: ";
    for (auto x : true_arr) {
        std::cout << x << ' ';
    }
    std::cout << '\n';

    std::cout << "false_arr: ";
    for (auto x : false_arr) {
        std::cout << x << ' ';
    }
    std::cout << '\n';

    system("PAUSE");
    return 0;
}
#输出:
sss
true_arr: 6 7 8 9 10
false_arr: 1 2 3 4 5

本文由 Ryan 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2020/08/22 22:52


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK