填充对矢量

Q-b*_*uit 15 c++ stl

我想用8对填充矢量.每一对代表棋子中的骑士在x和y坐标中的移动.目前我正是这样做的

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); 
Run Code Online (Sandbox Code Playgroud)

我这样做是为了了解Std库.这似乎是解决这个问题的一种无望的低效方式.

谁有更优雅的解决方案?

ipc*_*ipc 16

如果你有C++ 11(否则你不能写>>),你可以使用以下内容:

vector<pair<int,int>> moves = {
  {-2, -1},
  {-2,  1},
  {-1, -2},
  {-1,  2},
  { 1, -2},
  { 1,  2},
  { 2, -1},
  { 2,  1}
};
Run Code Online (Sandbox Code Playgroud)

  • @Praetorian我的gcc 4.7.2编译没有任何问题. (3认同)

hat*_*ine 13

拯救的循环:

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)));
Run Code Online (Sandbox Code Playgroud)

输出:http://ideone.com/2B0F9b


Ker*_* SB 9

在C++ 98/03中:

moves.push_back(std::make_pair(-2, -1));
Run Code Online (Sandbox Code Playgroud)

在C++ 11中:

moves.emplace_back(-2, -1);
Run Code Online (Sandbox Code Playgroud)

或者在C++ 11中:

std::vector<std::pair<int, int>> moves = { { -2, -1}, ... };
Run Code Online (Sandbox Code Playgroud)


Jos*_*man 6

如果您没有C++ 11,则可以使用make_pair,为向量预分配空间,而无需使用reserve初始化元素,然后在不进行新分配的情况下使用push_back.

例如:

vector<pair<int,int> > moves;
moves.reserve(8);
moves.push_back(make_pair(-2, -1));
    // and so on
Run Code Online (Sandbox Code Playgroud)

即使您拥有C++ 11,如果您需要动态计算元素而不是硬编码它们,这种技术也很有用.