标准库里的merge、set_union函数

使用一个东西,不明白它的道理,不高明
——侯捷老师

1. merge()函数

功能:合并两段序列

1.1 函数声明

// default (1)
template 
  OutputIterator merge (InputIterator1 first1, InputIterator1 last1,
                        InputIterator2 first2, InputIterator2 last2,
                        OutputIterator result);
// custom (2)   
template 
  OutputIterator merge (InputIterator1 first1, InputIterator1 last1,
                        InputIterator2 first2, InputIterator2 last2,
                        OutputIterator result, Compare comp);

1.2 等价操作实现

template 
  OutputIterator merge (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);
    *result++ = (*first2<*first1)? *first2++ : *first1++;
  }
}

1.3 示例程式

void test_merge() {
      int first[] = {5,10,15,20,25};
      int second[] = {50,40,30,20,10};
      std::vector v(10);
    
      std::sort (first,first+5);
      std::sort (second,second+5);
      std::merge (first,first+5,second,second+5,v.begin());
    
      std::cout << "The resulting vector contains:";
      for (std::vector::iterator it=v.begin(); it!=v.end(); ++it)
        std::cout << ' ' << *it;
      std::cout << '\n';
    }

输出结果:
image.png

1.4 参考链接

http://www.cplusplus.com/reference/algorithm/merge/

2. set_union()函数

功能:将两个序列合并成一个集合,不包括重复元素

2.1 函数声明

2.2 等价操作实现

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<*first2) { *result = *first1; ++first1; }
    else if (*first2<*first1) { *result = *first2; ++first2; }
    else { *result = *first1; ++first1; ++first2; }
    ++result;
  }
}

2.3 示例程式

void test_set_union() {
        int first[] = {5,10,15,20,25};
        int second[] = {50,40,30,20,10};
        std::vector v(10);                      // 0  0  0  0  0  0  0  0  0  0
        std::vector::iterator it;
    
        std::sort (first,first+5);     //  5 10 15 20 25
        std::sort (second,second+5);   // 10 20 30 40 50
        
        it=std::set_union (first, first+5, second, second+5, v.begin());
                                                   // 5 10 15 20 25 30 40 50  0  0
        v.resize(it-v.begin());                      // 5 10 15 20 25 30 40 50
    
        std::cout << "The union has " << (v.size()) << " elements:\n";
        for (it=v.begin(); it!=v.end(); ++it)
        std::cout << ' ' << *it;
            std::cout << '\n';
    }

输出结果:


image.png

2.4 参考链接

http://www.cplusplus.com/reference/algorithm/set_union/

你可能感兴趣的:(标准库里的merge、set_union函数)