假设我有一个对象
class Obj {
public:
int a;
int b;
int c;
}
和一组对象
Obj o[N];
我想将每个 Obj.a 复制到一个 int 数组中,我知道其他语言允许我在 C++ 中创建一个看起来像这样的函数
int & fun(Obj os[], T key, int N){
int a[N];
for (int i=0; i<N; i++) {
a[i] = os[i].key;
}
return a;
}
在 C++ 中是否有任何可重用的方法来做到这一点?仅供引用,Obj 的代码无法修改。
最佳答案
这就是 std::transform
函数的用途。您需要提供的只是一个从 Obj
获取所需元素的函数。此示例显示如何使用 std::mem_fn
执行此操作:
#include <algorithm>
#include <functional>
#include <iterator>
#include <iostream>
struct Obj { int a, b, c; };
int main() {
Obj o[3] = {{1, 2, 3}, {11, 22, 33},{111, 222, 333}};
int a[3];
std::transform(std::begin(o), std::end(o),
std::begin(a),
std::mem_fn(&Obj::a));
for (auto e : a)
std::cout << e << ' ';
std::cout << std::endl;
};
输出:
这一切都可以包含在一个辅助函数中,以允许调用者设置要提取的属性。但请注意,如果您真的希望函数返回数组,则需要使用可复制类型,例如
std::array
或 std::vector
。在 C++ 中,普通数组不可复制,因此不能从函数中按值返回。关于c++ - 有没有办法将对象的字段隐式传递给 C++ 中的函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38736754/