[英]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.