Character_Legend_Output_String += *Character_Legend_Pointer + " ";
Looking at the types of the arguments here, it's presumably: string += char + constchar*
The right side is the += is a pointer plus an integral type. The char gets promoted to int: int + constchar *
which adds the int to the constchar * to create a new constchar *.
It's equivalent to this:
1 2 3 4
int index = *Character_Legend_Pointer;
constchar *array = " ";
constchar *tmpPointer = &array[index]; // out of bounds for any index >3
Character_Legend_Pointer += tmpPointer.
Your second example works because string lets you add chars and constchar*s.
> you are better off with a range based for loop, not sure why you think iterators are easier ?
For iterating through a single range, particularly without side-effects, range-based loops are almost always easier, cleaner, less error-prone. IMHO.
A version using range-based loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
std::string insert_spaces( const std::string_view& str, std::size_t num_spaces = 3 )
const std::string spaces( num_spaces, ' ' ) ;
std::string result ;
for( char c : str ) result += c + spaces ;
// knock off trailing spaces (uncomment if required)
// while( !result.empty() && result.back() == ' ' ) result.pop_back() ;
return result ;
I guess iterators are used in the original code because there is another thread where seeplus (who had been helping CVRIV) made a fairly strong push for favouring iterator based classical for loops over range-based loops.
made a fairly strong push for favouring iterator based classical for loops over range-based loops
if I'm remembering the right post, I don't think I made a strong push. I just showed how to do it right using iterators. I favour range-based for loops. I can't remember ever posting my code that used an iterator loop when a range-for could be used.