Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct std::set from array

Tags:

c++

arrays

set

stl

Why doesn't C++ provide us with a constructor which takes an array as an argument? Alternatively, is there anything wrong with defining the following function?

template <class T>
std::set<T> ArrayToSet(T array[]) {
  return std::set<T>(array, array + sizeof(array) / sizeof(array[0]));
}

I think the answer might come down to ideas of dynamic memory allocation, but I'd like to hear some feedback on this.

Edit: I am not using C++11.

like image 399
David Hall Avatar asked Jun 07 '26 11:06

David Hall


1 Answers

Alternatively, is there anything wrong with defining the following function?

There is: it doesn’t work.

You cannot pass variable-length C-style arrays to functions. The T array[] syntax in an argument list is a synonym for T* array: a raw pointer is passed, not an argument.

You can, however, pass fixed-sized arrays by reference (i.e. T (&array)[5] works). To make this work for different array lengths you need to use a non-type template argument:

template <class T, std::size_t N>
std::set<T> ArrayToSet(T (&array)[N]) {
  return std::set<T>(array, array + N);
}

– But I agree in this with Zac: the function is over-specific (or, the other way round: not generic enough). There is already a universal collection-construction method, via iterators. So the correct way is to use C++11’s std::begin and std::end facility, and if you cannot use C++11, then the correct way is to write them yourself:

template <typename T, std::size_t N>
T* begin(T (&array)[N]) {
    return array;
}

template <typename T, std::size_t N>
T* end(T (&array)[N]) {
    return array + N;
}
like image 111
Konrad Rudolph Avatar answered Jun 10 '26 03:06

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!