I am working on a programming project that is an NFL survivor pool, and I am supposed to create sets of division, the create a union of those sets into the conferences.
#include <iostream>
#include <set>
#include <string>
int main()
{
// create an empty set and insert the items
std::set<std::string> AFCNorth;
AFCNorth.insert("BR");
AFCNorth.insert("CIN");
AFCNorth.insert("CLV");
AFCNorth.insert("PS");
std::cout << "AFC North:\n";
// displaying the set contents using iterators and a for loop
for (auto team = AFCNorth.begin(); team != AFCNorth.end(); team++)
{
std::cout << *team << ' ';
}
std::cout << "\n\n";
// filling a set on creation
std::set<std::string> NFCNorth { "CB", "DL", "GBP", "MV" };
std::cout << "NFC North:\n";
// displaying the contents using a range-based for loop
for (auto& team : NFCNorth)
{
std::cout << team << ' ';
}
std::cout << "\n\n";
// create a blank set to merge other sets
std::set<std::string> NFL;
// insert the entire contents of each set
NFL.insert(AFCNorth.begin(), AFCNorth.end());
NFL.insert(NFCNorth.begin(), NFCNorth.end());
std::cout << "NFL:\n";
for (auto& team : NFL)
{
std::cout << team << ' ';
}
std::cout << '\n';
}
@Furry Guy: set::merge() does not have the same behaviour than set::insert()
merge() will not allocate new elements, but simply move them. so at the end, AFCNorth will be empty
@OP: ¿can a team be in more than one division?
you can use the knowledge of your domain to simplify things.
sort() will be a simply append, no need to sort as the intersection will always be empty
> a more efficient way to create these unions.
you don't even have 30 elements, not going to matter.
@ne555, I never said merge() wouldn't MOVE the elements. Neither that it would exhibit the same behavior. Simply mentioned there is a new member function.
cppreference indicates there is no moving involved, though.
No elements are copied or moved, only the internal pointers of the container nodes are repointed.
@jonnin, not avoiding std::set_union, just showing alternatives which are member functions of std::set. I was going to post an example using it, but got lazy.
> I never said merge() wouldn't MOVE the elements
perhaps you should
> Neither that it would exhibit the same behavior.
you said «can be written as»
¿what's that suppose to mean then?
> cppreference indicates there is no moving involved, though.
yeah, `move' was a wrong term
what I want to highlight is that the source container will end up empty
I am starting to think that c++ set is one of the worst things Ive seen in the language. Its telling that 99% of the examples I see use vectors instead of sets to explain the set operations.