尝试返回矢量时收到错误"E0415"

Receiving error 'E0415' when trying to return a vector

本文关键字:错误 E0415 返回      更新时间:2023-10-16

试图在函数完成后返回一个完整的气泡排序,我得到这个:

E0415 不存在合适的构造函数来从"std::vector

, std::allocator> *" 转换为 "std::vector<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;

语法不正确,因为返回类型为 std::vector<double>,而 &newVect 的类型为 std::vector<double>*

这就是编译器抱怨的。

您需要使用

return newVect;

改进建议

最好

将返回类型更改为引用,这样就不会强制调用函数在调用函数时创建副本。

vector<double>& Sort(vector<double> &newVect, int arraySize)
{
   ...
   return newVect;
}

最好还是将返回类型更改为void,因为调用函数对对象进行了排序。

void Sort(vector<double> &newVect, int arraySize)
{
   ...
   // Not return statement
}