Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing std:array around

Tags:

c++

arrays

c++03

I'm trying to write a function that will work on a std::array of variable size, eg:

std::array a<int,5>={1,2,3,4,5};
std::array b<int,3>={6,7,8};

myFunc(a);
myFunc(b);

void myFunc(std::array &p)
{
cout << "array contains " << p.size() << "elements"; 
}

However, it doesn't work unless I specify the size, but I want the function to get the size from the array. I really didn't want the copying and dynamic allocation that vector uses, I want to use the space allocated by std::array() and don't want the compiler creating a copy of the function for every possible size of array.

I thought about creating a template that works like array but will take a pointer to existing data rather than allocating it itself, but don't want to reinvent the wheel.

Is this possible somehow?

like image 391
Steve Avatar asked Apr 20 '14 22:04

Steve


2 Answers

template<typename T, size_t N>
void myFunc(std::array<T, N> const &p) {
    cout << "array contains " << p.size() << "elements"; 
}

std::array is not a class and cannot be used like a class. It's a template, and you must instantiate the template in order to get a class that can be used like a class.

Also, the size is part of the type of an array. If you want a container where the size isn't part of the type then you can use something like std::vector. Alternatively you can write a template that works for any object that has the functionality you need:

template<typename Container>
void myFunc(Container const &p) {
    cout << "Container contains " << p.size() << "elements"; 
}
like image 124
bames53 Avatar answered Oct 01 '22 07:10

bames53


Prefer the STL way : pass iterators (by value) instead of containers to your functions. And templatize your functions.

Your code will integrate much better with the standard algorithms, and will work equally will with std::array or other standard containers.

e.g. :

template<class InputIterator>
void myFunc (InputIterator first, InputIterator last);
like image 35
quantdev Avatar answered Oct 01 '22 07:10

quantdev