std::ranges::copy在Visual Studio中不接受std::vector。

6
以下代码在Visual Studio中无法编译,出现“Error C2672 'operator __surrogate_func':sortms C:\Users\David\source\repos\sortms\sortms.cpp 103找不到匹配的重载函数”
使用C风格数组时,该函数按原样运行。 如果我使用代码注释掉的 input.begin(),input.end(), output.begin() ,该函数也能正常工作。
我使用的是Visual Studio Community 2019 v16.8.6,并使用/std:c++latest选项进行编译。 我认为标准容器都是基于范围的,那么有没有人能帮我更好地理解在处理向量或其他标准容器时使用std::range::copy()std::copy()的优势?
#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);
}

5
你需要将 out.begin() 传递给 ranges::copy,而不是 out - 康桓瑋
我感到非常愚蠢。 - davidbear
1个回答

11

因为其他人可能会陷入我曾经遇到的相同心理陷阱,以下内容适用于C风格数组或std::容器。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接