I want to fill a vector with 8 pairs. Each pair represents the moves in x and y coordinates a knight in a game of chess can make. At the moment I'm doing it like this
vector<pair<int,int>> moves;
pair<int,int> aPair;
aPair.first = -2;
aPair.second = -1;
moves.push_back(aPair);
aPair.first = -2;
aPair.second = 1;
moves.push_back(aPair);
aPair.first = -1;
aPair.second = -2;
moves.push_back(aPair);
aPair.first = -1;
aPair.second = 2;
moves.push_back(aPair);
aPair.first = 1;
aPair.second = -2;
moves.push_back(aPair);
aPair.first = 1;
aPair.second = 2;
moves.push_back(aPair);
aPair.first = 2;
aPair.second = -1;
moves[6].push_back(aPair);
aPair.first = 2;
aPair.second = 1;
moves.push_back(aPair);
I'm doing this to learn about the Std library. This seems like a hopelessly inefficient way of solving this problem.
Anyone have a more elegant solution?
A pair is a container which stores two values mapped to each other, and a vector containing multiple number of such pairs is called a vector of pairs.
The standard solution to add a new std::pair to a vector of pairs is using the std::emplace_back(T&&... args) function, which in-place construct and insert a pair at the end of a vector, using the specified arguments for its constructor. Note that this function is added in C++11.
If you have C++11 (otherwise you can't write >>
), you can use the following:
vector<pair<int,int>> moves = {
{-2, -1},
{-2, 1},
{-1, -2},
{-1, 2},
{ 1, -2},
{ 1, 2},
{ 2, -1},
{ 2, 1}
};
Loops to the rescue:
for(int k = 0; k < 2; k++)
for(int i = -1; i < 2; i += 2)
for(int j = -1; j < 2; j+= 2)
result.push_back(make_pair(i * (k+1), j * (((k + 1) % 2) + 1)));
Output: http://ideone.com/2B0F9b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With