Constructor with array as argument

Hi,

Quick question. If I wanted to make a constructor that takes 2 arguments, an array of ints to copy into a vector and another int that tells me how many elements are in the array, how would I do this?

Assuming class name is OneTwo...

Would the constructor declaration be OneTwo(int, int) ?
Not sure how to take an array as an argument.

Also, once I do it, how do I copy the values into a new array that is dynamically allocated. Thanks

For the constructor declaration you would use :

OneTwo(int array[], int size);
or you don't have to declare name for the arguments
OneTwo(int [], int);

as for how to copy into a vector, use a for loop and check out the references here on this site for vectors. You'll have to use the vector member function push_back().
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <vector>
#include <initializer_list> // C++11 only

struct A
{
    A() {} // 1. initialize to empty vector

    // 2. initialize to a vector of size n, each element being v
    A( std::size_t n, int v = 0 ) : sequence(n,v) {}

    // 3. initialize from pointer to first element of int array and its size
    A( const int* a, std::size_t n ) : sequence( a, a+n ) {}

    // 4. initialize from a polymorphic sequenceuence abstracted away with iterators
    template< typename ITERATOR >
    A( ITERATOR begin, ITERATOR end ) : sequence(begin,end) {}

    // 5. initialize from array via initializer list  - C++11 only
    A( std::initializer_list<int> ilist ) : sequence(ilist) {}

    //  6. initialize from array with compatible type
    template< typename T, std::size_t N > A( T(&a)[N] ) : sequence( a, a+N ) {}

    std::vector<int> sequence ;
};

int main()
{
    A a1 ; // 1

    A a2( 10U, 99 ) ; // 2

    const int a[] = { 0, 1, 2, 3, 4 } ;
    A a3( a, sizeof(a)/sizeof(int) ) ; // 3

    const short b[] = { 5, 6, 7, 8 } ;
    A a4( b, b + sizeof(b)/sizeof(short) ) ; // 4

    A a5 = { 10, 11, 12, 13, 14, 15, 16 } ; // 5

    A a6(b) ; // 6
}
Last edited on
If you're taking in an array, you don't need an extra size argument, because the size is part of the array's type already:

1
2
3
4
5
6
7
#include <vector>
struct One
{
    std::vector<int> data;
    template<std::size_t N>
    One(const int (&a)[N]) : data(a, a+N) {}
};


I am guessing you meant to say pointer to the first element of an array and the size:

1
2
3
4
5
6
7
8
9
10
11
12
struct Two
{
    std::vector<int> data;
    Two(const int* a, std::size_t n) : data(a, a+n) {}
};

int main()
{
    int a[5] = {1,2,3,4,5};
    One o(a);
    Two t(a, 5);
}


edit: I am slow today!
Last edited on
> If you're taking in an array, you don't need an extra size argument, because the size is part of the array's type already

Yes. I'm correcting it now, thanks.
Topic archived. No new replies allowed.