【问题标题】:std::ranges::copy will not accept std::vector in visual studiostd::ranges::copy 在 Visual Studio 中不接受 std::vector
【发布时间】:2021-03-01 15:50:21
【问题描述】:

下面的代码在 Visual Studio 中无法编译,给出

错误 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);
}

【问题讨论】:

  • 您需要将out.begin() 传递给ranges::copy 而不是out
  • 男孩,我觉得自己很笨吗。

标签: c++ compiler-errors c++20 std-ranges


【解决方案1】:

因为其他人可能会陷入和我一样的心理陷阱。以下适用于 c 样式数组或 std::container

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

【讨论】:

    猜你喜欢
    • 2015-10-20
    • 2012-09-08
    • 1970-01-01
    • 2022-01-18
    • 2020-01-11
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多