以下代码打印
1010
#include <iostream>
#include <range/v3/algorithm/starts_with.hpp>
int main () {
using namespace std::literals;
std::cout << ranges::starts_with("hello world"s, "hello"s)
<< ranges::starts_with("hello world"s, "hello")
<< ranges::starts_with("hello world", "hello"s)
<< ranges::starts_with("hello world", "hello") << std::endl; // prints 1010
}
为什么会这样?
我还注意到,如果两个刺痛相同,那么最后一个案例也会返回
1
:
std::cout << ranges::starts_with("hello world"s, "hello world"s)
<< ranges::starts_with("hello world"s, "hello world")
<< ranges::starts_with("hello world", "hello world"s)
<< ranges::starts_with("hello world", "hello world") << std::endl; // prints 1011
我知道
std::string
,例如 "bla"s
,是一个范围,而 char[N]
也是一个范围,给定一个常量 N
。所以我不明白为什么
像
"hello"
这样的字符串文字是一个 const char[N]
数组,其中 N
包含空终止符的空间,例如 char[6] = {'h','e','l','l','o','\0'}
.
像
"hello"s
这样的字符串文字是一个 std::string
对象,它的 size()
中不包含空终止符。
所以,你最终得到:
starts_with("hello world"s, "hello"s) = 1
// {'h','e','l','l','o',' ','w','o','r','l','d'}
// DOES begin with
// {'h','e','l','l','o'}
starts_with("hello world"s, "hello") = 0
// {'h','e','l','l','o',' ','w','o','r','l','d'}
// DOES NOT begin with
// {'h','e','l','l','o','\0'}
starts_with("hello world", "hello"s) = 1
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
// DOES begin with
// {'h','e','l','l','o'}
starts_with("hello world", "hello") = 0
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
// DOES NOT begin with
// {'h','e','l','l','o','\0'}
starts_with("hello world"s, "hello world"s) = 1
// {'h','e','l','l','o',' ','w','o','r','l','d'}
// DOES begin with
// {'h','e','l','l','o',' ','w','o','r','l','d'}
starts_with("hello world"s, "hello world") = 0
// {'h','e','l','l','o',' ','w','o','r','l','d'}
// DOES NOT begin with
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
starts_with("hello world", "hello world"s) = 1
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
// DOES begin with
// {'h','e','l','l','o',' ','w','o','r','l','d'}
starts_with("hello world", "hello world") = 1
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}
// DOES begin with
// {'h','e','l','l','o',' ','w','o','r','l','d','\0'}