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

C++StringIterator

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

Like this:


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



//Use the iterator...
++it;
//...

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


Solution 2 - C++

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.

Solution 3 - C++

You can use standard STL function distance as mentioned before

index = std::distance(s.begin(), it);

Also, you can access string and some other containers with the c-like interface:

for (i=0;i<string1.length();i++) string1[i];

Solution 4 - C++

A good practice would be based on readability, e.g.:

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

Or:

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

Or your original:

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

Etc. Whatever is easiest and cleanest to you.

It's not clear there is any one best practice as you'll need a counter variable somewhere. The question seems to be whether where you define it and how it is incremented works well for you.

Solution 5 - C++

For strings, you can use string.c_str() which will return you a const char*, which can be treated as an array, example:

const char* strdata = str.c_str();

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

Solution 6 - C++

I would use it-str.begin() In this particular case std::distance and operator- are the same. But if container will change to something without random access, std::distance will increment first argument until it reach second, giving thus linear time and operator- will not compile. Personally I prefer the second behaviour - it's better to be notified when you algorithm from O(n) became O(n^2)...

Solution 7 - C++

Since std::distance is only constant time for random-access iterators, I would probably prefer explicit iterator arithmetic. Also, since we're writing C++ code here, I do believe a more C++ idiomatic solution is preferable over a C-style approach.

string str{"Test string"};
auto begin = str.begin();

for (auto it = str.begin(), end = str.end(); it != end; ++it)
{
    cout << it - begin << *it;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpierrotlefouView Question on Stackoverflow
Solution 1 - C++Leandro T. C. MeloView Answer on Stackoverflow
Solution 2 - C++TheUndeadFishView Answer on Stackoverflow
Solution 3 - C++AndrewView Answer on Stackoverflow
Solution 4 - C++Alex ReynoldsView Answer on Stackoverflow
Solution 5 - C++jscharfView Answer on Stackoverflow
Solution 6 - C++maxim1000View Answer on Stackoverflow
Solution 7 - C++user2015735View Answer on Stackoverflow