C++ examples for STL Algorithm:disjoint
Using disjoint() with a comparison function.
#include <iostream> #include <list> #include <algorithm> #include <cctype> using namespace std; template<class InIter> void show_range(const char *msg, InIter start, InIter end); template<class InIter> bool disjoint(InIter start, InIter end,InIter start2, InIter end2); // Overload disjoint() to take a comparison function. template<class InIter, class Comp> bool disjoint(InIter start, InIter end,InIter start2, InIter end2, Comp cmpfn); bool equals_ignorecase(char ch1, char ch2); int main()/*from w w w .j a v a2s. c om*/ { list<char> lst1, lst2; for(int i=0; i < 5; i++) lst1.push_back('A'+i); for(int i=2; i < 7; i++) lst2.push_back('a'+i); show_range("Contents of lst1: ", lst1.begin(), lst1.end()); show_range("Contents of lst2: ", lst2.begin(), lst2.end()); cout << endl; // Test lst1 and lst2. cout << "Testing lst1 and lst2 in a case-sensitive manner.\n"; if(disjoint(lst1.begin(), lst1.end(), lst2.begin(), lst2.end())) cout << "lst1 and lst2 are disjoint\n"; else cout << "lst1 and lst2 are not disjoint.\n"; cout << endl; // Test lst1 and lst2, but ignore case differences. cout << "Testing lst1 and lst2 while ignoring case differences.\n"; if(disjoint(lst1.begin(), lst1.end(), lst2.begin(), lst2.end(), equals_ignorecase)) cout << "lst1 and lst2 are disjoint\n"; else cout << "lst1 and lst2 are not disjoint.\n"; return 0; } // Show a range of elements. template<class InIter> void show_range(const char *msg, InIter start, InIter end) { InIter itr; cout << msg; for(itr = start; itr != end; ++itr) cout << *itr << " "; cout << endl; } // determines if the contents of two ranges are disjoint. That is, if they contain no elements in common. template<class InIter> bool disjoint(InIter start, InIter end,InIter start2, InIter end2) { InIter itr; for( ; start != end; ++start) { for(itr = start2; itr != end2; ++itr) if(*start == *itr) return false; } return true; } // This overload of disjoint() lets you specify a comparison function // that determines when two elements are equal. template<class InIter, class Comp> bool disjoint(InIter start, InIter end, InIter start2, InIter end2, Comp cmpfn) { InIter itr; for( ; start != end; ++start) { for(itr = start2; itr != end2; ++itr) if(cmpfn(*start, *itr)) return false; } return true; } // This function returns true if ch1 and ch2 represent the // same letter despite case differences. bool equals_ignorecase(char ch1, char ch2) { if(tolower(ch1) == tolower(ch2)) return true; return false; }