Reputation: 2134
I have a std::vector I want to overwrite with new elements that will make it larger as well. What would be the fastest/most memory efficient method to do this? Here's my naive implementation:
#include <vector>
int main() {
std::vector<int> smallVec(10, 1);
int bigVecSize = 100;
smallVec.clear();
for(int i = 0; i < bigVecSize; ++i)
smallVec.push_back(i);
}
Are there any C++11 features that might help? Thanks.
Upvotes: 2
Views: 812
Reputation: 736
Sorry, I don't have any idea with C++11.
But, I think it is more faster to copy memory by ::memcpy
.
#include <vector>
void overwrite(std::vector<int>& dst, const std::vector<int>& src)
{
/* some code - to check the valid of dst and src */
dst.resize(src.size());
::memcpy(dst.data(), src.data(), sizeof(int) * src.size());
}
int main(int argc, char* argv[])
{
// an example
std::vector<int> via, vib;
via.push_back(22);
via.resize(5, 1);
vib.push_back(123);
vib.resize(10, 2);
vib.push_back(123);
overwrite(via, vib);
return 0;
}
The data memory of std::vector
is always consequent, so you can copy memory from one std::vector
to another.
Note: You need to be careful when the item type of your std::vector
is the object what contain a/some pointer(s). Because the ::memcpy
just copy the address to another, don't copy the object of pointer.
Upvotes: 3
Reputation: 2898
smallVec.reserve(bigVecSize); can reserve enough space for the new elements.
try this code :
#include <vector>
#include <stdio.h> //for printf()
#include <stdlib.h> //for system()
#include <time.h> //for time() & time_t
int main() {
std::vector<int> smallVec(10, 1);
int bigVecSize = 1000000;
smallVec.reserve(bigVecSize);
smallVec.clear();
time_t ts,te;
ts=time(NULL);
for(int i = 0; i < bigVecSize; ++i)
smallVec.push_back(i);
te=time(NULL);
printf("%ld\n",te-ts);
}
use reserve reduce the time cost from 0.125s to 0.087s
in C++11 if user define element is used as element of vector , R-value reference can be used to reduce copy.
Upvotes: 1