为什么我的两个元组包含以相同方式创建的字符串,而不是相等的? [英] Why are my two tuples containing strings, created the same way, not equal?
问题描述
我正在使用 Microsoft Visual C++ 将以下程序编译为 C++20 程序:
I'm compiling the following program using Microsoft Visual C++, as a C++20 program:
#include <iostream>
#include <tuple>
int main()
{
auto t1 = std::make_tuple("one", "two", "three");
auto t2 = std::make_tuple("one", "two", "three");
std::cout << "(t1 == t2) is " << std::boolalpha << (t1 == t2) << "\n";
std::cout << "(t1 != t2) is " << std::boolalpha << (t1 != t2) << "\n";
return 0;
}
当我运行它时,我看到以下输出:
When I run it, I see the following output:
(t1 == t2) is false
(t1 != t2) is true
元组是相同的,为什么会出现错误的比较结果?我该如何解决这个问题?
The tuples are identical, so why does it have wrong comparison results? How do I fix this?
推荐答案
您正在比较指向字符缓冲区的指针,而不是字符串.
You are comparing pointers to buffers of characters, not strings.
有时编译器会将两个不同的一个"
转入同一个缓冲区,有时不会.
Sometimes the compiler will turn two different "one"
s into the same buffer, sometimes it will not.
在你的情况下,它不是.可能是调试版本.
In your case, it isn't. Probably a debug build.
添加#include
,然后
using namespace std::literals;
auto t1 = std::make_tuple("one"sv, "two"sv, "three"sv);
auto t2 = std::make_tuple("one"sv, "two"sv, "three"sv);
你会得到你所期望的.(在 pre-c++17 编译器,使用
和 "s
而不是
和 ";"sv
).
and you'll get what you expect. (In pre-c++17 compilers, use <string>
and ""s
instead of <string_view>
and ""sv
).
这篇关于为什么我的两个元组包含以相同方式创建的字符串,而不是相等的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!