gpt4 book ai didi

c++ - 为什么 std::foreach 不能与 std::vector 一起使用?

转载 作者:可可西里 更新时间:2023-11-01 15:38:50 26 4
gpt4 key购买 nike

<分区>

我有以下代码片段,它采用 std::vector<int> list 并在所有 vector 元素中写入一个零。此示例运行良好。

#include <vector>
#include <iostream>
#include <algorithm>

int main () {
std::vector<int> list {1, 1, 2};
auto reset = [](int & element){element = 0;};

auto print = [](int element) {std::cout << element << " ";};
std::for_each(list.begin(), list.end(), reset);
std::for_each(list.begin(), list.end(), print);
}

如果我将 vector 类型从 int 更改为 bool,代码将无法编译。

#include <vector>
#include <iostream>
#include <algorithm>

int main () {
std::vector<bool> list {true, true, false};
auto reset = [](bool & element){element = false;};

auto print = [](int element) {std::cout << element << " ";};
std::for_each(list.begin(), list.end(), reset);
std::for_each(list.begin(), list.end(), print);
}

https://godbolt.org/g/2EntgX

我不明白编译器错误信息:

/opt/compiler-explorer/gcc-7.2.0/lib/gcc/x86_64-linux-gnu/7.2.0/../../../../include/c++/7.2.0/bits/stl_algo.h:3884:2: error: no matching function for call to object of type '(lambda at :7:18)'

    __f(*__first);

^~~

:10:10: note: in instantiation of function template specialization 'std::for_each:7:18)>' requested here

std::for_each(list.begin(), list.end(),reset);

^

:7:18: note: candidate function not viable: no known conversion from 'std::_Bit_iterator::reference' (aka 'std::_Bit_reference') to 'bool &' for 1st argument

auto reset = [](bool & element){element = false;};

^

:7:18: note: conversion candidate of type 'void (*)(bool &)'

为什么 std::foreach 可以与 std::vector<int> 一起使用,但不能与 std::vector<bool> 一起使用?

std::vector<bool>(参见 here)的内存优化是答案的一部分吗?

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com