/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <string> #include <algorithm> #include <iterator> #include <functional> #include <numeric> using namespace std; /* PRINT_ELEMENTS() * - prints optional C-string optcstr followed by * - all elements of the collection coll * - separated by spaces */ template <class T> inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="") { typename T::const_iterator pos; std::cout << optcstr; for (pos=coll.begin(); pos!=coll.end(); ++pos) { std::cout << *pos << ' '; } std::cout << std::endl; } /* INSERT_ELEMENTS (collection, first, last) * - fill values from first to last into the collection * - NOTE: NO half-open range */ template <class T> inline void INSERT_ELEMENTS (T& coll, int first, int last) { for (int i=first; i<=last; ++i) { coll.insert(coll.end(),i); } } // return whether the second object has double the value of the first bool doubled (int elem1, int elem2) { return elem1 * 2 == elem2; } int main() { vector<int> coll; coll.push_back(1); coll.push_back(3); coll.push_back(2); coll.push_back(4); coll.push_back(5); coll.push_back(5); coll.push_back(0); PRINT_ELEMENTS(coll,"coll: "); // search first two elements with equal value vector<int>::iterator pos; pos = adjacent_find (coll.begin(), coll.end()); if (pos != coll.end()) { cout << "first two elements with equal value have position " << distance(coll.begin(),pos) + 1 << endl; } } /* coll: 1 3 2 4 5 5 0 first two elements with equal value have position 5 */
Category Archives: C++
Use sorting criterion in sort function
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include <string> #include <algorithm> #include <iterator> #include <functional> #include <numeric> /* PRINT_ELEMENTS() * - prints optional C-string optcstr followed by * - all elements of the collection coll * - separated by spaces */ template <class T> inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="") { typename T::const_iterator pos; std::cout << optcstr; for (pos=coll.begin(); pos!=coll.end(); ++pos) { std::cout << *pos << ' '; } std::cout << std::endl; } /* INSERT_ELEMENTS (collection, first, last) * - fill values from first to last into the collection * - NOTE: NO half-open range */ template <class T> inline void INSERT_ELEMENTS (T& coll, int first, int last) { for (int i=first; i<=last; ++i) { coll.insert(coll.end(),i); } } using namespace std; void printCollection (const list<int>& l) { PRINT_ELEMENTS(l); } bool lessForCollection (const list<int>& l1, const list<int>& l2) { return lexicographical_compare (l1.begin(), l1.end(), // first range l2.begin(), l2.end()); // second range } int main() { list<int> c1, c2, c3, c4; // fill all collections with the same starting values INSERT_ELEMENTS(c1,1,5); c4 = c3 = c2 = c1; // and now some differences c1.push_back(7); c3.push_back(2); c3.push_back(0); c4.push_back(2); // create collection of collections vector<list<int> > cc; cc.push_back(c1); cc.push_back(c2); cc.push_back(c3); cc.push_back(c4); cc.push_back(c3); cc.push_back(c1); cc.push_back(c4); cc.push_back(c2); // print all collections for_each (cc.begin(), cc.end(), printCollection); cout << endl; // sort collection lexicographically sort (cc.begin(), cc.end(), // range lessForCollection); // sorting criterion // print all collections again for_each (cc.begin(), cc.end(), printCollection); } /* 1 2 3 4 5 7 1 2 3 4 5 1 2 3 4 5 2 0 1 2 3 4 5 2 1 2 3 4 5 2 0 1 2 3 4 5 7 1 2 3 4 5 2 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 2 1 2 3 4 5 2 1 2 3 4 5 2 0 1 2 3 4 5 2 0 1 2 3 4 5 7 1 2 3 4 5 7 */
Sort objects stored in deque
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <string> #include <deque> #include <set> #include <algorithm> using namespace std; /* class Person */ class Person { private: string fn; // first name string ln; // last name public: Person() { } Person(const string& f, const string& n) : fn(f), ln(n) { } string firstname() const; string lastname() const; // ... }; inline string Person::firstname() const { return fn; } inline string Person::lastname() const { return ln; } ostream& operator<< (ostream& s, const Person& p) { s << "[" << p.firstname() << " " << p.lastname() << "]"; return s; } /* binary function predicate: * - returns whether a person is less than another person */ bool personSortCriterion (const Person& p1, const Person& p2) { /* a person is less than another person * - if the last name is less * - if the last name is equal and the first name is less */ return p1.lastname()<p2.lastname() || (p1.lastname()==p2.lastname() && p1.firstname()<p2.firstname()); } int main() { // create some persons Person p1("nicolai","josuttis"); Person p2("ulli","josuttis"); Person p3("anica","josuttis"); Person p4("lucas","josuttis"); Person p5("lucas","otto"); Person p6("lucas","arm"); Person p7("anica","holle"); // insert person into collection coll deque<Person> coll; coll.push_back(p1); coll.push_back(p2); coll.push_back(p3); coll.push_back(p4); coll.push_back(p5); coll.push_back(p6); coll.push_back(p7); // print elements cout << "deque before sort():" << endl; deque<Person>::iterator pos; for (pos = coll.begin(); pos != coll.end(); ++pos) { cout << *pos << endl; } // sort elements sort(coll.begin(),coll.end(), // range personSortCriterion); // sort criterion // print elements cout << "deque after sort():" << endl; for (pos = coll.begin(); pos != coll.end(); ++pos) { cout << *pos << endl; } } /* deque before sort(): [nicolai josuttis] [ulli josuttis] [anica josuttis] [lucas josuttis] [lucas otto] [lucas arm] [anica holle] deque after sort(): [lucas arm] [anica holle] [anica josuttis] [lucas josuttis] [nicolai josuttis] [ulli josuttis] [lucas otto] */
A simple C++ Program code
#include <iostream> #include <fstream> using namespace std; int main() { ifstream in("test", ios::in | ios::binary); if(!in) { cout << "Cannot open input file.\n"; return 1; } double num; char str[80]; in.read((char *) &num, sizeof(double)); in.read(str, 14); str[14] = '\0'; // null terminate str cout << num << ' ' << str; in.close(); return 0; }
valarray with double value inside
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <valarray> using namespace std; // print valarray line-by-line template<class T> void printValarray (const valarray<T>& va, int num) { for (int i=0; i<va.size()/num; ++i) { for (int j=0; j<num; ++j) { cout << va[i*num+j] << ' '; } cout << endl; } cout << endl; } int main() { /* valarray with 12 elements * - four rows * - three columns */ valarray<double> va(12); // fill valarray with values for (int i=0; i<12; i++) { va[i] = i; } printValarray (va, 3); // assign 77 to all values that are less than 5 va[va<5.0] = 77.0; // add 100 to all values that are greater than 5 and less than 9 va[va>5.0 && va<9.0] = valarray<double>(va[va>5.0 && va<9.0]) + 100.0; printValarray (va, 3); } /* 0 1 2 3 4 5 6 7 8 9 10 11 77 77 77 77 77 5 106 107 108 9 10 11 */
Print minimum, maximum, and sum of the valarray
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <valarray> using namespace std; // print valarray template <class T> void printValarray (const valarray<T>& va) { for (int i=0; i<va.size(); i++) { cout << va[i] << ' '; } cout << endl; } int main() { // define two valarrays with ten elements valarray<double> va1(10), va2(10); // assign values 0.0, 1.1, up to 9.9 to the first valarray for (int i=0; i<10; i++) { va1[i] = i * 1.1; } // assign -1 to all elements of the second valarray va2 = -1; // print both valarrays printValarray(va1); printValarray(va2); // print minimum, maximum, and sum of the first valarray cout << "min(): " << va1.min() << endl; cout << "max(): " << va1.max() << endl; cout << "sum(): " << va1.sum() << endl; // assign values of the first to the second valarray va2 = va1; // remove all elements of the first valarray va1.resize(0); // print both valarrays again printValarray(va1); printValarray(va2); } /* 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 min(): 0 max(): 9.9 sum(): 49.5 0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 */
Call member function for each element in vector
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ //#define mem_fun1 mem_fun #include <iostream> #include <vector> #include <string> #include <algorithm> #include <functional>
class Person { private: std::string name; public: //... void print () const { std::cout << name << std::endl; } void printWithPrefix (std::string prefix) const { std::cout << prefix << name << std::endl; } };
void foo (const std::vector<Person>& coll) { using std::for_each; using std::bind2nd; using std::mem_fun_ref;
// call member function print() for each element for_each (coll.begin(), coll.end(), mem_fun_ref(&Person::print));
// call member function printWithPrefix() for each element // - "person: " is passed as an argument to the member function
for_each (coll.begin(), coll.end(),bind2nd(mem_fun_ref(&Person::printWithPrefix),"person: ")); }
void ptrfoo (const std::vector<Person*>& coll) // ^^^ pointer !
{ using std::for_each; using std::bind2nd; using std::mem_fun;
// call member function print() for each referred object for_each (coll.begin(), coll.end(),
mem_fun(&Person::print));
// call member function printWithPrefix() for each referred object // - "person: " is passed as an argument to the member function
for_each (coll.begin(), coll.end(),bind2nd(mem_fun(&Person::printWithPrefix),"person: ")); } int main() {
std::vector<Person> coll(5); foo(coll); std::vector<Person*> coll2; coll2.push_back(new Person); ptrfoo(coll2); } /*
person: person: person: person: person: person: */
Use bitset with enum together
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <bitset> #include <iostream> using namespace std; int main() { /* enumeration type for the bits * - each bit represents a color */ enum Color { red, yellow, green, blue, white, black, //..., numColors }; // create bitset for all bits/colors bitset<numColors> usedColors; // set bits for two colors usedColors.set(red); usedColors.set(blue); // print some bitset data cout << "bitfield of used colors: " << usedColors << endl; cout << "number of used colors: " << usedColors.count() << endl; cout << "bitfield of unused colors: " << ~usedColors << endl; // if any color is used if (usedColors.any()) { // loop over all colors for (int c = 0; c < numColors; ++c) { // if the actual color is used if (usedColors[(Color)c]) { //... } } } } /* bitfield of used colors: 001001 number of used colors: 2 bitfield of unused colors: 110110 */
Transform binary representation into integral number using bitset
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <bitset> #include <iostream> #include <string> #include <limits> using namespace std; int main() { /* print some numbers in binary representation */ cout << "267 as binary short: " << bitset<numeric_limits<unsigned short>::digits>(267) << endl; cout << "267 as binary long: " << bitset<numeric_limits<unsigned long>::digits>(267) << endl; cout << "10,000,000 with 24 bits: " << bitset<24>(1e7) << endl; /* transform binary representation into integral number */ cout << "\"1000101011\" as number: " << bitset<100>(string("1000101011")).to_ulong() << endl; } /* 267 as binary short: 0000000100001011 267 as binary long: 00000000000000000000000100001011 10,000,000 with 24 bits: 100110001001011010000000 1000101011" as number: 555 */ // create a bitset that is 8 bits long bitset<8> bs; // display that bitset for( int i = (int) bs.size()-1; i >= 0; i-- ) { cout << bs[i] << " "; } cout << endl; // create a bitset out of a number bitset<8> bs2( (long) 131 ); // display that bitset, too for( int i = (int) bs2.size()-1; i >= 0; i-- ) { cout << bs2[i] << " "; } cout << endl;