尝试返回向量时收到错误“ E0415”

时间:2019-03-25 21:59:54

标签: c++ function stdvector

尝试从函数完成返回完整的冒泡排序后,我得到了:

  

E0415不存在合适的构造函数,无法从“ std :: vector > *”转换为“ std :: vector >”

这是代码

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

1 个答案:

答案 0 :(得分:1)

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
}
相关问题