未排序向量上的STL set_union和set_intersection [英] STL set_union and set_intersection on unsorted vectors

查看:52
本文介绍了未排序向量上的STL set_union和set_intersection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我在设置交集和并集测试中执行的代码.我不明白为什么在注释掉sort函数时输出不正确.为什么需要排序?还是我在这里想念任何东西?使程序员负责首先对输入进行排序的技术原因是什么?

Below is my code on set intersection and union test that I did. I don't understand why it the output is incorrect when I commented out the sort function. Why is the sort necessary? or am I missing anything here? What is the technical reason for making the programmer responsible to sort the inputs first? Is it for guaranteeing sorting is not done twice(if the vector was already sorted and the algorithm sorts it again...)?

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
void test_vector_union();
void test_vector_intesection();

int main(int i, char * args [])
{
  cout <<endl<< "test union of unsorted vectors {1,4,3,2,0} and {6,10,2,1,4}" << endl;
  test_vector_union();
  cout <<endl<< "test intersection of unsorted vectors {1,4,3,2,0} and {6,10,2,1,4}" <<     endl;
  test_vector_intesection(); 
  return 0;
 }

void test_vector_union(){
 vector<int> x = {1,4,3,2,0};
 vector<int> y= {6,10,2,1,4};
//sort(x.begin(),x.end()); sort(y.begin(),y.end());
vector<int> z ;
set_union(x.begin(),x.end(),y.begin(),y.end(),back_inserter(z));

for (int i:z)
     cout << i <<",";
}

void test_vector_intesection(){
 vector<int> x = {1,4,3,2,0};
 vector<int> y= {6,10,2,1,4};
 //sort(x.begin(),x.end()); sort(y.begin(),y.end());
 vector<int> z ;
 set_intersection(x.begin(),x.end(),y.begin(),y.end(),back_inserter(z));

 for (int i:z)
     cout << i <<",";

}

推荐答案

因为这是要求/set_union"rel =" nofollow> std :: set_union :

Because it is a requirement for std::set_union:

构造一个从d_first开始的排序范围,该范围由一个或两个排序范围[first1,last1)和[first2,last2)中存在的所有元素组成.

Constructs a sorted range beginning at d_first consisting of all elements present in one or both sorted ranges [first1, last1) and [first2, last2).

1)期望对两个输入范围进行排序,并使用运算符<

1) Expects both input ranges to be sorted with operator<

2)期望使用给定的比较函数comp

2) Expects them to be sorted with the given comparison function comp

(重点是我的)

您不应在未排序的范围内调用这些算法.

you shouldn't call these algorithms on unsorted ranges.

这篇关于未排序向量上的STL set_union和set_intersection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆