C++容器流式处理类

很久没有上CSDN了,最近一段时间,因为工作的关系时间上比较闲,利用闲暇时间重新翻了一下丢弃很久的C++语言。C++从98、11、14、17目前已经也走到了20版本,发生了很多变化,也引入了很多新的语言特性和库,让开发也更加的便、高效。

但用惯了Java后,发现其中Java的容器流式操作特别简单,封装的很是优雅。而在C++中,针对容器的操作,与算法是完全分隔的,操作起来利用迭代器进行串接,这种方式其实本身实际上复用效率特别高效,但是对于开发者来说,又显得有些低效,考虑到这个问题,我自己对C++的容器与算法,简单做了一个封装。

话不多说,直接上代码,让大家看看效果!

示例代码

    vector<int> vec = {1, 3, 4, 6, 4, 2, 11, 9};
    auto minmax = JavaStyleStream<vector, int>(vec)
        .filter([](int i) { return i % 3 == 0; })
        .transform([](int i){return i*2.5;})     
        .sort()
        .for_each([](double i) { std::cout << i << " ";})
        .minmax();
    cout << minmax.first << ":" << minmax.second << endl;

最终结果

7.5 15 22.5 7.5:22.5

看到这里,是不是觉得容器操作起来要高效很多,不用再面对一成不变的迭代器了。

详细的Java Style容器流式封装类,见下面代码(未完整封装C++所有算法,工作还在进行中),觉得好用,麻烦点个赞,也欢迎大家提出宝贵意见

//
// Created by AILI on 2022/10/6.
//

#ifndef CPPTEST_JAVASTYLESTREAM_H
#define CPPTEST_JAVASTYLESTREAM_H

#include <algorithm>
#include "function_traits.h"

//template <template<typename, typename> class Cont>
//struct Stream {};

template<template<typename T1, typename T2> class Cont, typename Tp, typename Alloc = std::allocator<Tp>>
class JavaStyleStream {
public:
    typedef typename Cont<Tp, Alloc>::value_type value_type;
    typedef typename Cont<Tp, Alloc>::pointer    pointer;
    typedef typename Cont<Tp, Alloc>::const_pointer	const_pointer;
    typedef typename Cont<Tp, Alloc>::reference		reference;
    typedef typename Cont<Tp, Alloc>::const_reference	const_reference;
    typedef typename Cont<Tp, Alloc>::iterator  iterator;
    typedef typename Cont<Tp, Alloc>::const_iterator const_iterator;
    typedef typename Cont<Tp, Alloc>::const_reverse_iterator const_reverse_iterator;
    typedef typename Cont<Tp, Alloc>::reverse_iterator reverse_iterator;
    typedef typename Cont<Tp, Alloc>::size_type size_type;
    typedef typename Cont<Tp, Alloc>::difference_type  difference_type;
    typedef typename Cont<Tp, Alloc>::allocator_type allocator_type;

    //聚合
    value_type max() {
        return *max_element();
    }

    template<typename _Compare>
    value_type max(_Compare compare) {
        return *max_element();
    }

    iterator max_element() {
        return std::max_element(_container.begin(), _container.end());
    }

    template<typename _Compare>
    iterator max_element(_Compare compare) {
        return std::max_element(_container.begin(), _container.end(), compare);
    }

    value_type min() {
        return *min_element();
    }

    template<typename _Compare>
    value_type min(_Compare compare) {
        return *min_element(compare);
    }

    iterator min_element() {
 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值