合并矢量

扫码查看
本文介绍了合并矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个函数,它应该按升序合并两个向量而不重复。函数应该返回结果向量,但是当我尝试显示它时,虽然显示函数适用于其他向量,但没有任何反应。我也没有得到任何错误,所以它的行为就像结果向量它是空的。我正在尝试学习迭代器,这是第一次使用它们,所以也许我误解了这个概念。以下是代码:

I wrote this function that is supposed to merge two vectors in ascending order without duplicates.The function should return the resulting vector, but when I try to display it nothing happens although the display function works well for other vectors. I also don't get any error so it acts like the resulting vector it's empty.I am trying to learn iterators and this is the first time using them so maybe I have misunderstood the concept. Here is the code:

      vector<int> sort(vector<int> &a, vector<int> &b){
         vector <int> sorted;
           for (vector<int>::iterator it = a.begin(); it != a.end();) {
          for (vector<int>::iterator it2 = b.begin(); it2 != b.end();) {
            if (*it < *it2){
               sorted.push_back( *it);
               ++it2;
                }
            else if (*it >*it2){
               sorted.push_back(*it2);
               ++it;
                }
            else if (*it == *it2){
               sorted.push_back(*it);
                ++it;
                ++it2;
                }
          }
       }
        return sorted;
     }

我错误地使用了迭代器吗?任何帮助都非常感谢。

Am I mistakenly using the iterators? Any help is more than appreciated.

推荐答案

std :: set_union 中定义< algorithm> 做你想要的。请参阅以供参考。在可能的实施下,您可以找到有效的实施方案。

std::set_union defined in <algorithm> does what you want. See here for reference. Under "Possible implementation" you can find a working implementation.

这篇关于合并矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:44
查看更多