Reputation: 21
char mychars[] = { 'A','B','C','D' };
vector<int> a(mychars, mychars + 4);
cout << a[0] << " " << a[1] << " " << a[2] << " " << a[3];
why it's output is 65 66 67 68 ? i have created vector of int so it should have stored A,B,C,D in one int of 4 bytes but it is storing them individually by creating 4 ints why ?
Upvotes: 0
Views: 69
Reputation: 182
When you pass an array of chars to the constructor, the constructor assumes that the array contains chars and hence loops through the array, casts each char to an integer and creates the vector from the integers.
I guess you could do a little "hack" with pointers in order to achieve
the desired result. Instead of passing a pointer to char to the vector constructor,
you can cast mychars
to an integer pointer so that c++ views the 4 bytes consumed
by mychars array as a single integer.
However, you should be careful about the size of the supposed integer array that is used as offset to the constructor.
In your case, the offset is 1 instead of 4, because for every 4 chars you have 1 integer. However, I replaced it with the more general sizeof(mychars)/sizeof(int))
in order to account for arrays with more than 4 elements (the elements of mychar must be a multiple of 4).
#include <iostream>
#include <vector>
using namespace std;
/*
Id is between 0 and 3 (inclusive)
*/
char char_from_int(int number, int id) {
return (number >> (8*id)) & 0xff;
}
int main()
{
char mychars[] = { 'A','B','C','D','e','f','g','h' };
vector<int> a((int*)mychars, (int*)mychars +sizeof(mychars)/sizeof(int));
for(int i=0;i<a.size();i++) {
cout<<char_from_int(a[i],0)<<char_from_int(a[i],1)<<char_from_int(a[i],2)<<char_from_int(a[i],3)<<endl;
}
return 0;
}
Upvotes: 0
Reputation: 1679
No. a vector does not know the internal representation of the contained object. When you construct a vector using the range constructor, it will only constructs a container with as many elements as the range [first,last), with each element emplace-constructed from its corresponding element in myChars array, in the same order.
Upvotes: 1