I used a loop, like this:
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
void duplicateVec(vector<int>& v, const int timesOriginalSize = 2)
{
try {
const unsigned int vecSize = v.size();
for(unsigned int i = 0; i < (timesOriginalSize - 1) * vecSize; ++i)
v.push_back(v[i]);
}
catch (const std::bad_alloc&) {
cerr << "Out of memory! v.size() = " << v.size() << endl;
exit(EXIT_FAILURE);
}
}
int main() {
vector<int> v(10);
cout << "Before duplicating, v.size() = " << v.size() << endl;
duplicateVec(v);
cout << "After duplicating, v.size() = " << v.size() << endl;
return 0;
}
but I was wondering if there was any easier way to write this..Any ideas?
Aucun commentaire:
Enregistrer un commentaire