在c++中使用向量设置联合算法



在这个问题中我只使用std::vector,并且我可以保证每个向量中没有重复(但是每个向量中没有任何顺序)。如何对这些向量进行并集?

的例子:

如果我有以下向量…

1
1
3 2
5
5 4
2
4
4 2

并集之后应该只剩下两个向量:

1
2 3 4 5

我只使用向量,不允许使用std::set

可以使用std::set_union算法

int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};
  std::vector<int> v(10);                      // 0  0  0  0  0  0  0  0  0  0
  std::vector<int>::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

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

对向量进行排序,然后像合并排序一样合并它们,但不要插入重复项。

vector<int> a, b, c;
sort( a.begin(), a.end());
sort( b.begin(), b.end());
int i = 0, j = 0;
while( i < a.size() && j < b.size())
if( a[ i ] == b[ j ] )
{
   c.push_back( a[ i ] );
   ++i, ++j;
}
else if( a[ i ] < b[ j ] )
   c.push_back( a[ i++ ] );
else 
   c.push_back( b[ j++ ] );
while( i < a.size()) c.push_back( a[ i++ ] );
while( j < b.size()) c.push_back( b[ j++ ] );

下面是我的代码:

template<class T> bool vectorExist (vector<T> c, T item)
{
    return (std::find(c.begin(), c.end(), item) != c.end());
}
template<class T> vector<T> vectorUnion (vector<T> a, vector<T> b)
{
    vector<T> c;
    std::sort(a.begin(), a.end());
    std::sort(b.begin(), b.end());
    auto i = a.begin();
    auto j = b.begin();
    while (i != a.end() || j != b.end())
    {
        if (j == b.end() || *i < *j)
        {
            if(!exist(c,*i)) c.insert(*i);
            i++;
        }
        else
        {
            if(!exist(c,*j)) c.insert(*j)
            j++;
        }
    }
    return c;
}

最新更新