gpt4 book ai didi

c++ - 迭代 std::string 元素

转载 作者:行者123 更新时间:2023-11-30 03:10:31 25 4
gpt4 key购买 nike

将迭代器移动到以下字符串元素是否需要常数时间:

std::string str // string of size 100 MB
std::string::iterator iter = str.begin();
std::advance(iter, str.size()-1);

像按索引搜索一样需要固定时间吗?

char c = str[str.size()-1];

最佳答案

是的,没错。这是由 C++ 标准(§24.3,迭代器操作)保证的:

Since only random access iterators provide + and - operators, the library provides two function templates advance and distance. These function templates use + and - for random access iterators (and are, therefore, constant time for them);

关于c++ - 迭代 std::string 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3087364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com