so iterating through a sequence of characters using an index is out of date |
A range-based for loop DOES iterate through a container sequentially, just not in your "this is how I was taught so everyone must learn it this way" manner.
Since you are so allergic to the concept of
auto:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
#include <string>
int main()
{
std::string passCode { "1 2 a 4" };
for (char& itr : passCode)
{
if (itr == ' ')
{
itr = '_';
}
}
std::cout << passCode << '\n';
}
| |
we are helping a novice, not building a commercial application |
Too many commercial apps suffer from legacy code that has to be coddled and cajoled just to survive should a bug need to be fixed or a capability requires modification.
Why accept without comment instructing beginners about
std::string? Clearly that is a high level construct unsuitable except for experts, right? C strings should be the only allowed method for dealing with character sequences for noobs.
I don't believe there is
One True Way To Do Code.
A very common and yet mythical idea is "to learn C++ one must first learn C." That is the 1st of 5 popular myths about C++.
Let Bjarne Stroustup explain:
https://isocpp.org/blog/2014/12/myths-1
For someone who complained about range-based for loops, auto, etc, it is a bit strange you would show
std::replace to a beginner.
In this topic using std::replace_if would be the way to go. |
std::replace doesn't need a predicate function when the replacement is as simple as '_' for ' '.
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string passCode { "1 2 a 4" };
std::replace(passCode.begin(), passCode.end(), ' ', '_');
std::cout << passCode << '\n';
}
| |
According to the experts we should never write loops.
If there is no STL algorithm we should write our own. |
Writing an algorithm that iterates through a container, especially when done sequentially, kinda requires some form of a loop. Look at the
possible implementations of
std::replace &
std::replace_if:
https://en.cppreference.com/w/cpp/algorithm/replace