简体   繁体   English

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

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

I am trying to do selection sort using a template, I originally coded it for vectors of type int then abstracted it with templates. 我正在尝试使用模板进行选择排序,我最初将其编码为int类型的向量,然后使用模板对其进行了抽象。 When I try to use a vector of strings I get the error "No viable conversion from string to int". 当我尝试使用字符串向量时,出现错误“从字符串到int没有可行的转换”。

I noticed that in my swap function I am using a temp variable of type int, how do you declare a temporary holding variable if you don't know what the value type of the variables will be? 我注意到在我的交换函数中,我使用的是类型为int的临时变量,如果不知道变量的值类型将如何声明一个临时的持有变量?

I think the error is in the function swapval. 我认为错误是在函数swapval中。

Also, how do I overload the operator to deal with multiple types? 另外,如何重载运算符以处理多种类型? Do templates work for operator overloading? 模板是否适用于操作员重载?

Here is my code. 这是我的代码。

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;
}

You should use a single type when swapping: 交换时应使用单一类型:

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