tags:

views:

59

answers:

3

Hi,

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

+8  A: 

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 fst containing the first five elements of array, and a vector snd containing the rest.

sth
Thank you very much.
brett
+4  A: 

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

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());
Billy ONeal
+1: for giving the vector alternative
Chubsdad
A: 

You could use std::valarray and std::slice as in:

#include <valarray>
#include <iostream>

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

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

    std::valarray<size_t> fh = va[std::slice(0, va.size()/2, 1)];
    std::valarray<size_t> 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;
}
andand