How to add to a vector of vectors
May 22, 2013 at 7:54pm UTC
In my program i'm trying to have a function that returns a possible set of moves for a knight chess piece to move based off of its current position. Here's what I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
int x1 = x+1;
int x2 = x+2;
int x3 = x-1;
int x4 = x-2;
int y1 = y+1;
int y2 = y+2;
int y3 = y-1;
int y4 = y-2;
vector<vector<int >> temp;
if (x1 >= 0 && x1 < grid_.size())
{
if (y2 >= 0 && y2 < grid_.size())
{
temp.push_back(x1,y2); //here's the error
return temp;
}
}
I want to return a vector of x,y coordinate, but the push_back only allows one argument. Any suggestions?
May 22, 2013 at 8:22pm UTC
std::vector<std::pair<int, int>>temp;
temp.push_back( std::make_pair( x1, y2 ) );
or temp.emplace_back( x1, y2 );
A sample
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
#include <vector>
#include <utility>
int main()
{
std::vector<std::pair<int , int >> v;
v.emplace_back( 1, 1 );
v.emplace_back( 2, 2 );
for ( auto p : v ) std::cout << "< " << p.first
<< ", " << p.second
<< " >\n" ;
}
EDIT: If you are using MS VC++ 2010 then the loop in the sample can be rewritten as
1 2 3
for each ( auto p in v ) std::cout << "< " << p.first
<< ", " << p.second
<< " >\n" ;
Last edited on May 22, 2013 at 8:37pm UTC
Topic archived. No new replies allowed.