【发布时间】:2019-06-14 19:57:30
【问题描述】:
假设你有一个 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() 从每个字符串中获取一个 char*。不确定这是否能有效地比较字符串,你试试看:
stdString.c_str() == boostString.c_str() // compiles, but comparison returns false
然后您尝试仅使用 std::string 中的 c_str() 方法:
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
【问题讨论】:
标签: c++ string boost string-comparison c++-standard-library