C++ 每次手术两次
我希望每个功能都能完成两次。参数在数组中,所以它是这样的:C++ 每次手术两次,c++,arrays,for-loop,C++,Arrays,For Loop,我希望每个功能都能完成两次。参数在数组中,所以它是这样的: fun1(A[0]); fun1(A[1]); fun2(A[0]); fun2(A[1]); fun3(A[0]); fun3(A[1]); 有没有一种方法可以自动完成?我不能用 for(int i=0; i<2; i++) 在这种情况下,秩序很重要 您可以使用函数指针来循环遍历要在容器中的每个元素上调用的所有函数。比如说 #include <iostream> #include <vector>
fun1(A[0]);
fun1(A[1]);
fun2(A[0]);
fun2(A[1]);
fun3(A[0]);
fun3(A[1]);
有没有一种方法可以自动完成?我不能用
for(int i=0; i<2; i++)
在这种情况下,秩序很重要 您可以使用函数指针来循环遍历要在容器中的每个元素上调用的所有函数。比如说
#include <iostream>
#include <vector>
void fun1(int i)
{
std::cout << "fun1: " << i << "\n";
}
void fun2(int i)
{
std::cout << "fun2: " << i << "\n";
}
int main()
{
using fn_t = void(*)(int);
std::vector<fn_t> funs{&fun1, &fun2};
std::vector<int> A = {2, 5};
for (auto& f : funs)
{
for (int i : A)
{
f(i);
}
}
}
这里是一个用于存储函数数组的C版本(忽略std名称空间),以防您无法使用@CoryKramer提供的解决方案
typedef void (*PointerFunction)(int x);
void functA(int a) {
std::cout << "functA: " << a << std::endl;
}
void functB(int b) {
std::cout << "functB: " << b << std::endl;
}
PointerFunction functions[] = { functA, functB };
for (int func = 0; func < 2; func++) {
for (int i = 0; i < 2; i++) {
functions[func](i);
}
}
typedef void(*PointerFunction)(int x);
无效函数(int a){
std::cout您可以将该行为包装在一个高阶函数中,该函数应用一个函数两次,然后将该函数应用于您的函数
使用C++17倍的表达式,该函数看起来像
template <typename Func, typename Arr, typename... Indices>
void map_indices(Func&& f, Arr&& arr, Indices&&... is) {
(f(arr[is]), ...);
}
不,无法自动执行此操作。但可能您的代码需要重构。您喜欢哪种语法?类似于foo({&fun1,&fun2,&fun3},{A[0],A[1]});
?for(auto-f:{&func1,&func2,&func3}){for(auto&A:{A[0],A[1]}{f(A);}
?函数是否具有相同的签名?@MichaelWalz隐式转换可能正在发生。std::vector
早于C++11(假设这就是您所说的“C++0x”)的洛蒂想说的是C版本(显然忽略std
)我刚刚编辑过,谢谢!如果OP故意加上C++,那么提供C解决方案的目的是什么?
typedef void (*PointerFunction)(int x);
void functA(int a) {
std::cout << "functA: " << a << std::endl;
}
void functB(int b) {
std::cout << "functB: " << b << std::endl;
}
PointerFunction functions[] = { functA, functB };
for (int func = 0; func < 2; func++) {
for (int i = 0; i < 2; i++) {
functions[func](i);
}
}
template <typename Func, typename Arr, typename... Indices>
void map_indices(Func&& f, Arr&& arr, Indices&&... is) {
(f(arr[is]), ...);
}
#include <array>
#include <iostream>
template <typename Func, typename Arr, typename... Indices>
void map_indices(Func&& f, Arr&& arr, Indices&&... is) {
(f(arr[is]), ...);
}
void f1(int x) {
std::cout << "f1 " << x << '\n';
}
void f2(int x) {
std::cout << "f2 " << x << '\n';
}
void f3(int x) {
std::cout << "f3 " << x << '\n';
}
int main() {
std::array arr{1, 2, 3};
map_indices(f1, arr, 0, 1);
map_indices(f2, arr, 0, 1);
map_indices(f3, arr, 0, 1);
}
template <typename Func, typename Arr>
void map_indices(Func&& f, Arr&& arr) {
f(arr[0]);
f(arr[1]);
}