迭代器
返回指向起始的迭代器
std::basic_string<CharT,Traits,Allocator>::begin
std::basic_string<CharT,Traits,Allocator>::cbegin
iterator begin(); (C++11 前)
iterator begin() noexcept; (C++11 起)
const_iterator begin() const; (C++11 前)
const_iterator begin() const noexcept; (C++11 起)
const_iterator cbegin() const noexcept; (C++11 起)
返回指向字符串首字符的迭代器。
begin()
返回可变或常迭代器,取决于 *this 的常性。
cbegin()
始终返回常迭代器。它等价于 const_cast<const basic_string&>(*this).begin() 。
返回指向末尾的迭代器
std::basic_string<CharT,Traits,Allocator>::end
std::basic_string<CharT,Traits,Allocator>::cend
iterator end(); (C++11 前)
iterator end() noexcept; (C++11 起)
const_iterator end() const; (C++11 前)
const_iterator end() const noexcept; (C++11 起)
const_iterator cend() const noexcept; (C++11 起)
返回指向后随字符串末字符的字符的迭代器。此字符表现为占位符,试图访问它导致未定义行为。
参数 (无)
返回值 指向后随尾字符的字符的迭代器
复杂度 常数
返回指向起始的逆向迭代器
std::basic_string<CharT,Traits,Allocator>::rbegin
std::basic_string<CharT,Traits,Allocator>::crbegin
reverse_iterator rbegin(); (C++11 前)
reverse_iterator rbegin() noexcept; (C++11 起)
const_reverse_iterator rbegin() const; (C++11 前)
const_reverse_iterator rbegin() const noexcept; (C++11 起)
const_reverse_iterator crbegin() const noexcept; (C++11 起)
返回指向逆转字符串首字符的逆向迭代器。它对应非逆向字符串的末字符。
参数 (无)
返回值 指向首字符的逆向迭代器
复杂度 常数
返回指向末尾的逆向迭代器
std::basic_string<CharT,Traits,Allocator>::rend
std::basic_string<CharT,Traits,Allocator>::crend
reverse_iterator rend(); (C++11 前)
reverse_iterator rend() noexcept; (C++11 起)
const_reverse_iterator rend() const; (C++11 前)
const_reverse_iterator rend() const noexcept; (C++11 起)
const_reverse_iterator crend() const noexcept; (C++11 起)
返回指向后随逆向字符串末字符的字符的逆向迭代器。它对应前驱非逆向字符串首字符的字符。此字符表现为占位符,试图访问它会导致未定义行为。
参数 (无)
返回值 指向后随末字符的字符的逆向迭代器
复杂度 常数
代码示例
string str = "abcdefg hijk";
// 通过const_iterator迭代器顺序遍历string
std::cout << "const_iterator: " << std::endl;
for (string::const_iterator it = str.cbegin(); it != str.cend(); it++)
{
std::cout << *it << " " ;
}
std::cout << std::endl;
// 通过iterator迭代器顺序修改string
std::cout << "iterator: " << std::endl;
for (string::iterator it = str.begin(); it != str.end(); it++)
{
*it += 3;
}
std::cout << str << std::endl;
// 通过const_reverse_iterator迭代器逆序遍历string
std::cout << "const_reverse_iterator: " << std::endl;
for (string::const_reverse_iterator it = str.crbegin(); it != str.crend(); it++)
{
std::cout << *it << " " ;
}
std::cout << std::endl;
// 通过reverse_iterator迭代器逆序修改string
std::cout << "reverse_iterator: " << std::endl;
for (string::reverse_iterator it = str.rbegin(); it != str.rend(); it++)
{
*it += 3;
}
std::cout << str << std::endl;