Using vector as returning function

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

 ``1234567891011121314151617`` ``````vector dec2Bin(int n){ vector 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); } }``````
 ``1234567891011`` ``````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:

 ``12345`` ``````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
 ``12345678910111213141516`` ``````#include #include using namespace std; using vec = vector; 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