gpt4 book ai didi

c++ - 将模板函数传递给 std::for_each

转载 作者:太空狗 更新时间:2023-10-29 23:43:55 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的模板函数来打印某个容器的每个元素,而不使用 for 循环。到目前为止,我已经

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

template <typename T> void print_with_space(T x){
std::cout << x << ' ';
}

template <typename T> void print_all(T beg, T end){
std::for_each(beg, end, print_with_space<int>);
std::cout << '\n';
}

int main(){
int a[] = {1, 2, 3};
std::vector<int> v(a, a+3);
print_all(v.begin(), v.end());
return 0;
}

代码编译并运行,但只是因为我输入了print_with_space<int>print_all 的执行中.我只想拥有 print_with_space那里的原因很明显,但是代码无法编译。我该怎么做?

最佳答案

您可以使用:

std::for_each(beg, end, [](const typename T::value_type& value) {
print_with_space(value);
});

T类型为 std::vector<>::iterator ,这是一个 RandomAccessIterator .每个RandomAcessIterator有一个基础类型,由 value_type 公开.

所以,如果你通过 std::vector<int>::iterator , std::vector<int>::iterator::value_type将是 int .

现在您有了类型,您可以创建一个 lambda,它会在每次迭代时执行。


在 C++14 中,您甚至可以:

//'auto' automatically deduces the type for you
std::for_each(beg, end, [](const auto& value) {
print_with_space(value);
});

关于c++ - 将模板函数传递给 std::for_each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935694/

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