简体   繁体   中英

Can I add a value to all members of an Array

Is there an algorithm in STL that can add at once the same value to all the members of an array?

For example:

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;

   }
}

The axpepted results are 2 arrays which each element is the element plus a constant value;

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; }
}

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM