c++STLアルゴリズムset_unionとsort


STLにおける相関アルゴリズムを柔軟に使用することは,C++開発に必須であり,ここでは最近用いられた2つのSTLアルゴリズムを記録する.
1.set_union
集合S 1 US 2をマージして、並列集合を得る.ここでは、S 1とS 2がset集合の反復器であることを前提としている.これは、これらの集合がシーケンスされていることを意味する.
パラメータとしてsetmultisetを受け入れることができます.
template 
  OutputIterator set_union (InputIterator1 first1, InputIterator1 last1,
                            InputIterator2 first2, InputIterator2 last2,
                            OutputIterator result)
{
  while (true)
  {
    if (first1==last1) return std::copy(first2,last2,result);
    if (first2==last2) return std::copy(first1,last1,result);

    if (*first1

2.sort関数
リレーショナルコンテナ(map,set)の下部は赤黒ツリーで実現されるため、vectorとdequeのパラメータのみが受け入れられ、ソート機能が付いているため、必要ありません.
シーケンスコンテナの(stack,queue,priority-queue)には特定の出入り口があり、ユーザーが要素をソートすることは許されません.
比較方式をsortに渡すことを自分で定義するとき、sortはstrict weak orderであることに注意してください.
”Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool . The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments.This can either be a function pointer or a function object.”
2つの要素が等しい場合、返される結果がtrueであると、sortで予期せぬcoredumpがプログラムに現れる.これは,下層のsort実装に起因し,この問題を引き起こした.
コード検証を貼る時間があります.