* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download The C++ language, STL
Name mangling wikipedia , lookup
Lua (programming language) wikipedia , lookup
Python (programming language) wikipedia , lookup
Scheduling (computing) wikipedia , lookup
Monitor (synchronization) wikipedia , lookup
Design Patterns wikipedia , lookup
Go (programming language) wikipedia , lookup
Join-pattern wikipedia , lookup
APL syntax and symbols wikipedia , lookup
C Sharp (programming language) wikipedia , lookup
Overview, C++ lecture 4 ● struct - class ● Standard Template Library ● Connecting Python and C++ ● Some other things struct vs class in C++ ● ● ● ● In C++, a struct and a class is almost the same thing. Both can have methods. public, private and protected can be used with both. Inheritance is the same. Both are stored in the same way in memory. The only difference is that members are public by default in a struct and private by default in a class, and inheritance is public by default for structs and private for classes. In practice though, you usually use struct as if it was a C-struct. Standard Template Library (STL) ● Originally created by Silicon Graphics ● Became a part of the C++ in 1994 ● ● Many different implementations appeared since then. Contains: Containers, Iterators, Algorithms Some STL material ● http://en.wikipedia.org/wiki/Standard_Template_Library ● http://www.cplusplus.com/reference/stl/ ● http://www.codeproject.com/KB/stl/stlintroduction.aspx Common STL templates Sequence containers vector Function deque Dynamic array, two open ends list Doubly linked list Container adaptors stack Function queue FIFO queue priority_queue Priority queue Dynamic array, one open end LIFO stack Associative containers Function set Mathematical set multiset Can contain duplicates map Keys mapped to values multimap As map but each key can be mapped to several values STL collection functions Function empty Returns size Number of elements begin Forward iterator set to the first element end Forward iterator set just past the last element rbegin Backward iterator set to the last element rend Backward iterator set just before the first element clear Erases all elements, by calling the destructor to everything and setting the size to 0. erase Erasing one or more elements. Call with iterators or index. Is empty vector ● ● ● The most used template in STL? Similar to an ordinary array, but dynamic, i.e. the length can both increase and decrease. Elements are stored contiguously in memory. Commonly used vector functions ● [] - get/set, with bound checking in MSVC ● at - get/set, with bound checking ● push_back - appending objects ● capacity - the allocated nr of elem. ● reserve - request a capacity change ● clear - clear the content ● front - the first element ● back - the last element vector #include <vector> #include <iostream> using namespace std; int main() { vector<int> vNumbers; vNumbers.push_back(1); cout << vNumbers[0]; return 0; } Looping over a vector, ”old style” using namespace std; // Create a vector with two elements vector<int> vIntegers; vIntegers.push_back(1); vIntegers.push_back(2); for(int i=0; i<myIntVector.size(); i++) { cout << vIntegers[i] << " "; } // (not a complete program) Looping over a vector, ”official way” using namespace std; // Create a vector with two elements vector<int> vIntegers; vIntegers.push_back(1); vIntegers.push_back(2); // Print the vector using an iterator vector<int>::iterator it; for( it = vIntegers.begin(); it != myIntVector.end(); it++ ) { cout << *it << ” ”; } Looping over a vector, BOOST_FOREACH #include <boost/foreach.hpp> using namespace std; #define foreach BOOST_FOREACH // Create a vector with two elements vector<int> vIntegers; vIntegers.push_back(1); vIntegers.push_back(2); // Print using foreach-macro foreach( int& val, vIntegers) { cout << val << ” ”; } Other ways ● Upcoming C++ version, C++0x: vector<int> vIntegers; vIntegers.push_back(1); vIntegers.push_back(2); for (int& val : vIntegers) { cout << val << ” ”; } ● Visual Studio only, avoid: for each (.. in ..) ● - STL: UnaryFunction for_each( input_iterator start, input_iterator end, UnaryFunction f ); Strange loop example // An for_each example from an STL documentation // Printing the elements of an array template<class T> struct print : public unary_function<T, void> { print(ostream& out) : os(out), count(0) {} void operator() (T x) { os << x << ' '; ++count; } ostream& os; int count; }; int main() { int A[] = {1, 4, 2, 8, 5, 7}; const int N = sizeof(A) / sizeof(int); } print<int> P = for_each(A, A + N, print<int>(cout)); cout << endl << P.count << " objects printed." << endl; for_each with C++0x ● for_each is somewhat better with C++0x features. Example from Wikipedia, summing up a vector: std::vector<int> someList; int total = 0; std::for_each(someList.begin(), someList.end(), [&total](int x) { total += x; }); std::cout << total; Another example ● vector<int> v1; vector<int> v2; // Create some elements for (int i=0; i<10; i++) v1.push_back(i); Example output: 8 1 9 2 0 5 7 3 4 6 0 1 2 3 4 5 6 7 8 9 random_shuffle(v1.begin(), v1.end()); v2 = v1; sort(v2.begin(), v2.end()); // Print the vectors // Assuming that BOOST_FOREACH is available and remapped to foreach foreach(int val, v1) cout << val << " "; cout << endl; foreach(int val, v2) cout << val << " "; cout << endl; Queue example #include <queue> queue<int> myQueue; myQueue.push(1); myQueue.push(7); myQueue.push(4); while (!myQueue.empty()) { cout << myQueue.front() << endl; myQueue.pop(); } ● Output: 1 7 4 Priority queue example #include <queue> priority_queue<Task> prioQueue; prioQueue.push(Task(4, "Go to the cinema")); prioQueue.push(Task(9, "Solve the programming assignments")); prioQueue.push(Task(3, "Washing up")); while (!prioQueue.empty()) { cout << prioQueue.top().task << endl; prioQueue.pop(); } ● Output: Solve the programming assignments Go to the cinema Washing up Task class definition class Task { public: Task(int _priority, string _task); bool operator<(const Task&) const; }; int priority; string task; // The constructor Task::Task(int _priority, string _task) : priority(_priority), task(_task) { }; // The comparison function bool Task::operator<(const Task& right) const { return priority < right.priority; } Queue example #include <queue> queue<Task> myQueue; myQueue.push(Task(4, "Go to the cinema")); myQueue.push(Task(9, "Solve the programming assignments")); myQueue.push(Task(3, "Washing up")); while (!myQueue.empty()) { cout << myQueue.top().task << endl; myQueue.pop(); } ● Output: Go to the cinema Solve the programming assignments Washing up set example #include <set> set <int> mySet; mySet.insert(4); mySet.insert(2); mySet.insert(4); for ( set<int>::iterator it = mySet.begin(); it != mySet.end(); it++ ) { cout << val << endl; } // With BOOST_FOREACH defined as foreach, // the loop header could have been written: // foreach(int& val, mySet) ● Output: 4 2 map #include <map> map <int, double> myMap; // Format: insert(pair<type1,type2>(key, value)) typedef pair<int,double> MyPair; myMap.insert(MyPair(1, 4.7)); myMap.insert(MyPair(3, 8.5)); myMap.insert(MyPair(4, 9.0)); // Accessing the data using a key cout << "myMap[4] = " << myMap[4] << endl; // Traversing all elements for ( map<int,double>::iterator it = myMap.begin(); it != myMap.end(); it++) { cout << it->first << " " << it->second << endl; } // BOOST_FOREACH runs into trouble here ● Output: myMap[4] = 9 1 4.7 3 8.5 4 9 BOOST_FOREACH with map ● Trouble: foreach (pair<int,double>& pair, myMap) - Won't work because the <> doesn't work with the foreach-macro and an object in a map is not stored directly as a pair. ● This works instead: typedef map<int,double> MapType; foreach (MapType::value_type& pair, myMap) { pair.second += 2.0; } STL drawbacks ● There is no neat way of initializing containers to a small set of values, as for example: int array[] = {1,44,72,100}; ● The way of using iterators for simple tasks leads to long notation: for( vector<int>::iterator it = vec.begin(); it != vec.end(); it++ ) sort(vec.begin(), vec.end()) // vec.sort() would be nicer I think Error messages ● Are the right header files included? ● Are the right namespaces used? ● Are the right libraries included? ● Is there something wrong on the line before the error line? Extra checks during debugging // Is this a debug build? #ifdef DEBUG // Some tests #endif // (Windows only) Is running under debugger? if ( IsDebuggerPresent() ) { // Some tests } ● ● Coherency is often good to test. This is called assertions. 'assert' is a keyword for testing conditions and aborting(!) the program if they don't hold. But often you don't want the program to abort but rather to handle the error in some way. C++0x B. Stroustrup on overall goals: ”- Make C++ a better language for systems programming and library building - Make C++ easier to teach and learn” Some features: ● Increased type safety ● Type inference ● More functional programming constructs Connecting Python and C ● Using C-functions from Python: Wrapper functions in C must be created ● Boost.Python or SWIG simplifies this process. ● Help on using SWIG: http://www.swig.org/Doc1.3/Python.html#Python_nn6 Source file //func.cpp // Just contains a simple test function int add(int a, int b) { return a+b; } SWIG interface file //func.i %module func %{ extern int add(int, int); %} extern int add(int, int); Compiling for use in Python ● Compile func.c and generate the object file func.o: $ gcc -c -fpic func.c ● Create the wrapper code from the specification i func.i. Generates func_wrap.c and func.py: $ swig -python func.i ● Compile the wrapper: $ gcc -c -fpic func_wrap.c -I/usr/include/python2.4 ● Link the object files to _func.so: $ gcc -shared func.o func_wrap.o -o _func.so Use in Python rontok> python Python 2.3.5 (#2, Feb 23 2005, 18:16:39) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import func >>> func.add(2,7) 9 >>> SWIG in Windows ● Swigwin together with Microsoft Visual C++. ● http://www.swig.org/download.html ● Look at the examples for Python which comes with the installation.