首页 > 解决方案 > 如何使用自定义非纯交换函数对算法进行参数化?

问题描述

我想从<algorithms>包含在一个容器中的元素范围应用一种算法,由迭代器对定义,包含到另一个容器中。为此,我需要一个swap带状态的函数:只需指向带有元素的容器的指针,就可以swap在两个容器中同步创建 s 。

这是我不完整的尝试:

#include <utility>
#include <algorithm>
#include <vector>
#include <list>
#include <iostream>
#include <random>

inline
std::ostream & operator << (std::ostream & out, const std::pair< int, int > & p)
{   
    return out << '{' << p.first << ", " << p.second << '}';
}   

int main()
{   
    using L = std::list< std::pair< int, int > >;
    using I = typename L::const_iterator;
    using P = std::pair< I, I >;
    using R = std::vector< P >;
    L values;
    R ranges;
    auto l = std::cbegin(values);
    for (int i = 0; i < 10; ++i) {
        l = values.emplace(std::cend(values), i, 0); 
        auto & p = ranges.emplace_back(l, l); 
        for (int j = 1; j <= i; ++j) {
            p.second = values.emplace(std::cend(values), i, j); 
        }   
    }   
    const auto swap = [&values] (P & l, P & r)
    {   
        auto ll = std::next(l.second);
        auto rr = std::next(r.second);
        if (ll == r.first) {
            values.splice(rr, values, l.first, ll);
        } else if (rr == l.first) {
            values.splice(ll, values, r.first, rr);
        } else {
            L temp;
            temp.splice(std::cend(temp), values, l.first, ll);
            values.splice(ll, values, r.first, rr);
            values.splice(rr, std::move(temp));
        }   
        std::swap(l, r); 
    };  
    for (const auto & p : values) {
        std::cout << p << std::endl;
    }   
    std::cout << "-----" << std::endl;
    std::shuffle(std::begin(ranges), std::end(ranges), std::mt19937{std::random_device{}()}); // just an example, it can be any algo, say std::sort w/ custom comparator
    for (const auto & p : values) {
        std::cout << p << std::endl;
    }
}

确定swap上面代码中的函数对象不能“参与重载决议”(由于许多原因,在当前上下文中是矛盾的,请不要关注这一点)。

我能做的是像这样在命名空间范围(全局(命名或匿名,无关紧要))中定义迭代器对的标记版本,并使用上面代码中的 lambda 主体using P = struct { std::pair< I, I > p };重载自由函数void swap(P & l, P & r);. 我当然也应该做values一个全局变量。它导致阻碍上述代码的方法的有用性。

有没有办法以更通用的方式将有状态swap函数传递给算法<algorithm>,然后如上所述?

我阅读了关于 Eric Niebler 的自定义点的文章草稿。但他的方法意味着修改 STL。无论哪种方式,即使他的方法不能让我从函数范围传递有状态的重载,我认为,不是吗?

标签: c++algorithmlambdastloverload-resolution

解决方案


您可以只包含values在您的范围对象中。

struct Range { I first; I second; L & list; }

void swap(Range & l, Range & r)
{
    assert(std::addressof(l.list) == std::addressof(r.list));
    using std::swap;

    auto ll = std::next(l.second);
    auto rr = std::next(r.second);
    if (ll == r.first) {
        l.list.splice(rr, l.list, l.first, ll);
    } else if (rr == l.first) {
        l.list.splice(ll, l.list, r.first, rr);
    } else {
        L temp;
        temp.splice(std::cend(temp), l.list, l.first, ll);
        l.list.splice(ll, l.list, r.first, rr);
        l.list.splice(rr, std::move(temp));
    }   
    swap(l.first, r.first); 
    swap(l.second, r.second); 
}

推荐阅读