[英]Can I add a value to all members of an Array
STL 中是否有一種算法可以一次向數組的所有成員添加相同的值?
例如:
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;
}
}
我可以做這樣的事情,但我希望有更好的解決方案
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;
}
}
axpepted 的結果是 2 個數組,其中每個元素是元素加上一個常量值;
如果你有 C++11,你可以使用基於范圍的 for循環:
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 :
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.