c++ 无法专门化函数模板 'iterator_traits'

标签 c++ visual-studio

我正在尝试编制一份学校作业,但出现错误,而且由于这个时间 uni 没有合格的老师,我来这里寻求帮助。

我收到一条错误消息:“Error C2893 Failed to specialize function template 'iterator_traits<_Iter>::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

关于c++ 无法专门化函数模板 'iterator_traits',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43142584/

相关文章:

c++ - lldb: vector 元素的自定义摘要(C++)

c++ - 如何解释 C++ 语法中的 decl-specifier

c++ - while 循环没有结束

visual-studio - 颠覆结构问题

.net - C# 结构体中的数组

c++ - 如何将指针作为参数传递给方法?

c++ - 在 ros cmake 文件中包含 dlib

c++ - 类有友元功能。该函数在不同头文件的命名空间内定义。它不能访问私有(private)成员?

c# - 为什么未处理的异常在调试时不会终止进程?

angularjs - Visual Studio HTML 文件中的 Angular Syntax Highlighter