我正在尝试编写学校作业,但出现错误,并且由于此时此刻大学没有合格的老师,我来这里寻求帮助。
即时通讯收到错误消息:“错误C2893无法专门化功能模板'iterator_traits ::difference_type std::distance(_InIt,_InIt)'”第22行
我不知道为什么会出现此错误。
码:
#pragma once
// ttt.h
#ifndef TTT_H
#define TTT_H
#include <tuple>
#include <array>
#include <vector>
#include <ctime>
#include <random>
#include <iterator>
#include <iostream>
enum class Player { X, O, None };
using Move = int;
using State = std::array<Player, 9>;
// used to get a random element from a container
template<typename Iter, typename RandomGenerator>
Iter select_randomly(Iter start, Iter end, RandomGenerator& g) {
std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1);
std::advance(start, dis(g));
return start;
}
template<typename Iter>
Iter select_randomly(Iter start, Iter end) {
static std::random_device rd;
static std::mt19937 gen(rd());
return select_randomly(start, end, gen);
}
std::ostream &operator<<(std::ostream &os, const State &state);
std::ostream &operator<<(std::ostream &os, const Player &player);
Player getCurrentPlayer(const State &state);
State doMove(const State &state, const Move &m);
Player getWinner(const State &state);
std::vector<Move> getMoves(const State &state);
#endif // TTT_H
函数调用”:
State mcTrial(const State &board)
{
State currentBoard = board;
std::vector<Move> possibleMoves = getMoves(currentBoard);
while (possibleMoves.size() > 0) {
int move = select_randomly(0, (int)possibleMoves.size() -1);
Move m = possibleMoves[move];
currentBoard = doMove(currentBoard, m);
possibleMoves = getMoves(currentBoard);
}
return currentBoard;
}
最佳答案
您应该将迭代器传递给select_randomly
,而不是索引。这是正确的函数调用:std::vector<Move>::iterator it = select_randomly(possibleMoves.begin(), possibleMoves.end());
要了解有关迭代器的更多信息,请访问http://www.cprogramming.com/tutorial/stl/iterators.html