首页 > 解决方案 > 对字符串使用 set_union

问题描述

我有两个向量,我需要它们在第三个向量中的并集(不指定第三个向量的大小)

std::vector<std::string> a = {"a","b"};
std::vector<std::string> b = {"d","c"};

std::vector<std::string> c;

std::set_union(a.begin(),a.end(),b.begin(),b.end(),c.begin());
std::cout<<c[1];

这编译但给出一个空的输出。

标签: c++algorithmsortingvectorstl

解决方案


该算法std::set_union需要有序序列。在您的字符串示例中,第一个向量按升序排列,第二个向量按降序排列。

此外,向量c是空的,因此您不能c.begin()在算法调用中使用表达式。你需要使用std::back_insert_iterator.

对于您的字符串示例,算法的调用可以如下所示,如演示程序中所示。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>


int main() 
{
    std::vector<std::string> a = { "a", "b" };
    std::vector<std::string> b = { "d", "c" };

    std::vector<std::string> c;

    std::set_union( std::begin( a ), std::end( a ), 
                    std::rbegin( b ), std::rend( b ),
                    std::back_inserter( c ) );

    for ( const auto &s : c ) std::cout << s << ' ';
    std::cout << '\n';

    return 0;
}

它的输出是

a b c d 

否则,您需要对向量进行排序。

如果您可能无法对原始向量进行排序,则可以使用以下方法

#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>


int main() 
{
    std::vector<std::string> a = { "a", "b" };
    std::vector<std::string> b = { "d", "c", "a" };

    std::vector<std::string> c( a );
    c.insert( std::end( c ), std::begin( b ), std::end( b ) );

    std::sort( std::begin( c ), std::end( c ) );

    c.erase( std::unique( std::begin( c ), std::end( c ) ), std::end( c ) );

    for ( const auto &s : c ) std::cout << s << ' ';
    std::cout << '\n';

    return 0;
}

程序输出为

a b c d

推荐阅读