help me understand strings?
im starting to get confused. i would appriciate it if someone could help me with my noobish understandings...
1. when do i use string::size_type vs using the iterator for string?
for example, i would like to examine each character in a string. therefore i would do something like
int index = 0;
while ( index < mystring.size)
{
cout << mystring.at(stringindex);
}
now i could also print out each character in a string via the iterator?
for(myiterator = st1.begin(); myiterator != st1.end(); myiterator ++)
{
if( *myiterator == 'h')
{
do something
}
}
///////
i guess when to find out the size or length or get what is in a particular space in a string, use the size_t....when using a string function, use the iterator???
Re: help me understand strings?
bbq,
This is a very rich topic.
I believe that most developers tend to avoid the use of iterators for strings. Recall that the std::string, much like the std::vector<T>, offers a clean indexing operator. In addition, std::string has the member function at(...).
It might be wise at first to avoid using iterators for std::string's and simply, until a clearer understanding has been reached, use the size_type combined with size(...) as well as operator[](...) and/or at(...).
The power of iterators comes with template such as std::list<T>.
P.S. Do not forget the parentheses in the call to mystring.size().
Sincerely, Chris. :thumb:
Re: help me understand strings?
Using iterators is preferable for a couple of reasons:
Code is more generic, so you can use any other container instead of the std::string.
It may be faster (especially it may reduce the number of indirection needed to access a character).
However, if it makes the code look less pretty, or if you fear errors, you can use indexes.
For indexes, you should not use int, but std::string::size_type.