我可以为数组的所有成员添加一个值吗 [英] Can I add a value to all members of an Array
本文介绍了我可以为数组的所有成员添加一个值吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
STL 中是否有一种算法可以一次将相同的值添加到数组的所有成员中?
Is there an algorithm in STL that can add at once the same value to all the members of an array?
例如:
KnightMoves moveKnight(int currentPossition_x, int currentPossition_y)
{
array<int , 8> possibleMoves_x = { -2 , -2 , -1 , -1 , 1 , 1 , 2 , 2 };
array<int , 8> possibleMoves_y = { -1 , 1 , -2 , 2 , -2 , 2 , -1 , 1 };
for (auto it = possibleMoves_x.begin(); it != possibleMoves_x.end(); it++)
{
array <int, 8> newTempKnightPoss_x = currentPossition_x + possibleMoves_x;
array <int, 8> newTempKnightPoss_y = currentPossition_y + possibleMoves_x;
}
}
我可以做这样的事情,但我希望有更好的解决方案
I could do something like this but i was hopping there is a better solution
KnightMoves moveKnight(int currentPossition_x, int currentPossition_y)
{
array<int , 8> possibleMoves_x = { -2 , -2 , -1 , -1 , 1 , 1 , 2 , 2 };
array<int , 8> possibleMoves_y = { -1 , 1 , -2 , 2 , -2 , 2 , -1 , 1 };
for (auto it = possibleMoves_x.begin(); it != possibleMoves_x.end(); it++)
{
*it = *it +currentPossition_x;
}
for (auto it = possibleMoves_y.begin(); it != possibleMoves_y.end(); it++)
{
*it = *it + currentPossition_y;
}
}
得到的结果是2个数组,每个元素是一个元素加上一个常数值;
The axpepted results are 2 arrays which each element is the element plus a constant value;
推荐答案
如果你有 C++11 你可以使用 基于范围的 for 循环:
If you have C++11 you can use the range-based-for loop:
KnightMoves moveKnight(int currentPossition_x, int currentPossition_y){
array<int , 8> possibleMoves_x = { -2 , -2 , -1 , -1 , 1 , 1 , 2 , 2 };
array<int , 8> possibleMoves_y = { -1 , 1 , -2 , 2 , -2 , 2 , -1 , 1 };
for(auto& i : possibleMoves_x){ i += currentPossition_x; }
for(auto& i : possibleMoves_y){ i += currentPossition_y; }
}
在 C++11 之前,您可以使用 std::for_each:
Before C++11 you can use std::for_each:
struct adder{
adder(int val): v{val}{}
void operator()(int& n) { n += v; }
int v;
};
KnightMoves moveKnight(int currentPossition_x, int currentPossition_y){
array<int , 8> possibleMoves_x = { -2 , -2 , -1 , -1 , 1 , 1 , 2 , 2 };
array<int , 8> possibleMoves_y = { -1 , 1 , -2 , 2 , -2 , 2 , -1 , 1 };
std::for_each(possibleMoves_x.begin(), possibleMoves_x.end(),
adder(currentPossition_x));
std::for_each(possibleMoves_y.begin(), possibleMoves_y.end(),
adder(currentPossition_x));
}
这篇关于我可以为数组的所有成员添加一个值吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文