简体   繁体   中英

C++ minor problem: no suitable constructor exists to convert from “void”

I'm new to C++ and run into the following problem when trying to implement a simple recursive algorithm. The problem is highlighting the sorted_lst.push_back(last[0]) in the base case return and says: no suitable constructor exists to convert from "void" to "std::__1::vector<int, std::__1::allocator<int>>"C/C++(415) . Now, I don't see where my void is since I have a return of a vector and not void . I don't even know what a constructor is in this case, since I have a function and not a class?

vector<int> merge_sorting(vector<int> lst, vector<int> sorted_lst = vector<int>()) {

    if (lst.size() == 1){
        return sorted_lst.push_back(lst[0]);
    };
    vector <int> llst(lst.begin(), lst.begin() + (lst.size()/2));
    vector <int> rlst(lst.begin() + (lst.size()/2), lst.end());
    vector<int> a = merge_sorting(llst, sorted_lst);
    vector<int> b = merge_sorting(rlst, sorted_lst);
    // ...

std::vector<T>::push_back returns void

You probably meant to return sorted_lst itself.

Refer to docs on push_back here: https://en.cppreference.com/w/cpp/container/vector/push_back

As Tumblweed53 pointed out, you are returning the void which was returned by push_back . You can do the following instead:

vector<int> merge_sorting(vector<int> lst, vector<int> sorted_lst = vector<int>()) {

    if (lst.size() == 1){
        sorted_lst.push_back(lst[0]);
        return sorted_lst;
    };
    vector <int> llst(lst.begin(), lst.begin() + (lst.size()/2));
    vector <int> rlst(lst.begin() + (lst.size()/2), lst.end());
    vector<int> a = merge_sorting(llst, sorted_lst);
    vector<int> b = merge_sorting(rlst, sorted_lst);

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