【问题标题】:STL algorithm for splitting a vector into multiple smaller ones based on lambda基于 lambda 将向量拆分为多个较小向量的 STL 算法
【发布时间】:2019-07-29 02:20:01
【问题描述】:

假设我有一个向量,其中包含一个结构,其中一个成员描述了它的目标向量。

struct Foo
{
  int target;
  static const int A = 0;
  static const int B = 1;
  static const int C = 2;
};

std::vector<Foo> elements;

std::vector<Foo> As;
std::vector<Foo> Bs;
std::vector<Foo> Cs;
std::vector<Foo> others;

现在我想根据 Target 的值将每个 Foo 移动到其他四个向量之一中。

例如

auto elements = std::vector<Foo>{ {Foo::A}, {Foo::A}, {Foo::B} };

应该在As 中产生两个元素,一个在Bs 中,而在Cs 或others 中没有。 Elements 之后应该是空的。

我自己也可以,但我想知道是否有一种 STL 算法可以用来完成它的工作。

【问题讨论】:

    标签: algorithm c++11 vector stl


    【解决方案1】:

    标准算法通常不会在多个输出目标上运行,因此当您想通过输出迭代器抽象出目标容器时,很难在这里找到合适的解决方案。最接近的可能是std::copy_if。这可能看起来像

    // Help predicate creation:
    auto pred = [](int target){ return [target](const Foo& f){ return f.target == target; }; };
    
    std::copy_if(elements.begin(), elements.end(), std::back_inserter(As), pred(Foo::A));
    std::copy_if(elements.begin(), elements.end(), std::back_inserter(Bs), pred(Foo::B));
    std::copy_if(elements.begin(), elements.end(), std::back_inserter(Cs), pred(Foo::C));
    std::copy_if(elements.begin(), elements.end(), std::back_inserter(others),
        [](const Foo& f){ return false; /* TODO */ });
    
    elements.clear();
    

    如果复制比移动构造更昂贵,您应该将std::make_move_iterator(elements.begin()) 和elements.end() 传递给算法。这里的问题是这不能扩展。 std::copy_if 线性遍历输入范围,上面要这样做四次。可以获得一次遍历,例如像下面这样。

    auto doTheWork = [&As, &Bs, &Cs, &others](const Foo& foo) {
       if (foo.target == Foo::A)
          As.push_back(foo);
       else if (foo.target == Foo::B)
          Bs.push_back(foo);
       else if (foo.target == Foo::C)
          Cs.push_back(foo);
       else
          others.push_back(foo);
    };
    
    std::for_each(elements.begin(), elements.end(), doTheWork);
    

    在这种情况下,我们至少采用了标准算法,但将逻辑转换为相当丑陋的 lambda。请注意,上面的 lambda 将始终复制其参数,它需要进行一些调整才能正确使用 std::move_iterators。

    有时,基于 for 循环的良好旧范围是最易读的解决方案。

    【讨论】:

    • 我想是的,我搜索了 并没有真正找到采用多个迭代器的东西。我现在坚持使用 for 循环,谢谢 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多