Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::initializer_list that can be sorted

Tags:

c++

c++11

I would like to std::sort an std::initializer_list;

  real_t median(const std::initializer_list<real_t> vars) {
    const unsigned x = vars.size() / 2;
    // std::sort(vars.begin(), vars.end());
    if (x & 1) {
      return *(vars.begin() + x);
    }
    return (*(vars.begin() + x) + *(vars.begin() + x + 1)) * 0.5;
  }

This gives an obscure error which I predict is because the internal elements of the list are of const &, thus they can't be sorted.

What alternatives do I have for a mutable list on the stack that will compile with -pedantic ?

I'm using C++11. Templates are not optimal unless they can be forward instantiated for all combinations of parameters, or have a small range I can extern.

like image 324
kvanbere Avatar asked Oct 29 '25 08:10

kvanbere


1 Answers

std::initializer_list(both const and not) cannot be std::sorted. That's because its iterators are read-only (its iterator type is const T*, a pointer to a const T).

For your function to work, you must use a container that satisfies the requirements of std::sort. Probably the best container for that would be std::vector.

real_t median(std::vector<real_t> vars) {  // Without the const

If you want a stack-based (fixed-sized) container, then you could use std::array, which is also std::sortable.

like image 153
Mark Garcia Avatar answered Oct 31 '25 20:10

Mark Garcia



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!