For every run of x or more consecutive zeros in a list in C++, I would like to delete all zeros in the run except for x of them. If x = 0, then delete all zeros.
I was thinking of a C++ function that took a list, list<int> L, and a number, int x, as inputs.
For example, let L = {7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8}.
- If
x = 0, then returnL = {7, 12, 2, 27, 10, 8} - If
x = 1, then returnL = {7, 0, 12, 0, 2, 0, 27, 10, 0, 8} - If
x = 2, then returnL = {7, 0, 12, 0, 0, 2, 0, 0, 27, 10, 0, 0, 8} - If
x = 3, then returnL = {7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 8} - If
x = 4, then returnL = {7, 0, 12, 0, 0, 2, 0, 0, 0, 27, 10, 0, 0, 0, 0, 8}(Same as originalL) - If
x >= 5, then return originalLas there are no runs of 5 or more consecutive zeros.
Several months ago, I asked the same question above using Python (stackoverflow.com/questions/11732554/...) and received excellent answers. Now I would like to complete this task in C++.
Any help would be sincerely appreciated.
Here's some code that should do the job:
Basically, you count how many zeros you have in a row, and delete them if you're
> x, otherwise continue iterating the list.Giving the following output:
7,12,2,27,10,87,0,12,0,2,0,27,10,0,87,0,12,0,0,2,0,0,27,10,0,0,87,0,12,0,0,2,0,0,0,27,10,0,0,0,87,0,12,0,0,2,0,0,0,27,10,0,0,0,0,87,0,12,0,0,2,0,0,0,27,10,0,0,0,0,8It depends on your style,
remove_ifmight be the moreC++ish way to do it, but I find it clearer to manipulate the values directly and it doesn't involve a new data type (astructto keep track of the number of0you encountered).The reason why the code doesn't work using
NTL::ZZis simply that there is no implicit conversion between anint,0, and aNTL::ZZbig number, therefore it cannotremove(0). What you can do though could be something along the lines of: