尝试 return 向量时收到错误 'E0415'
Receiving error 'E0415' when trying to return a vector
在函数完成后尝试return一个完整的冒泡排序,我得到这个:
E0415 no suitable constructor exists to convert from "std::vector<double, std::allocator<double>> *" to "std::vector<double, std::allocator<double>>"
这是代码
class BubbleSort : SortingAlogrithm
{
void swap(double *xp, double *yp)
{
double temp = *xp;
*xp = *yp;
*yp = temp;
}
public:
vector<double> Sort(vector<double> &newVect, int arraySize)
{
cout << "Bubble sort algorithm commencing" << endl;
int i, j;
for (i = 0; i < arraySize - 1; i++)
// Last i elements are already in place
for (j = 0; j < arraySize - i - 1; j++)
if (newVect[j] > newVect[j + 1])
swap(&newVect[j], &newVect[j + 1]);
cout << "Ordered List: ";
for (int i = 0; i < arraySize; i++)
{
cout << newVect[i] << " ";
}
return &newVect;
}
};
return &newVect;
在语法上是不正确的,因为 return 类型是 std::vector<double>
而 &newVect
是类型 std::vector<double>*
.
这就是编译器所抱怨的。
你需要使用
return newVect;
改进建议
最好将 return 类型更改为引用,这样您就不会在调用函数时强制调用函数进行复制。
vector<double>& Sort(vector<double> &newVect, int arraySize)
{
...
return newVect;
}
最好将 return 类型更改为 void
,因为调用函数具有正在排序的对象。
void Sort(vector<double> &newVect, int arraySize)
{
...
// Not return statement
}
在函数完成后尝试return一个完整的冒泡排序,我得到这个:
E0415 no suitable constructor exists to convert from "std::vector<double, std::allocator<double>> *" to "std::vector<double, std::allocator<double>>"
这是代码
class BubbleSort : SortingAlogrithm
{
void swap(double *xp, double *yp)
{
double temp = *xp;
*xp = *yp;
*yp = temp;
}
public:
vector<double> Sort(vector<double> &newVect, int arraySize)
{
cout << "Bubble sort algorithm commencing" << endl;
int i, j;
for (i = 0; i < arraySize - 1; i++)
// Last i elements are already in place
for (j = 0; j < arraySize - i - 1; j++)
if (newVect[j] > newVect[j + 1])
swap(&newVect[j], &newVect[j + 1]);
cout << "Ordered List: ";
for (int i = 0; i < arraySize; i++)
{
cout << newVect[i] << " ";
}
return &newVect;
}
};
return &newVect;
在语法上是不正确的,因为 return 类型是 std::vector<double>
而 &newVect
是类型 std::vector<double>*
.
这就是编译器所抱怨的。
你需要使用
return newVect;
改进建议
最好将 return 类型更改为引用,这样您就不会在调用函数时强制调用函数进行复制。
vector<double>& Sort(vector<double> &newVect, int arraySize)
{
...
return newVect;
}
最好将 return 类型更改为 void
,因为调用函数具有正在排序的对象。
void Sort(vector<double> &newVect, int arraySize)
{
...
// Not return statement
}