gpt4 book ai didi

c++ - 我可以为数组的所有成员添加一个值吗

转载 作者:行者123 更新时间:2023-11-30 04:48:24 25 4
gpt4 key购买 nike

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;

}
}

预期的结果是2个数组,每个元素是元素加上一个常量值;

最佳答案

如果你有 C++11,你可以使用 range-based-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));
}

关于c++ - 我可以为数组的所有成员添加一个值吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55811251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com