简体   繁体   中英

C++ returning a vector (conversion of int to non-scalar type)

I am trying to fill a vector with integers starting with -1 and going until the negative of my size parameter. For example: if the parameter is 6, then I want the vector to have 6 items, from -1 to -6. Oh and if the size parameter is less than 1 I want to return an empty parameter.

I am getting a "conversion from 'int' to non-scalar type" error message. To the best of my knowledge this is good code but obviously I can't figure it out. Any help is appreciated.

#include <iostream>
#include <vector>

int negativity(int size) {
    std::vector<int> vect;
    if (size < 1) {
        return vect;
    }
    for (int i=-1; i > size; i--) {
        vect.push_back(i);
    }
    return vect;
}

The return type of your function is int , but you are returning std::vector<int> .

This should correct compiler error.

#include <iostream>
#include <vector>
std::vector<int> negativity(int size) {
    std::vector<int> vect;
    if (size < 1) {
        return vect;
    }
    for (int i=-1; i > size; i--) {
        vect.push_back(i);
    }
    return vect;
}
/** other implementation;
 - Usage of an argument to avoid duplication of copying object.
 */
size_t negativity(std::vector<int>& vResult, const unsigned int uiHowmany)
{
    vResult.clear();
    for(unsigned int i=1; i < uiHowmany; ++i)
    {
        vResult.push_back((-1)*i);
    }
    return vResult.size();
}

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