Допустим, у вас есть std :: string и boost :: container :: string, например:
std::string stdString = "This is a test";
boost::container::string boostString = "This is a test";
Допустим, вы хотите сравнить их содержимое;следующее невозможно, потому что мы не можем сравнивать их типы:
stdString == boostString // no operator "==" matches these operands
Затем вы решаете использовать оба их метода .c_str (), чтобы получить символ * из каждой строки.Не будучи уверенным, что это эффективно сравнивает строки, вы пытаетесь это сделать:
stdString.c_str() == boostString.c_str() // compiles, but comparison returns false
Затем вы пытаетесь использовать только метод c_str () из std :: string:
stdString.c_str() == boostString // compiles, and comparison seems fine
Вы пробуете противоположное из любопытства, и оно также работает:
stdString == boostString.c_str() // compiles, and comparison seems fine
Итак, вопрос в том, почему эти два последних сравнения, кажется, работают нормально, когда первое не сработало?
Дополнительный вопрос: Является ли это ненадежным способом сравнения содержимого этих строк?
Полный пример кода:
#include <boost/container/string.hpp>
#include <iostream>
int main(int argc, char *argv[])
{
std::string stdString = "This is a test";
boost::container::string boostString;
for (int i = 0; i < 2; ++i)
{
if (i == 0)
{
boostString = "This is a test";
std::cout << "Both strings have the same content." << std::endl << std::endl;
}
else
{
boostString = "This is z test";
std::cout << std::endl << std::endl;
std::cout << "Both strings are different from each other." << std::endl << std::endl;
}
std::cout << "stdString.c_str() == boostString.c_str() comparison is : ";
if (stdString.c_str() == boostString.c_str())
std::cout << "true" << std::endl;
else
std::cout << "false" << std::endl;
std::cout << "stdString.c_str() == boostString comparison is : ";
if (stdString.c_str() == boostString)
std::cout << "true" << std::endl;
else
std::cout << "false" << std::endl;
std::cout << "stdString == boostString.c_str() comparison is : ";
if (stdString == boostString.c_str())
std::cout << "true" << std::endl;
else
std::cout << "false" << std::endl;
}
return 0;
}
Вывод, предоставленный примером:
> Both strings have the same content.
>
> stdString.c_str() == boostString.c_str() comparison is : false
> stdString.c_str() == boostString comparison is : true
> stdString == boostString.c_str() comparison is : true
>
>
> Both strings are different from each other.
>
> stdString.c_str() == boostString.c_str() comparison is : false
> stdString.c_str() == boostString comparison is : false
> stdString == boostString.c_str() comparison is : false