我试图掌握迭代器的窍门,我会发布失败的尝试,但我没有看到任何意义,所以我只会发布我试图用迭代器重写的代码。
如何让类使用向量的迭代器来跟踪位置,而不是制作自己的临时迭代器?
具体来说,我试图跟踪固定循环中已经打印了哪些字母。
实时代码
代码预览
#include <vector>
#include <cstdio>
class ABC
{
protected:
std::vector<char> ABCs;
int currentLetter;
public:
ABC():currentLetter( 0 ){}
void AddLetter( char Letter )
{
ABCs.push_back( Letter );
}
char getLetter( int position )
{
return ABCs.at( position );
}
int getLetterPosition()
{
return currentLetter;
}
void setLetterPosition( int newPosition )
{
currentLetter = newPosition;
}
};
void printSentence( ABC * alphabet, int limit )
{
for( int i = 0; i < limit; i += 2 )
{
printf( "The current letter is %c, the letter after is %c \n", alphabet->getLetter( alphabet->getLetterPosition() ), alphabet->getLetter( alphabet->getLetterPosition() + 1 ) );
alphabet->setLetterPosition( alphabet->getLetterPosition() + 2 );
}
}
int main()
{
ABC alphabet;
ABC * alphabetPointer = &alphabet;
for( char letter = 'a'; letter < 'z'; letter++ )
{
alphabet.AddLetter( letter );
}
printf( "%s\n" , "printSentence() with param of four letters." );
printSentence( alphabetPointer, 4 );
//again
printf( "%s\n" , "printSentence() with param of six letters." );
printSentence( alphabetPointer, 6 );
return 0;
}