我有两个 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/