liu shijie liu shijie - 2 months ago 10
C++ Question

how can i append a vector in a function recursion which return a vector?

here is my function to change a Decimal number to a binary number,and it seems like the last sentence have some problem. i know i can create a static vector to solve the problem,but i don't want to make it this way. how can i append a vector which is the return object of the recursion function?

vector<int> tenchangetwo(int num)
{
int i = num/2;
int j = num%2;
if(i==0)return vector<int>{j};
else return tenchangetwo(i).push_back(j);
}



Line 6: could not convert 'tenchangetwo(int)().std::vector<_Tp, _Alloc>::push_back >(j)' from 'void' to 'std::vector'

Answer

push_back is a void method so you just need to get the reference at first:

vector<int> tenchangetwo(int num)
{
    int i = num/2;
    int j = num%2;
    if(i==0)return vector<int>{j};
    else {
      auto temp = tenchangetwo(i);
      temp.push_back(j);
      return temp;
    }
}

however this will not do much, so you should rather add the vector as an argument and create it prior to calling this recursive function:

void tenchangetwo(int num, vector<int> result)
{
    int i = num/2;
    int j = num%2;
    if (i > 0) {
        result.push_back(j);
        tenchangetwo(i, result);
    }
}
Comments