I am just starting to use C++ iterators, so this code may be very bad compared to experienced programmers, but I would love all help because I am trying to get better with them. In this function, I am attempting to use a reverse iterator's position to add a comma in between each 3 letters of a number. Ex: 100000 to 100,000.
I was able to fix all errors and warnings, but the code wont output anything. It also says that I have a SIGTRAP that my program received. Please help me.
#include <iostream>
#include <vector>
#include <iterator>
#include <string>
using namespace std;
int main() {
string text = "100000";
vector<char> news{};
for (size_t i{}; i < text.size(); i++) {
news.push_back(text[i]);
}
for (vector<char>::reverse_iterator it = news.rbegin(); it != news.rend(); it = it + 2) {
news.insert(it.base(), ',');
}
string fin;
for (char i: news)
fin.push_back(i);
cout << fin;
return 0;
}
I normally would not use a
vector
this type of operation but for the sake of your learning, here are some mistakes you have made:vector::insert
manual:What happens to iterators when you modify a container is something you have to keep in mind at all time and be careful with.
Also, generally speaking, if you can know the size of a container in advance, you should reserve the memory to avoid reallocation. I have not bothered double-checking the calculation below but I know the size I reserved is either correct or 1 byte over correct, aka accurate enough.
it + 1
is the past-the-end iterator of yourvector
,it = it + 2
is undefined behavior (UB). The code would need something to know when to stop incrementing the iterator before getting to close torend()
(as opposed to "before reachingrend()
"), which is not a completely obvious condition.BTW, I doubt increasing the iterator by 2 would put a comma every 3 characters (not that having commas more often than desired would cause a crash nor be difficult to adjust). On the same note, you are not using the return value of
vector::insert
.Correcting those mistakes results in the following code:
A better way to handle this case is by avoiding using a vector completely, which would also make it more efficient. I like the approach of 2 nested loops increasing the same iterator.
For that 2nd snippet below, text is processed in left-to-right order, as appending text is the natural way strings work (not prepending, not inserting).