Please explain why in some cases it is true
and in other cases it is false
, although in all three cases the addresses of the strings are different?
In the first case, vectors are simply initialized with string literals and then iterators of those strings are passed to the
equal
function. The result istrue
. Since C-style strings have no comparison operators, their addresses are compared, but when the addresses of strings in vectors are output, it shows that the addresses are not equal. Why then does the result of the equal function gettrue
?In the second case, vectors are already initialized from pointers to C-style strings. In this case
true
is also returned, though again the string addresses are different. Why?In the third case, vectors are initialized using two-dimensional arrays. In this case, again, the addresses of strings in vectors are different, but this time the output is
false
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
int main()
{
std::cout << std::boolalpha;
std::vector<const char*> vec_e{ "String" };
std::vector<const char*> vec_f{ "String" };
std::cout << equal(vec_e.begin(), vec_e.end(), vec_f.begin()) << std::endl; // true
std::cout << &vec_e[0] << std::endl;
std::cout << &vec_f[0] << std::endl;
const char* str_a[1] = { "Hello" };
const char* str_b[1] = { "Hello" };
std::vector<const char*> vec_a(std::begin(str_a), std::end(str_a));
std::vector<const char*> vec_b(std::begin(str_b), std::end(str_b));
std::cout << equal(vec_a.begin(), vec_a.end(), vec_b.begin()) << std::endl; // true
std::cout << &vec_a[0] << std::endl;
std::cout << &vec_b[0] << std::endl;
const char str_c[][6] = { "World" };
const char str_d[][6] = { "World" };
std::vector<const char*> vec_c(std::begin(str_c), std::end(str_c));
std::vector<const char*> vec_d(std::begin(str_d), std::end(str_d));
std::cout << equal(vec_c.begin(), vec_c.end(), vec_d.begin()) << std::endl; // false
std::cout << &vec_c[0] << std::endl;
std::cout << &vec_d[0] << std::endl;
return 0;
}