## Confusion about set_intersect() / what a set actually is

Discuss all kind of algorithms and data structures from their mathematical and programming sides.

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

### Confusion about set_intersect() / what a set actually is

Please could someone explain a little about what a set is actually supposed to do? I have the following code, which compiles and runs apparently perfectly OK. It's making me suspect that I don't really understand how a C++ set works (I'm thinking in terms of mathematical sets, and may well be being mislead by difference between the two).
[syntax="cpp"]
#include <set>
#include <algorithm>
#include <string>
#include <iostream>

using namespace std;

int main()
{
set<string> firstSet;
set<string> secondSet;
set<string> intersection;

string a("first");
string b("second");
string c("third");

firstSet.insert(a);
firstSet.insert(b);
secondSet.insert(b);
secondSet.insert(c);

set<string>::iterator firstIt, secondIt;

for (firstIt = firstSet.begin(); firstIt != firstSet.end(); ++firstIt) cout << *firstIt << ' ';
cout << endl;

for (secondIt = secondSet.begin(); secondIt != secondSet.end(); ++secondIt) cout << *secondIt << ' ';
cout << endl;

set<string>::iterator firstEndIt = firstSet.end();
set<string>::iterator secondEndIt = secondSet.end();
insert_iterator<set<string> > intersectionIt(intersection, intersection.begin());

set_intersection(firstIt, firstEndIt, secondIt, secondEndIt, intersectionIt);

for (set<string>::iterator interIt = intersection.begin(); interIt != intersection.end(); ++interIt) cout << *interIt << ' ';
cout << endl;

return 0;
}
[/syntax]
The output I get is this:
first second
second third

I don't understand why the intersection set is empty. Both firstSet and secondSet contain the string "second", so why doesn't this get put into intersection by the set_intersection function?

Thanks to anyone who can clarify for me!

GeekDog

Posts: 1160
Joined: Sun Sep 28, 2003 1:42 pm
Location: UK

It seems to me you are intersecting two empty sets. After your initial printing loops, firstIt==firstEndIt, same holds for second one.
Togra

Posts: 188
Joined: Wed Jul 28, 2004 8:51 am
Location: NL

Edit: beaten by Togra.

Alvaro
Moderator

Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA

Thanks guys. I should've realised I was being an idiot!

GeekDog

Posts: 1160
Joined: Sun Sep 28, 2003 1:42 pm
Location: UK