std::equal

1.
1
2
3
4
5
std::vector<unsigned char> vec;
vec.resize(5, 0x61);
std::string str = "aa";
if (std::equal(vec.begin(), vec.end(), str.begin())) {
...

String is shorter than vector - is this code safe?

2.
1
2
3
4
std::vector<unsigned char> vec;
vec.resize(5, 0x61);
if (std::equal(vec.begin(), vec.end(), "aaaaa")) {
...

Is this code ok?
Can i put string as third argument to std::eqaul?
I tested it, and it works, but i just want to be sure:)
1.
No it's not safe.

2.
Yes it works because the string literals gives you a pointer (const char*) that can work as an iterator. The string still needs to be at least as long as the vector though.
The first example is unsafe (more precisely is invalid) because the size of the string is less than the size of the vector. The behavior of the example is undefined.
The second code is safe.
Take into account that in the first example you are trying to compare unsigned char with char (the value type of std::string) which can behave as signed char. So you can get the result other you hoped to get.

Last edited on
you are trying to compare unsigned char with char

I know for 100%, that vector contains only ascii lower letters (0x61 - 0x7A)
Is it ok to compare unsigned char with signed char in that case?
Yes it is ok. In this example it is unimportant that you can compare unsigned char with signed character because equivalence is used. But in other cases where for example operator < is used it is important.
Last edited on
Topic archived. No new replies allowed.