C++ Lambda - 遍历整数数组
C++ Lambda - Loop over integer array
我正在尝试使用 lambda 模板遍历整数数组。
调用 lambda 的代码看起来像这样(演示目的,不是功能代码):
menu.option("Set Pedestrian Health to 0").allpeds(ped => {
SET_ENTITY_HEALTH(ped, 0);
});
问题:如何制作 allpeds
lambda 模板?
allpeds
将遍历代表游戏中行人的唯一整数数组。
到目前为止我有这个代码:
template<typename T> Menu& allpeds() {
if (pressed()) {
int numElements = 20;
int arrSize = numElements * 2 + 2;
int peds[arrSize];
peds[0] = numElements;
int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds, -1);
for (int i = 0; i < countPeds; i++) {
int ped = peds[i * 2 + 2];
// if this is the right way to do it,
// how to put `ped` in an integer array, and return it
// so I can use it in the lambda template?
}
}
//return *this;
}
我尽量将代码保持为 C。
如果需要更多解释,请告诉我!
就 lambda 语法而言,您展示的示例更像是 C# 而不是 C++。但即便如此,该示例显然将 lambda 作为参数传递给 allpeds()
,并且 lambda 本身也采用输入参数。 allpeds()
没有返回 lambda 然后迭代的数组,allpeds()
调用 lambda 根据需要将每个整数值传递给它。
在 C++ 中,你可以这样使用:
menu.option("Set Pedestrian Health to 0").allpeds(
[](int ped) {
SET_ENTITY_HEALTH(ped, 0);
}
);
template<typename FuncType>
Menu& allpeds(FuncType func) {
if (pressed()) {
int numElements = 20;
int arrSize = numElements * 2 + 2;
std::vector<int> peds(arrSize);
peds[0] = numElements;
int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds.data(), -1);
for (int i = 0; i < countPeds; ++i) {
int ped = peds[i * 2 + 2];
func(ped);
}
}
return *this;
}
我正在尝试使用 lambda 模板遍历整数数组。
调用 lambda 的代码看起来像这样(演示目的,不是功能代码):
menu.option("Set Pedestrian Health to 0").allpeds(ped => {
SET_ENTITY_HEALTH(ped, 0);
});
问题:如何制作 allpeds
lambda 模板?
allpeds
将遍历代表游戏中行人的唯一整数数组。
到目前为止我有这个代码:
template<typename T> Menu& allpeds() {
if (pressed()) {
int numElements = 20;
int arrSize = numElements * 2 + 2;
int peds[arrSize];
peds[0] = numElements;
int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds, -1);
for (int i = 0; i < countPeds; i++) {
int ped = peds[i * 2 + 2];
// if this is the right way to do it,
// how to put `ped` in an integer array, and return it
// so I can use it in the lambda template?
}
}
//return *this;
}
我尽量将代码保持为 C。
如果需要更多解释,请告诉我!
就 lambda 语法而言,您展示的示例更像是 C# 而不是 C++。但即便如此,该示例显然将 lambda 作为参数传递给 allpeds()
,并且 lambda 本身也采用输入参数。 allpeds()
没有返回 lambda 然后迭代的数组,allpeds()
调用 lambda 根据需要将每个整数值传递给它。
在 C++ 中,你可以这样使用:
menu.option("Set Pedestrian Health to 0").allpeds(
[](int ped) {
SET_ENTITY_HEALTH(ped, 0);
}
);
template<typename FuncType>
Menu& allpeds(FuncType func) {
if (pressed()) {
int numElements = 20;
int arrSize = numElements * 2 + 2;
std::vector<int> peds(arrSize);
peds[0] = numElements;
int countPeds = PED::GET_PED_NEARBY_PEDS(playerPed, peds.data(), -1);
for (int i = 0; i < countPeds; ++i) {
int ped = peds[i * 2 + 2];
func(ped);
}
}
return *this;
}