Using vector as returning function

Write your question here.
Hello, I am new to the community. I want to ask a question about my code. I want to return a vector from my function dec2Bin. In main, when I call this function, I only get one value inside my vector. I don't know what is wrong with it, can someone help me please. This is the code I have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
vector<int> dec2Bin(int n){
    vector<int> v;
    if (n == 0){
        v.push_back(0);
        return v;
    }
    
    else if (n == 1){
        v.push_back(1);
        return v;
    }
    
    else{
        v.push_back(n%2);
        return dec2Bin(n/2);
    }
}
1
2
3
4
5
6
7
8
9
10
11
std::vector< unsigned int > dec2Bin( unsigned int n ) {

    if( n < 2 ) return {n} ; // return a vector containing the one element 0 or 1

    else {

        std::vector< unsigned int > vec = dec2Bin(n/2) ; // get the higher order bits
        vec.push_back(n%2) ; // add the least significant bit at the end
        return vec ;
    }
}

http://coliru.stacked-crooked.com/a/4ea80a5096baf963
This same code in a compact pseudo-ish code:

1
2
3
4
5
function dec2Bin(number) {
  if (number == 0) return an_array_containing(0);
  if (number == 1) return an_array_containing(1);
  return dec2Bin(number % 2);
}


You're getting a single value because that's what you told your code to do.


Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
using namespace std;

using vec = vector<bool>;
vec operator + ( vec v, int i ){ v.push_back( i ); return v; }
ostream &operator << ( ostream &strm, const vec &v ) { for ( auto e : v ) strm << e; return strm; }


vec dec2Bin( unsigned int n ) { return n < 2 ? vec( 1, n ) : dec2Bin( n / 2 ) + ( n % 2 ); }


int main()
{
   for ( unsigned int i = 0; i < 32; i++ ) cout << i << ": " << dec2Bin( i ) << '\n';
}

Last edited on
Registered users can post here. Sign in or register to post.