简体   繁体   中英

Fastest way to pass raw array into std::vector

If I have an array of chars and I want to push the data into a std::vector , what is the fastest way to do this? I'm currently using a loop with the push_back method.

std::vector<char> vec;
char test[] = {'0', '1', '2', '3' };
for(size_t i = 0; i < test.size(); ++i)
  vec.push_back(test[i]);

Is there a way to push all the data at once?

Just pass the array start and end iterators into the vector constructor.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    char test[] = {'0', '1', '2', '3' };
    std::vector<char> vec(begin(test), end(test));

    for(auto c: vec){
        cout << c << '\n';
    }
}

This will be faster than your method as it will only require the vector to make a single allocation, instead of incrementally allocating and copying as the size of the vector grows.

If your vector is declared before the array, you could call reserve before the loop to ensure that only a single allocation occurs.

eg

vec.reserve(distance(begin(test), end(test)));

or use the overload of insert taking a range, instead of your loop.

vec.insert (begin(vec), begin(test), end(test));

Also note that c++ arrays have no member functions, so calling test.size() is not valid. std::array however has a size member function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM