未排序向量上的STL set

编程入门 行业动态 更新时间:2024-10-18 08:30:27
本文介绍了未排序向量上的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

本文发布于:2023-11-29 03:56:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645192.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:向量   STL   set

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!