c++boostboost-ptr-container

Differences between std::set and boost::ptr_set?


I've changed some code to convert a std::set to a boost::ptr_set. However, the code doesn't compile; the problem is that I'm assuming that the return value from a ptr_set insert is the same as a set insert (a pair<myIter, bool>). After an hour on Google I found this, and it turns out that the return value from a ptr_set insert appears to be a bool.

Is there any definitive documentation on the differences between the ptr containers and the std containers? I haven't found anything on the boost website, but maybe I'm just being dumb...

EDIT

Ok - what was confusing me was that this code

  t.insert(s.release(s.begin()));
  p = t.insert(s.release(s.begin()));

reports no error on the first line on gcc, but reports no match for operator= on the second line, so I thought the error was in the return type. However, if you comment out the second line, the first line is then reported as an error (release doesn't return an iterator). My confusion was compounded by the link I posted, in which ptr_container's author states that "insert() in ptr_set<> returns bool". However, reading on down the link it becomes obvious that the code hadn't been finished at the time. Thanks Kerrek.


Solution

  • The following code works as expected, and the interface is the same as for std::set::insert():

    #include <boost/ptr_container/ptr_set.hpp>
    #include <boost/assign/ptr_list_inserter.hpp>
    #include <iostream>
    
    int main()
    {
      boost::ptr_set<int> s;
    
      {
        auto p = s.insert(new int(4));
        std::cout << "Element " << *p.first << (p.second ? " inserted" : " already existed") << std::endl;
      }
      {
        auto p = s.insert(new int(4));
        std::cout << "Element " << *p.first << (p.second ? " inserted" : " already existed") << std::endl;
      }
    
      boost::assign::ptr_insert(s)(1)(2)(3)(4);
    
      for (auto it = s.begin(), end = s.end(); it != end; ++it) { std::cout << *it << "\n"; }
    }
    

    The documentation is perhaps not the easiest to navigate, but it's all there. You should look for the "set adapter", though, perhaps that's not entirely obvious.