【问题标题】:How to use ranges::actions::insert with std::vector如何将范围::actions::insert 与 std::vector 一起使用
【发布时间】:2019-12-12 16:49:44
【问题描述】:

在向量中插入元素的无范围如下所示:my_vec.insert(std::begin(my_vec), 0);

现在我正在尝试对范围做同样的事情:

#include <range/v3/action/insert.hpp>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> input = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
    for (auto x : ranges::actions::insert(input, 0, 0)) {
        std::cout << x << " ";
    }
    std::cout << "\n";
}

我得到了很多类似这样的编译器错误:

lib/range-v3/include/range/v3/action/insert.hpp:243:18: note: candidate template ignored:
    substitution failure [with Rng = std::__1::vector<int, std::__1::allocator<int> > &, I = int, T = int]:
    no matching function for call to 'insert'
        auto operator()(Rng && rng, I p, T && t) const

我也尝试过ranges::actions::insert(input, {0, 0}),因为我看到以下重载:

auto operator()(Rng && rng, I p, std::initializer_list<T> rng2)

但它仍然不起作用。我正在使用 clang-9.0.0 并使用 -std=c++17 标志进行编译。

【问题讨论】:

    标签: c++ range-v3


    【解决方案1】:

    首先,ranges::actions::insert(cont, pos, value) 本质上调用了cont.insert(pos, value),所以pos 应该是一个迭代器,而不是一个整数值。

    第二,ranges::actions::insert返回insert_result_t,也就是insert成员函数调用的结果:

    template<typename Cont, typename... Args>
    using insert_result_t = decltype(
        unwrap_reference(std::declval<Cont>()).insert(std::declval<Args>()...));
    

    std::vector::insert 返回std::vector::iterator,不能与基于范围的 for 一起使用。而是迭代向量:

    #include <range/v3/action/insert.hpp>
    #include <iostream>
    #include <vector>
    
    int main() {
        std::vector<int> input = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        ranges::actions::insert(input, input.begin(), 0); // input.begin() instead of 0
        for (auto x : input) {                            // iterate over the vector
            std::cout << x << " ";
        }
        std::cout << "\n";
    }
    

    (live demo)

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 2012-05-02
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 2012-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多