c++ - 对字符串使用 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];
这编译但给出一个空的输出。
解决方案
该算法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
推荐阅读
- python - 我如何提取除表格以外的pdf表格
- r - 使用花括号取消嵌套 JSON
- python - 在使用我在文件夹 train 中提供脚本的容器进行训练测试期间如何处理问题?
- ios - SwiftUI Preview 未突出显示视图,Xcode 12.5.1
- c# - Acumatica - 尽管传递了有效 ID,但 SelectFrom 返回 Null
- python-3.x - Django 模型属性不起作用 - Django
- python - 熊猫:以固定间隔计算差异,并在没有更多记录时更改为可变间隔以使用最早的记录
- python - 蟒蛇 | 将特定类型的文件从输入/源文件夹移动到输出/目标文件夹,保留文件夹结构
- networking - 使用接口参数作为 NIC 名称的 ping 命令正在工作,但不能通过 IP 工作
- javascript - 如何使用 Axios 拦截器向响应添加一些标头?