Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a vector of pairs

Tags:

c++

stl

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?

like image 560
Q-bertsuit Avatar asked Nov 15 '12 21:11

Q-bertsuit


People also ask

Can you make a vector of pairs?

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.

How do you input a pair into a vector?

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.


2 Answers

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}
};
like image 171
ipc Avatar answered Oct 23 '22 21:10

ipc


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

like image 45
hate-engine Avatar answered Oct 23 '22 22:10

hate-engine