英文:
Comparing an std::string_view and a char
问题
以下是您要翻译的代码部分:
#include <iostream>
#include <string_view>
#include <string>
using namespace std::string_view_literals;
int main() {
const char bar{'a'};
std::string_view sep{"a"sv};
std::cout << sep.compare(&bar) << std::endl;
std::cout << sep.compare(std::string_view(&bar)) << std::endl;
std::cout << (sep == &bar)<< std::endl;
std::cout << (sep == std::string_view{&bar}) << std::endl;
}
请注意,由于您要求只提供翻译,我没有回答您的问题。如果您需要进一步的解释或回答,请随时提出。
英文:
The following code
#include <iostream>
#include <string_view>
#include <string>
using namespace std::string_view_literals;
int main() {
const char bar{'a'};
std::string_view sep{"a"sv};
std::cout << sep.compare(&bar) << std::endl;
std::cout << sep.compare(std::string_view(&bar)) << std::endl;
std::cout << (sep == &bar)<< std::endl;
std::cout << (sep == std::string_view{&bar}) << std::endl;
}
produces different results on different compilers:
- -1, -1, 0, 0 on gcc 9.4, 9.5, 12.2
- 0, 0, 1, 1 on clang 11
(godbolt)
By massaging the code a bit (adding / removing spaces), I can sometimes get 0&1 on some of the GCC builds. The clang 11 build consistenly prints 0 & 1.
Is the behavior of GCC justified? If so, how do I correctly compare an std::string_view with a char?
答案1
得分: 1
std::string_view::compare
比较两个视图。将视图中的char
与char
进行比较:
std::cout << (sep.at(0) == bar) << '\n';
如果要将char
转换为string_view
,然后比较这两个视图(假设我们要比较的是视图中的第一个字符):
assert(sep.compare(0, 1, &bar, 1) == 0);
英文:
> how do I correctly compare an std::string_view with a char?
std::string_view::compare
compares two views. Comparing a char
from view with char
:
std::cout << (sep.at(0) == bar) << '\n';
If you want to convert the char
to a string_view
and then compare the views (presuming that it is the first character from the view we want to compare with):
assert(sep.compare(0, 1, &bar, 1) == 0);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论