Best way to split a vector into two smaller arrays?

Use iterators.

std::vector<int> lines;
// fill
std::size_t const half_size = lines.size() / 2;
std::vector<int> split_lo(lines.begin(), lines.begin() + half_size);
std::vector<int> split_hi(lines.begin() + half_size, lines.end());

Since iterator ranges represent half open ranges [begin, end), you don’t need to add 1 to the second begin iterator: lines.begin() + half_size isn’t copied to the first vector.


Note that things like

int split = lines.size() / 2;
int arrayA[split];
int arrayB[split];

Are not standard C++ (and as such not portable). These are so-called variable-length arrays (VLAs for short) and are a C99 thing. Some compilers have them as an extension while compiling C++ code (GCC, Clang). Always compile with -pedantic to get a warning. These VLAs act funky for non-POD types and aren’t generally useful, since you can’t even return them.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)