c++ - Getting range of vector without creating a new subvector -
i'm trying create recursive function each time accepts vector, this:
std::vector<int> mergesort(std::vector<int> &main_vector) { //.......... rest of code ....... middle = get_midpoint(unsorted_vector); first_temp.insert(first_temp.begin(), main_vector.begin(), middle); second_temp.insert(second_temp.begin(), middle, main_vector.end()); first_half = mergesort(first_temp); second_half = mergesort(second_temp); //.......... rest of code ....... return main_vector; }
here i'm trying pass vector each time call function mergesort
again. had create 2 temporary vectors first_temp
, second_temp
, because don't know how extract range main_vector
without creating new temporary vector hold value.
is there way won't need create holder vectors ? main_vector[0:n]
or ?
traditional way use iterator range:
template <typename iterator> void mergesort(iterator begin, iterator end) { const auto middle = get_midpoint_it(begin, end); // .......... rest of code ....... mergesort(begin, middle); mergesort(middle, end); // .......... rest of code ....... }
with library range-v3, may use range directly:
template <typename range> void mergesort(range&& range) { const auto middle = get_midpoint_index(range); // .......... rest of code ....... mergesort(range | ranges::view::slice(0, middle)); mergesort(range | ranges::view::slice(middle, (int) range.size())); // .......... rest of code ....... }
Comments
Post a Comment