Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the complexity of set_intersection in C++?

What is the complexity of the following code?

set<int> S1, S2, ans;
set_intersection(S1.begin(), S1.end(), S2.begin(), S2.end(), inserter(ans, ans.begin()))

where S1 and S2 are some non_empty sets and ans is an empty set.

I know that inserting a sorted range into a set is linear; but is inserting using inserter linear too?

like image 891
Farzam Avatar asked Feb 10 '12 07:02

Farzam


1 Answers

The inserter remembers where it last inserted each item and tries to insert the next item at the same place. This is O(1) if it's the right place.

Which means copying a sorted range to the inserter is linear overall, so you're good here.

like image 102
Alan Stokes Avatar answered Nov 05 '22 01:11

Alan Stokes