Date: prev next · Thread: first prev next last
2012 Archives by date, by thread · List index


2012/7/10 Noel Grandin <noel@peralex.com>:
On 2012-07-10 15:35, Caolán McNamara wrote:
How does this look? It's the bare minimum I need in a sorted_vector class.

namespace o3tl
{
/** Represents a sorted vector of values.

    @tpl Value
    @tpl Compare comparison method
*/
template <class Value, class Compare = less<Value>>
class sorted_vector : vector<Value>
{
public:

    // MODIFIERS
    pair<iterator,bool> insert( const Value& x );
    size_type           erase( const Value& x );

    // OPERATIONS
    /* Searches the container for an element with a value of x
     * and returns an iterator to it if found, otherwise it returns an
     * iterator to sorted_vector::end (the element past the end of the
container).
     */
    iterator            find( const Value& x ) const;

};



// IMPLEMENTATION

template <class Value, class Compare>
pair<iterator,bool> sorted_vector<Value,Compare>::insert( const Value& x )
{
    iterator it = std::lower_bound(begin(), end(), p, Compare);
    if( !Compare(*it, x) )
    {
        return make_pair( it, false );
    }
    it = insert( it, p );
    return make_pair( it, true );
}

template <class Value, class Compare>
size_type sorted_vector<Value,Compare>::erase( const Value& x )
{
    iterator it = std::lower_bound(begin(), end(), p, Compare);
    if( !Compare(*it, x) )
    {
        erase( it );
        return 1;
    }
    return 0;
}

template <class Value, class Compare>
iterator sorted_vector<Value,Compare>::find( const Value& x )
{
    iterator it = std::lower_bound(begin(), end(), p, Compare);
    if( !Compare(*it, x) )
    {
        return it;
    }
    return end();
}


Maybe a stupid question and more (clean) code related: Why do you
duplicate the "search if already included" instead of using the ::find
method in ::insert? I mean, sure, at the moment it is just two
lines... but most of the stuff in this code base started that small
and are now big evil monsters ;-) But maybe I am too pessimistic in
this point...

Cheers,
Philipp

Context


Privacy Policy | Impressum (Legal Info) | Copyright information: Unless otherwise specified, all text and images on this website are licensed under the Creative Commons Attribution-Share Alike 3.0 License. This does not include the source code of LibreOffice, which is licensed under the Mozilla Public License (MPLv2). "LibreOffice" and "The Document Foundation" are registered trademarks of their corresponding registered owners or are in actual use as trademarks in one or more countries. Their respective logos and icons are also subject to international copyright laws. Use thereof is explained in our trademark policy.