c++ - 对字符串使用 set_union

标签 c++ algorithm sorting vector stl

我有两个 vector ,我需要在第三个 vector 中合并它们(不指定第三个 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];

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

最佳答案

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

此外, vector 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 

否则你需要对 vector 进行排序。

如果您可能无法对原始 vector 进行排序,那么您可以使用以下方法

#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

关于c++ - 对字符串使用 set_union,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497105/

相关文章:

algorithm - 如何检查程序是否终止?

python - 重新组合 Pandas df 中的列值

algorithm - 给定一台可以对 5 个对象进行分类的机器。我们能以多快的速度对其中的 25 个进行排序?

c++ - 如何确定 (x, y) 点是否在由边界点列表定义的多边形内

android - cocos2dx android AppDelegate 链接时出错

c++ - 为什么不能在派生类初始化时编译代码?

javascript `localeCompare` 返回不同的值

c++ - 尝试使用初始化列表构造 `std::vector` 的问题

java - 当必须通过姓名和号码访问时,存储电话簿的最佳数据结构

algorithm - 字体 ID 算法如何工作?