Std :: find vs. getting template from vector

I use vectors a lot in my programming and, as a rule, to move a vector for an existing value, I use std :: find , as in:

std::vector<int> foo;
std::vector<int>::iterator pos( std::find( foo.begin(), foo.end(), bar );

This is real boredom. So I went to create a template from std :: vector to provide the find method :

template<class T>
class foovector : public std::vector<T>
{
public:
    typename std::vector<T>::iterator find( const T& value )
    {
        return std::find( this->begin(), this->end(), value );
    }
};

So now I can find more naturally:

foovector<int> foo;
foovector<int>::iterator pos( foo.find( bar ) );

My question is that this seems like a natural and obvious extension of the vector, so why is it not part of STL or even boost ? I feel that I am missing some secret knowledge here.

+3
source share
6

, , , std::vector

template <typename T>
typename std::vector<T>::const_iterator find( const std::vector<T>& v, const T& value )
 {
     return std::find( v.begin(), v.end(), value );
 }

std (, , ), - ( , ADL, ).

P.S. ,

template <typename Container, typename T>
typename Container::const_iterator find( const Container& c, const T& value )
{
     return std::find( c.begin(), c.end(), value );
}
+4
  • STL - , .

  • < > - .

  • , , .

+6

STL , , , .

( ). , , , . , - .

+5

, - , () , .

O (1), , , .

+2

, , ( ). , O(log n) , O(n).

:

map<stuff> m
m[bar] // returns a reference to the element with key bar.

.

+1

, , <algorithm>, , / . , ( , , ..), .

In your case, the general way to do this is:

template <typename Container>
typename Container::iterator find(Container& c,
                                  typename Container::value_type const& v)
{
  return std::find(c.begin(), c.end(), v);
}

template <typename Container>
typename Container::const_iterator find(Container const& c,
                                        typename Container::value_type const& v)
{
  return std::find(c.begin(), c.end(), v);
}

This can be used with any STL-compatible container.

Of course, it would be nice to adapt this through a concept to use a member function find, if available ...

+1
source

Source: https://habr.com/ru/post/1769180/


All Articles