How can I iterate through a string and also know the index (current position)?


Often when iterating through a string (or any enumerable object), we are not only interested in the current value, but also the position (index). To accomplish this by using string::iterator we have to maintain a separate index:

string str ("Test string");
string::iterator it;
int index = 0;
for ( it = str.begin() ; it < str.end(); it++ ,index++)
    cout << index << *it;

The style shown above does not seem superior to the 'c-style':

string str ("Test string");
for ( int i = 0 ; i < str.length(); i++)
    cout << i << str[i] ;

In Ruby, we can get both content and index in a elegant way:

"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }

So, what is the best practice in C++ to iterate through an enumerable object and also keep track of the current index?

9/7/2018 9:53:00 AM

Accepted Answer

I've never heard of a best practice for this specific question. However, one best practice in general is to use the simplest solution that solves the problem. In this case the array-style access (or c-style if you want to call it that) is the simplest way to iterate while having the index value available. So I would certainly recommend that way.

8/22/2009 3:51:24 AM

Like this:

    std::string s("Test string");
    std::string::iterator it = s.begin();

    //Use the iterator...

    std::cout << "index is: " << std::distance(s.begin(), it) << std::endl;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow