c++ - std::string s1 {"现代 C++", 3} 与 std::string s1 {str, 3}
问题描述
以下代码的输出让我感到困惑:
const std::string str = "Modern C++";
std::string s1 {"Modern C++", 3};
std::string s2 {str, 3};
std::cout << "S1: " << s1 << "\n";
std::cout << "S2: " << s2 << "\n";
输出:
> S1: Mod
> S2: ern C++
谁能解释这个结果?
解决方案
从:
https://en.cppreference.com/w/cpp/string/basic_string/basic_string
std::string s1 {"Modern C++", 3};
使用以下构造函数:
basic_string( const CharT* s,
size_type count,
const Allocator& alloc = Allocator() );
所以需要 3 个字符才能得到Mod
.
std::string s2 {str, 3};
将使用以下构造函数:
basic_string( const basic_string& other,
size_type pos,
const Allocator& alloc = Allocator() );
因此,从位置 3 开始获取字符串 : ern C++
。
推荐阅读
- sql - SQL 选择按 ID 分组的 Day IN 和 Day OUT
- elasticsearch - ElasticSearch - 按计划从远程重新索引,每天删除源索引
- python - 在 Python 中正确引用 JSON。字符串与整数和嵌套项
- python - 加入两个数据框,其中一个有两列要加入一列?
- docker - 无法从外部主机访问 Docker 部署的映像
- python - jinja2 格式过滤器 - 需要创建列
- c - x86 上的 Bison/Lex 段错误,但在 arm 上运行
- typescript - TypeScript 没有捕获未定义的变量?
- jquery - 如何为多个元素设置脚本
- angularjs - Angular Promise 有条件的