6

The code below does not compile in Visual Studio, giving

Error C2672 'operator __surrogate_func': no matching overloaded function found sortms C:\Users\David\source\repos\sortms\sortms.cpp 103

The function works as written when I use a C-style array. The function also works if I use the commented code specifying input.begin(), input.end(), output.begin().

I am using Visual Studio Community 2019 v16.8.6, compiling with the /std:c++latest option. I thought that the standard containers were range-based?

Could someone help me better understand the advantages of std::range::copy() vs std::copy() when dealing with vectors or other standard containers?

#include <iostream>
#include <ranges>
#include <algorithm>
#include <array>
#include <utility>
#include <vector>
#include <functional>
#include <string>
#include <concepts>

void ranges_copy_demo()
{
    std::cout << "\nstd::ranges::copy()\n";

/*
    int const input[] = { 1, 2, 3, 5, 8, 13, 21, 34, 45, 79 };
    int output[10] = { 0 };
*/
    std::vector<int> input = { 1, 2, 3, 5, 8, 13, 21, 34, 45, 79 };
    std::vector<int> output(10, 0);

//  auto r1 = std::ranges::copy(input.begin(), input.end(), output.begin());
    auto r1 = std::ranges::copy(input, output);
    print_range("copy output", output, r1);

    // copy number divisible by 3
//  auto r2 = std::ranges::copy_if(input.begin(), input.end(), output.begin(), [](const int i) {
    auto r2 = std::ranges::copy_if(input, output, [](const int i) {
        return i % 3 == 0;
        });
    print_range("copy_if %3 output", output, r2);

    // copy only non-negative numbers from a vector
    std::vector<int> v = { 25, 15, 5, 0, -5, -15 };
//  auto r3 = std::ranges::copy_if(v.begin(), v.end(), output.begin(), [](const int i) {
    auto r3 = std::ranges::copy_if(v, output, [](const int i) {
        return !(i < 0);
        });
    print_range("copy_if !(i < 0) output", output, r3);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
davidbear
  • 375
  • 2
  • 13

1 Answers1

11

Since someone else might fall in the same mental trap that I did. The following works for either a c-style array or a std::container

    auto r1 = std::ranges::copy(input, std::begin(output));

davidbear
  • 375
  • 2
  • 13