Copy Subvector

I want to split my array of n elements and copy it into a vector in two halves (from 0 to n / 2, from n / 2 to n). What is the easiest way to do this?

+3
source share
3 answers

Are you trying to do something like this?

int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

std::vector<int> fst(&array[0], &array[5]);
std::vector<int> snd(&array[5], &array[10]);

This will create a vector fstcontaining the first five elements array, and the vector sndcontains the rest.

+10
source

To add @sth to the answer, you can do the same with all vectors (and +1 to its BTW answer):

std::vector<int> source;
//Add things to source
std::vector<int> first(source.begin(), source.begin() + source.size()/2);
std::vector<int> second(source.begin() + source.size()/2, source.end());
+8
source

You can use std::valarrayand std::slice, as in:

#include <valarray>
#include <iostream>

int main(int argc, char *argv[])
{
    std::valarray<unsigned int> va(10);

    for (size_t i = 0; i < va.size(); ++i)
        va[i] = i*2;

    std::valarray<unsigned int> fh = va[std::slice(0, va.size()/2, 1)];
    std::valarray<unsigned int> sh = va[std::slice(va.size()/2, va.size()/2, 1)];

    std::cout << "first half: ";
    for (size_t i = 0; i < fh.size(); ++i)
        std::cout << fh[i] << " ";

    std::cout <<std::endl;

    std::cout << "second half: ";
    for (size_t i = 0; i < sh.size(); ++i)
        std::cout << sh[i] << " ";

    std::cout << std::endl;
}
+1
source

Source: https://habr.com/ru/post/1761436/


All Articles