井字棋樹中的所有posiible孩子都在那裏定大小的井字棋「板」 N返回所有給定板的孩子寫的實現。但是,它不會打印出每個矢量內的任何值,我不知道爲什麼。C++入門使用向量
這裏我們假設X(表示爲1)總是在O之前(表示爲-1)。空的空間是指爲0
這裏是實現文件,其中頭文件有vector<int> b_;
和int n_;
作爲其私有數據成員:
#include "tttboard.h"
#include <vector>
#include <iostream>
using namespace std;
tttboard::tttboard()
{
}
tttboard::tttboard(int n, vector<int> &e)
{
n_ = n;
for (int i=0; i<n*n; i++)
{
e.push_back(i);
}
}
tttboard::tttboard(int n){
n_ = n;
for (int i=0; i<n*n; i++)
b_.push_back(0);
}
vector<tttboard> tttboard::possibleNextBoards(int turn) const{
vector<tttboard> children;
int temp;
for (int i = 0; i < children.size(); i++)
{
children.push_back(temp);
}
return children;
}
bool tttboard::operator==(const tttboard& rhs) const
{
bool check = true;
for (int i=0; i < b_.size(); i++)
{
if (b_[i] == rhs.b_[i])
{
continue;
}
else
{
check = false;
break;
}
}
return check;
}
ostream& operator << (ostream & output, const tttboard &board)
{
output << "{";
for (int i=0; i < board.b_.size(); i++)
{
output << board.b_[i];
if (i != board.b_.size() - 1)
output << ", ";
}
output << "}";
return output;
}
編輯:這是主要的文件,我我有工作(道歉,如果這是一個有點長)
#include "tttboard.h"
#include "gTree.h"
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
void Tokenize(string line, vector<string> & tokens, string delimiters = "\t "){
string token = "";
string OneCharString = " ";
for (int i=0; i<line.size(); i++)
if (find(delimiters.begin(), delimiters.end(), line[i])!=delimiters.end()) // line[i] is one of the delimiter characters
{
if (token != "")
tokens.push_back(token);
token = "";
}
else
{
OneCharString[0] = line[i];
token +=OneCharString;
}
if (token != "")
tokens.push_back(token);
}
int getTurn(vector<int> b){
int s = 0;
for (int i=0; i<b.size(); i++)
s+=b[i];
if (s==0)
return 1;
else
return -1;
}
int main(int argc, char** argv){
if (argc!=3){
cout << "usage: executable.o n board\n example of board:(\"{0,0,1,0,0,-1,1,0,0}\")";
return 1;
}
int n= atoi(argv[1]);
string str_board = argv[2];
vector<string> tokens;
Tokenize(str_board,tokens," {,}");
vector<int> board;
for (int i=0; i<tokens.size(); i++){
board.push_back(atoi(tokens[i].c_str()));
}
if (n*n!= board.size()){
cout<< "n and board are not consistent!\n";
return 1;
}
tttboard p(n,board);
int turn = getTurn(board);
vector<tttboard> v = p.possibleNextBoards(turn);
cout <<"children of the given board:" << endl;
for (int i=0; i<v.size(); i++)
cout << v[i] << endl;
return 0;
}
'main'看起來像什麼?另外,'tttboard :: operator =='並不需要那麼複雜:只是'for(...){if(b_ [i]!= rhs.b_ [i])返回false; } return true;'會做,並且'possibleNextBoards'中的邏輯對我來說沒有多大意義。雖然這些都與你的問題沒有關係。 – HTNW
@HTNW以上 – nickoba