libmoost
/home/mhx/git/github/libmoost/include/moost/algorithm/inplace_set_intersection.hpp
Go to the documentation of this file.
00001 /* vim:set ts=3 sw=3 sts=3 et: */
00028 #ifndef MOOST_ALGORITHM_INPLACE_SET_INTERSECTION_HPP__
00029 #define MOOST_ALGORITHM_INPLACE_SET_INTERSECTION_HPP__
00030 
00031 namespace moost { namespace algorithm {
00032 
00033 // just like stl set_intersection, these two algorithms have the precondition
00034 // that their input ranges are sorted
00035 // i've looked through gcc's include and it seems like we shouldn't need our own in-place version,
00036 // and that this would be safe:
00037 // std::set_intersection(foo.begin(), foo.end(), bar.begin(), bar.end(), foo.begin());
00038 // however, the preconditions of set_intersection (http://www.sgi.com/tech/stl/set_intersection.html)
00039 // explicitly state that the output range and input ranges should not overlap
00040 // so just to be safe, we'll write our own
00041 template <class ForwardIterator, class InputIterator>
00042 ForwardIterator inplace_set_intersection(ForwardIterator first1, ForwardIterator last1,
00043                                          InputIterator first2, InputIterator last2)
00044 {
00045   ForwardIterator result = first1;
00046   while (   first1 != last1
00047          && first2 != last2)
00048   {
00049     if (*first1 < *first2)
00050       ++first1;
00051     else if (*first2 < *first1)
00052       ++first2;
00053     else
00054     {
00055       *result = *first1;
00056       ++first1;
00057       ++first2;
00058       ++result;
00059     }
00060   }
00061   return result;
00062 }
00063 
00064 template <class ForwardIterator, class InputIterator, class StrictWeakOrdering>
00065 ForwardIterator inplace_set_intersection(ForwardIterator first1, ForwardIterator last1,
00066                                          InputIterator first2, InputIterator last2,
00067                                          StrictWeakOrdering comp)
00068 {
00069   ForwardIterator result = first1;
00070   while (   first1 != last1
00071          && first2 != last2)
00072   {
00073     if (comp(*first1, *first2))
00074       ++first1;
00075     else if (comp(*first2, *first1))
00076       ++first2;
00077     else
00078     {
00079       *result = *first1;
00080       ++first1;
00081       ++first2;
00082       ++result;
00083     }
00084   }
00085   return result;
00086 }
00087 
00088 }} // moost::algorithm
00089 
00090 #endif // MOOST_ALGORITHM_INPLACE_SET_INTERSECTION_HPP__