That's incredible. I work out a binary converter which convert decimal value into binary.A lot of people has already done the same that before,but now I also has maneged to do it. I didn't think so far that this task can be coded in such a simply and brief way. How effective c++ sometimes can be! Here you are:
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
vector<int>binary(1); int i, s=0 ;
vector<int> Binary(int dec);
int main(){
cout<<"Give a positive integer: ";
while(cin>>i){ cin.ignore(); Binary(i);
cout<<endl; i = binary.size();
while(i>0){ i -=1; s+=sizeof(binary[i]);
cout<<binary[i]<<" ";
} cout<<"\tThe size of your vector in byte: "<< s;
cout<<endl<<endl; binary.resize(1); s=0; main(); }
cin.get();
}
vector<int> Binary(int dec){ int l=1, m=0; bool flag = 0; binary[0]=0;
loop: while(l<dec){
l*=2; m++; if (flag==false && l<=dec) binary.push_back(0);
}
if(dec==0){binary[0]=0;}
else if(dec==1){binary[0]=1;}
else if(dec-l==0)binary[m]=1;
else{binary[m-1]=1; dec -= l/2; flag = true; l=1; m=0; goto loop;}
}
My binary converter trigger question about vector, datatypes, sizeof op. and their usage which may be worth to discuss.
However this solvation put up some brand new question to me as well.
The point is, the following behaviour of the code: If you replace the type of the data that binary vector contains with bool
type (allocated 1byte space) the program doesn't do the converting in the right way.
The following event happens to programme with vector of bool type:
1st input(any power of the number two): e.g. 16 1st output: 10000
2nd input(any number that isn't power of two): e.g. 7 2nd output: 000 (the number of digit is right)
Then the program goes well without any mistake.
Am I right when I come to the conclusion that vector class is a description (designe) of such data containers that don't
work with bool datatype properly, Maybe, there are defined flag bits which needs to mark the beginning or the end of the
allocated memory region, for example.
The another event which not cause problem just simply new for me. The behavour of the sizeof operator:
In the case of code with vector of integer type (allocated 4 byte space for each element) : e.g.:
1st input: 3 1st output: 11 The size of your vector in byte 8
2nd input: 16 2nd output: 10000 The size of your vector in byte 20
In the case of code with vector of bool type (allocated 1 byte space for each element): e.g.:
1st input: 3 1st output: 11 The size of your vector in bit 16
2nd input: 16 2nd output: 10000 The size of your vector in bit 40
Yes, you can see well, you must overwrite even the text part "in byte" as I think sizeof operator, in case of bool type,
calculat tha space of mamory not byte by byte but bit by bit. That's the curious happening suprises me.