如何使用range :: actions :: insd with std :: vector

时间:2019-12-12 16:49:44

标签: c++ range-v3

在无范围内将元素插入向量的样子如下: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标志进行编译。

1 个答案:

答案 0 :(得分:3)

首先,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

相关问题