对字符串使用set_union

may*_*yaa 6 c++ sorting algorithm stl vector

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

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];
Run Code Online (Sandbox Code Playgroud)

这会编译,但输出为空。

Vla*_*cow 9

该算法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;
}
Run Code Online (Sandbox Code Playgroud)

它的输出是

a b c d 
Run Code Online (Sandbox Code Playgroud)

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

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

程序输出为

a b c d
Run Code Online (Sandbox Code Playgroud)


Log*_*uff 8

您的代码有两点错误:

  1. 您尚未阅读的要求std::set_union-输入范围必须根据给定的比较函数(operator<在您的情况下)进行排序-这不适用于b
  2. 该算法无法c通过调整大小c.begin(); 它仍然是空的,您超出范围。使用std::back_insert_iterator