Reputation: 11
I have a string value:
std::string bl="0x"+"a0";
//where a0 is a heva number. I did add 0x because i want my vector
std::vector<unsigned char>vect;
vect.push_back(bl.begin(), bl.end());
//error is not working.
Need help. What to do? I am working in ubuntu c++ code.
Upvotes: 1
Views: 8044
Reputation: 2368
Do not use push_back(...), it classically can not push an interval, it pushs the one item. You can use assign(begin, end) or insert(iter_position, vect_begin, vect_end).
For example:
vect.assign(bl.begin(), bl.end());
vect.insert(vect.begin(), bl.begin(), bl.end());
vect.push_back(bl[0]); // '0'
vect.push_back(bl[1]); // 'x'
vect.push_back(bl[2]); // 'a'
vect.push_back(bl[3]); // '0'
Upvotes: 1
Reputation: 385088
I'm not 100% sure on what you want, because of the contents of your string bl
.
Taking you literally:
std::string bl = "0xA0";
// ^ this is what you meant to write ("0x"+"A0" is actually adding pointers)
std::vector<unsigned char> vect;
vect.insert(vect.begin(), bl.begin(), bl.end());
// ^ you use ranges with .insert not push_back
Or you can use the constructor:
std::string bl = "0xA0";
std::vector<unsigned char> vect(bl.begin(), bl.end());
// ^ you use ranges with the constructor too
In both these cases, the vector contains the characters '0', 'x', 'A' and '0'.
Alternatively, you might have meant for the string to contain the single character whose ASCII value is (in hex) 0xA0
. If so, "0x"+"a0"
is very wrong.
std::string bl = "\xA0";
std::vector<unsigned char> vect(bl.begin(), bl.end());
The vector contains one character, whose ASCII value is 0xA0
.
I hope this helps.
Upvotes: 7
Reputation: 3407
give type to vector.
std::vector vec;
to
std::vector< string> vec or whatever you need. and vector push_back signature is void push_back(const T&). It does not take two arguments.
Upvotes: 0
Reputation: 3208
the reason is simple, you are trying to insert an invalid element into your container.
std::string has no implicit conversion to change its data into vector of unsigned char.
Upvotes: -1