Best way to split a vector into two smaller arrays?

前端 未结 4 1732
一个人的身影
一个人的身影 2021-02-01 16:01

What I\'m trying to do:

I am trying to split a vector into two separate arrays. The current int vector contains an element per line in a text file. Th

4条回答
  •  一个人的身影
    2021-02-01 16:28

    Use iterators.

    std::vector lines;
    // fill
    std::size_t const half_size = lines.size() / 2;
    std::vector split_lo(lines.begin(), lines.begin() + half_size);
    std::vector 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.

提交回复
热议问题