繁体   English   中英

选择使用模板排序,无效的字符串转换为int,C ++

[英]Selection Sort using Templates, invalid conversion string to int, C++

我正在尝试使用模板进行选择排序,我最初将其编码为int类型的向量,然后使用模板对其进行了抽象。 当我尝试使用字符串向量时,出现错误“从字符串到int没有可行的转换”。

我注意到在我的交换函数中,我使用的是类型为int的临时变量,如果不知道变量的值类型将如何声明一个临时的持有变量?

我认为错误是在函数swapval中。

另外,如何重载运算符以处理多种类型? 模板是否适用于操作员重载?

这是我的代码。

template<typename T>
void selection_sort(vector<T>& v)
{
    int next = 0;
    for (next = 0; next <  v.size() -1; next++)
    {
        int minpos = check_value(v, next, v.size() -1.0);

        if (minpos != next) {
            swapval( v[minpos], v[next]);
        }
    }
}

template<typename A, typename B>
void swapval(A& a, B& b)
{
    int temp = b; // temp value of int declared here, think this causes error
    b = a;
    a = temp;
}

template<typename T, typename A, typename B>
int check_value(vector<T>& v, A from, B to)
{
    int minpos = from;
    for (int i = from; i <= to; i++)
    {
        if (v[minpos] > v[i])
        {
            minpos = i;
        }
    }
    return minpos;
}

交换时应使用单一类型:

template<typename T>
void swapval(T& a, T& b)
{
    T temp = std::move(b);
    b = std::move(a);
    a = std::move(temp);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM