Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a function that can take in an array or a vector?

I would like to write a C++ function with one argument such that one can pass in either any of the following types:

std::vector<int>
std::array<int>
int array[numElements]
int *ptr = new int[numElements]
etc

Would templating be the best way to accomplish this?

like image 389
24n8 Avatar asked Nov 11 '18 19:11

24n8


1 Answers

If you expect to just be able to do func(v) you cannot, because there's no way I can think of that your function could deduce the size of the dynamically allocated int[numElements].

A good way you could wrap this is to take a pair of forward iterators, that is, if you only need iterating over items one by one, since random access is very bad on some containers like std::list.

template<class FWIt>
void func(FWIt a, const FWIt b)
{
    while (a != b)
    {
        std::cout << "Value: " << *a << '\n';
        ++a;
    }
}

template<class T>
void func(const T& container)
{
    using std::begin;
    using std::end;
    func(begin(container), end(container));
}

This would work with the following:

int array[5] = {1, 2, 3, 4, 5};
func(array);

int* dynarray = new int[5]{1, 2, 3, 4, 5};
func(dynarray, dynarray + 5);

std::vector<int> vec{1, 2, 3, 4, 5};
func(vec);
func(vec.begin(), vec.end());

std::list<int> list{1, 2, 3, 4, 5};
func(list);

Edit: This also works by passing raw arrays directly rather than as two pointers thanks to @DanielH's change (but still won't work with dynamically allocated arrays).

like image 67
Asu Avatar answered Nov 12 '22 13:11

Asu