简体   繁体   中英

How do I return a modified vector in c++?

Why does (return A;) not work? The error I get is "No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called."

How do I return the newly sorted vector?

int sort(vector <int> A, int n)
{
    if( n >= 2 && n <= 43)
    {
        //sort vector
        for(int j=2; j<=n; j++)
        {
            int tmp = A[j];
            int i = j-1;
            while (-1<i && tmp < A[i])
            {
                A[i+1] = A[i];
                i--;
            }
            A[i+1] = tmp;
        }
    }

    return A;
}

You can go with one of the following two ways to solve this problem:

1) Change return type of the function to vector

vector<int> sort(vector <int> A, int n){
    // body of function
}

2) Pass reference to the vector as parameter. It will affect the function prototype as follows

int sort(vector <int> &A, int n){
    // body of function
}

Change your method declaration to:

vector <int> sort(vector <int> A, int n)

You are trying to return a vector<int> when your return type is currently int .

You can only return values of the declared type from your functions in C / C++.
Anyway, in your case the proper choice is not returning the vector, but passing it in by reference, so you can modify the original vector. Change your prototype thus:

void sort(vector<int>& A)

I also removed n , because the vector knows its size.

Also, if you do not want to change it, for efficiency consider passing a const -qualified reference to the original instead. Don't do that for small easily copied basic types though.

change

int sort(vector <int> A, int n)

to

vector<int> sort(vector <int> A, int n)

if u would like to return A.

or you can use pass byref instead.

Use this Code .

vector<int> sort(vector <int> A, int n)
{
    if( n >= 2 && n <= 43)
    {
        //sort vector
        for(int j=2; j<=n; j++)
        {
            int tmp = A[j];
            int i = j-1;
            while (-1<i && tmp < A[i])
            {
                A[i+1] = A[i];
                i--;
            }
            A[i+1] = tmp;
        }
    }

    return A;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM