My single pass version of decimate() :
void decimate (std::vector<int>& a) { const std::size_t sz = a.size(); const std::size_t half = sz / 2; bool size_even = ((sz % 2) == 0); std::size_t index = 2; for (; index < half; index += 2) { a[index/2] = a[index]; } for (; index < sz; ++index) { a[(index+1)/2] = a[index]; a[index] = 0; } if (size_even && (half < sz)) { a[half] = 0; } }
and check it out:
#include <vector> #include <iostream> #include <cstddef> void decimate(std::vector<int> &v); void print(std::vector<int> &a) { std::cout << "{"; bool f = false; for(auto i:a) { if (f) std::cout << ", "; std::cout << i; f = true; } std::cout << "}" << std::endl; } void test(std::vector<int> v1, std::vector<int> v2) { auto v = v1; decimate(v1); bool ok = true; for(std::size_t i = 0; i < v1.size(); ++i) { ok = (ok && (v1[i] == v2[i])); } if (ok) { print(v); print(v1); } else { print(v); print(v1); print(v2); } std::cout << "--------- " << (ok?"ok":"fail") << "\n" << std::endl; } int main(int, char**) { test({}, {}); test({1}, {1}); test({1, 2}, {1, 0}); test({1, 2, 3}, {1, 3, 0}); test({1, 2, 3, 4}, {1, 3, 0, 0}); test({1, 2, 3, 4, 5}, {1, 3, 5, 0, 0}); test({1, 2, 3, 4, 5, 6}, {1, 3, 5, 0, 0, 0}); test({1, 2, 3, 4, 5, 6, 7}, {1, 3, 5, 7, 0, 0, 0}); test({1, 2, 3, 4, 5, 6, 7, 8}, {1, 3, 5, 7, 0, 0, 0, 0}); test({1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 3, 5, 7, 9, 0, 0, 0, 0}); test({1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {1, 3, 5, 7, 9, 0, 0, 0, 0, 0}); test({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, {1, 3, 5, 7, 9, 11, 0, 0, 0, 0, 0}); return 0; }