c++ - 为什么 string::begin 存在?

标签 c++ stl iterator stdstring

如果我没理解错的话,string::begin 返回指向字符串中第一个元素的指针。如果是这样,我们为什么不直接使用 &str 来获取指针。

是否存在使用 begin 更好的情况,还是我误解了它的功能?

最佳答案

If I understand correctly, string::begin returns the pointer to the first element in the string.

不,它向字符串中的第一个元素返回一个迭代器。它有助于使 std::string 与设计用于标准容器的语言结构(认为模板)兼容。

why wouldn't we just use &str to get the pointer.

一方面,那不是字符串第一个元素的地址吗?假设 str 是一个类型为 std::string 的变量,这将是一个对象的地址,除其他外,(通常)持有指向第一个元素的指针的字符串。 (如果你指的是 c_str() 成员函数,那么可以这样做,但它不是一个特别清晰和可读的语法。)

关于c++ - 为什么 string::begin 存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61283098/

相关文章:

c++ - 理解 char * 到 int * 的转换及其含义

C++ 如何访问和更改映射中对象的成员数据?

iterator - 这个Scheme列表迭代器如何使用call-with-current-continuation?

c++ - 在 STL 中使用字符串中的删除关键字?

java - 支柱2 : Displays table of Songs - null gets printed

c++ - 简单的 cin cout 代码由 "build and run"运行,但在 bin/debug/x.exe 中不起作用

c++ - getline() 如何在指针方面工作?

c++ - 没有互联网弹出窗口 Qt 和 QML(移动设备)

c++ - 在顶部插入时双端队列是否提供 O(1) 复杂度

c++ - 从 c++ std::vector 中删除所有项目