#include #include #include #include using namespace std; //------------------------------------------ // Utility methods //------------------------------------------ void printSeparator(string s) { cout << endl << "=====================================================" << endl; cout << s << endl; } template void dumpContainer(const T c) { for (auto el : c) { cout << el << ' '; } cout << endl; } //--------------------------------------------------------- // apply sorting-related methods to container class //--------------------------------------------------------- template void process(T &c) { cout << "Original container contents:" << endl; dumpContainer(c); //-------------------------- // is_sorted() algorithm // (Relies on "<" operator) //-------------------------- cout << "Container is " << (is_sorted(c.cbegin(), c.cend()) ? "" : "not") << " sorted " << endl; //------------------------- // sort() algorithm //------------------------- cout << "Sorting..." << endl; sort(c.begin(), c.end()); dumpContainer(c); cout << "Container is " << (is_sorted(c.cbegin(), c.cend()) ? "" : "not ") << "sorted" << endl; } //------------------------------------------- // main //------------------------------------------- int main(int argc, char *argv[]) { //---------------------------------------------- // Establish containers for sorting algorithms, // and then sort them //---------------------------------------------- vector stringVec = {"one", "two", "three", "four"}; deque intDeque = {4, 1, 3, 2}; printSeparator("Sorting a vector:"); process(stringVec); printSeparator("Sorting a deque:"); process(intDeque); //------------------------------------------------------------------- // Most algorithms can be applied to slices of sequential containers. // Here we use find(). //------------------------------------------------------------------- printSeparator("find() on a slice of a vector:"); auto beginIt = stringVec.cbegin(); auto endIt = --(stringVec.cend()); dumpContainer(stringVec); cout << "beginIt refers to " << *beginIt << endl << "endIt refers to " << *endIt << endl; printSeparator("Looking for 'one':"); auto foundIt = find(beginIt, endIt, "one"); if ( foundIt != endIt ) cout << "Found '" << *foundIt << "'" << endl; else cout << "Didn't find 'one'" << endl; printSeparator("Looking for 'two':"); foundIt = find(beginIt, endIt, "two"); if ( foundIt != endIt ) cout << "Found " << *foundIt << endl; else cout << "Didn't find two" << endl; return 0; }