如何在STL中使用Iterator指针

Gri*_*fin 1 c++ stl

嘿,我对迭代器的工作方式有点困惑.const_iterator在这种情况下,特别是一个类.我知道它们实际上只是指向字符串的特定元素或者你正在使用的任何东西的指针,但在这种情况下: 我会认为它们是一个内存地址,因此你不能只是添加整数来实现字符串中的下一个项目.

这是我困惑的代码:

string::const_iterator iCharacterLocater;

for ( iCharacterLocater = strSTLString.Begin();
      iCharacterLocater != strSTLString.end();
      ++ iCharacterLocater )
{
    cout << "Character [ " << nCharOffset ++ <<"] is: ";
    cout << *iCharacterLocater << endl;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!!=)

zne*_*eak 7

这比那复杂一点.迭代器引用同名GOF设计模式,并且在C++中,它们的应用方式与指针类似.C++允许您重载运算符,这意味着自定义类型在使用某些运算符时可以以特定方式运行.

C++中几种类型的迭代器,具有不同的功能级别.向量和字符串的底层表示都非常简单,迭代器的行为与指针非常相似:您可以向它们添加数字以查找特定项.例如,myVector.begin() + 5将迭代器返回到向量的第6个元素(第6个因为索引从零开始,0将是第一个).字符串迭代器也允许你这样做.

字符串常量迭代器的行为与常量char指针非常相似.当你看到const char* foo,这并不意味着你无法改变foo- 只是意味着你无法改变它指向的东西.所以当你看到时std::string::const_iterator foo,并不意味着你无法改变foo.它只是意味着你无法改变它引用的内容.

const char* foo = "abcd";
foo = "zyxwvu"; // valid: the pointer itself can be changed
*foo = 't'; // invalid: the pointed data can't be changed
*(foo + 2) == 'x'; // true

std::string myString = "zyxwvu";
std::string::const_iterator foo = myString.begin();
foo = myString.begin() + 2; // valid: the iterator itself can be changed
*foo = 't'; // invalid: the pointed data can't be changed
*(foo + 2) == 'x'; // true
Run Code Online (Sandbox Code Playgroud)

如果不尝试修改数据,则迭代器和const迭代器的行为相同.此外,除了两者之间没有直接转换之外,指向字符串内容的指针和字符串内容的迭代器的行为完全相同.