Without ranges inserting element into the vector looks like this: my_vec.insert(std::begin(my_vec), 0);
Now I'm trying to do same thing with ranges:
#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";
}
And I get a lot of compiler errors looking like this one:
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
I've also tried ranges::actions::insert(input, {0, 0}), because I see following overload:
auto operator()(Rng && rng, I p, std::initializer_list<T> rng2)
But it still does not work. I'm using clang-9.0.0 and compile with -std=c++17 flag.
First, ranges::actions::insert(cont, pos, value) essentially calls cont.insert(pos, value), so pos should be an iterator, not an integer value.
Second, ranges::actions::insert returns insert_result_t, which is just the result of the insert member function call:
template<typename Cont, typename... Args>
using insert_result_t = decltype(
unwrap_reference(std::declval<Cont>()).insert(std::declval<Args>()...));
std::vector::insert returns std::vector::iterator, which cannot be used with the range-based for. Iterate over the vector instead:
#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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With