比较一个 std::string_view 和一个 char

huangapple go评论61阅读模式
英文:

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比较两个视图。将视图中的charchar进行比较:

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 &lt;&lt; (sep.at(0) == bar) &lt;&lt; &#39;\n&#39;; 

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, &amp;bar, 1) == 0);

huangapple
  • 本文由 发表于 2023年3月3日 18:52:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75626124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定