c++ ranges::starts_with与C样式字符串参数有什么关系?

i7uaboj4  于 2023-03-25  发布在  其他
关注(0)|答案(1)|浏览(88)

下面的代码打印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

}

为什么会这样?
我还注意到,如果两个stin相同,那么最后一个case也返回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,所以我不明白为什么

abithluo

abithluo1#

"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'}

相关问题