Is it a good idea to extend std :: vector?

Working a bit with javascript, I realized that it’s faster to develop compared to C++, which slows down the recording for reasons that are often not applied. It is not always convenient to go through .begin()and .end()that happen through my entire application.

I am thinking of an extension std::vector(more encapsulation than inheritance) that can basically follow the conventions of methods javascriptlike

.filter([](int i){return i>=0;})
.indexOf(txt2)
.join(delim)
.reverse()

instead

auto it = std::copy_if (foo.begin(), foo.end(), std::back_inserter(bar), [](int i){return i>=0;} );

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

copy(elems.begin(), elems.end(), ostream_iterator<string>(s, delim)); 

std::reverse(a.begin(), a.end());

But I was wondering if this is a good idea, why is there no longer a library C++for such ordinary daily functions? Is there something wrong with this idea?

+6
source share
2 answers

, .

:

auto myvec = new MyVector<int>;
std::vector<int>* myvecbase = myvec;

delete myvecbase; // bad! UB
delete myvec; // ok, not UB

, .

, - .

, , , , . .

, :

// Code not in your control:
std::vector<int>& get_vec();

// error! std::vector doesn't have reverse!
auto reversed = get_vec().reverse();

// Works if you copy the vector to your class
auto copy_vec = MyVector<int>{get_vec()};
auto reversed_copy = copy_vec.reverse();

, , , .


, - . , . ( ) .

, , , ranges-v3, .


STL. , , , std::tuple (), .

, , . std::array (), .

: , , , .

+3

API.

template<typename container >
class wrapper{
public:
  wrapper(container const& c) : c_( c ){}

  wrapper& reverse() {
    std::reverse(c_.begin(), c_.end());
    return *this;
  }

  template<typename it>
  wrapper& copy( it& dest ) {
    std::copy(c_.begin(), c_.end(), dest ); 
    return *this;
  }

  /// ...

private:    
  container c_;
};

""

std::vector<int> ints{ 1, 2, 3, 4 };

auto w = wrapper(ints);    
auto out = std::ostream_iterator<int>(std::cout,", ");

w.reverse().copy( out );

. .

+2

All Articles