#c #stl
#c #stl
Вопрос:
Существует ли алгоритм в 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 массива, каждый элемент которых является элементом плюс постоянное значение;
Комментарии:
1. В зависимости от того, что все, что вы хотите сделать, есть
std::valarray
2. Использовать
std::transform
с подходящей и простой лямбда-функцией (или объектом-функтором)?3. для диапазона делает это тривиальным, хотя:
for (autoamp; e : possibleMoves_x) { e = currentPossition_x; }
Ответ №1:
Если у вас 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(autoamp; i : possibleMoves_x){ i = currentPossition_x; }
for(autoamp; i : possibleMoves_y){ i = currentPossition_y; }
}
До C 11 вы могли использовать std::for_each:
struct adder{
adder(int val): v{val}{}
void operator()(intamp; 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));
}
Комментарии:
1. «до C 11» вы не можете использовать лямбды.