Boost logo

Boost Users :

From: Joaquín Mª López Muñoz (joaquin_at_[hidden])
Date: 2006-04-28 04:22:49


bert hubert ha escrito:

> Hi,
>
> I misread (or didn't read) the boost::multi_index_container documentation
> and assumed 'insert' on a unique index would do 'replace', but of course it
> doesn't and shouldn't.
>
> So, I've made this change:
>
> - s_negcache.insert(ne);
> +
> + pair<negcache_t::iterator, bool> res=s_negcache.insert(ne);
> + if(!res.second) {
> + s_negcache.erase(res.first);
> + s_negcache.insert(ne);
> + }
>
> But I can't help feeling there is probably a better and prettier way. Do
> people have any suggestions?

Hello Bert,

You can do it more efficiently by using replace() instead of deleting and
reinserting on collision. The following packages the entire procedure

  template<typename Index>
  std::pair<typename Index::iterator,bool>
  replacing_insert(Index& i,const typename Index::value_type& x)
  {
    std::pair<typename Index::iterator,bool> res=i.insert(x);
    if(!res.second)res.second=i.replace(res.first,x);
    return res;
  }

So that you can say

  pair<negcache_t::iterator, bool> res=replacing_insert(s_negcache,ne);

Note that replacing_insert() still cannot guarantee in the general case that
insertion will always be succesful (hence its returning a pair<iterator,bool>):

failure happens if two or more distinct elements are colliding with the value
to
be inserted. Check the attached code for an example of a failing call to
replacing_insert().

HTH,

Joaquín M López Muñoz
Telefónica, Investigación y Desarrollo




Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net