Some other issues in C tsaiwncsie nctu edu

  • Slides: 49
Download presentation
Some other issues in C++ 蔡文能 tsaiwn@csie. nctu. edu. tw tsaiwn@cs. nctu. edu. tw

Some other issues in C++ 蔡文能 tsaiwn@csie. nctu. edu. tw tsaiwn@cs. nctu. edu. tw 交通大學資訊 程學系 2006/08/23 1 交通大學資訓 程學系 蔡文能

http: //tsaiwn. net/cpp/ Agenda http: //www. csie. nctu. edu. tw/~tsaiwn/cpp • • Namespace static

http: //tsaiwn. net/cpp/ Agenda http: //www. csie. nctu. edu. tw/~tsaiwn/cpp • • Namespace static ? const ? cast in C++ Class Library STL – Standard Template Library Exception handling 2 交通大學資訓 程學系 蔡文能

Namespaces • variables with same name and different scopes can overlap – need to

Namespaces • variables with same name and different scopes can overlap – need to distinguish them • a namespace defines a scope for local and global identifiers. – body delimited by braces {} – use (: : ) to access namespace members: 例如 std: : cout namespace_name: : member – or, a using statement must occur before name is used using namespace_name; -members of the namespace do not need a prefix – not guaranteed to be unique – can be nested using namespace std; //for STL 交通大學資訓 程學系 蔡文能 3

神奇的 “static” ü On a global variable or a function static long my. Data[38];

神奇的 “static” ü On a global variable or a function static long my. Data[38]; //information hiding static void my. Function(float); – Tells the linker not to export the variable or function. – Makes the identifier “file scope, ” as the linker will not use it fulfill dependencies from other files. ü On a local variable in a function void some. Func(void) { static int array[4000]; } Places the variable off the stack. This has the side-effect that it retains it value across calls. It is often used when a variable is too large to be put on the stack. (auto變數則在 stack) ü On a class member data or member function (next slide) 4 交通大學資訓 程學系 蔡文能

Static Global 變數 #include <stdio. h> 參考K&R課本 4. 6節 #define BUFSIZE 100 static char

Static Global 變數 #include <stdio. h> 參考K&R課本 4. 6節 #define BUFSIZE 100 static char buf[BUFSIZE]; int bufp = 0; 別的檔案中任何function都 int getch( ) { 看不見這個 static 的變數 /*. . . */ } void ungetch(int c) { /*. . . */ 也參考stack的push和pop寫在同一獨 } 立 file 中, push和pop共享 data 交通大學資訓 程學系 蔡文能 5

再談Static Global 變數 #include <stdio. h> 參考K&R課本 4. 6節 #define RAND_MAX 65535 static unsigned

再談Static Global 變數 #include <stdio. h> 參考K&R課本 4. 6節 #define RAND_MAX 65535 static unsigned long seed=0; int rand( ) { seed = seed * 1103515245 + 12345; return seed % (RAND_MAX+1); } void srand(int newseed) { seed = newseed; } 交通大學資訓 程學系 蔡文能 Pseudo random number 6

Static Local變數 (1/2) #include <iostream. h> int fa( ) { int x = 1;

Static Local變數 (1/2) #include <iostream. h> int fa( ) { int x = 1; return x++; /*先取其值, 再做 ++ */ } int fb( ) { static int x = 1; /* 注意 static int x = 1; */ return x++; } int main( ) { cout << "fa( )=" << fa( )<<fa( ) << endl; cout << "fb( )=" << fb( )<<fb( ) << endl; return 0; /* 0 in main( ) means OK */ } return x++; 和 return ++x; 不同 ! 7 交通大學資訓 程學系 蔡文能

Static class member • static member不需要透過任何的object存取,在無任何 object時可透過member selection operators (就是 : : 或Java 仍用.

Static class member • static member不需要透過任何的object存取,在無任何 object時可透過member selection operators (就是 : : 或Java 仍用. )來存取. • Static member functions – Also known as class function (class methods) – Can be called without any instance, for example: m = Mankind: : howmany( ); – Can NOT access instance variables • Static member data – Also known as class variable – All objects of a class share one copy of a static data member (non-static member data = instance variable) – Usage example: x = Mankind: : data_which_is_static; – They are not global variables; they have class scope All member functions are shared between objects, even the non-static member functions 交通大學資訓 程學系 蔡文能 10

神奇的 “const” ü Const object is NOT modifiable ü const x = 3. 14159;

神奇的 “const” ü Const object is NOT modifiable ü const x = 3. 14159; // 在 C 與較舊C++ compile會過; 問題在哪裡? ü Const parameter can NOT be modified in the function Return. Type Function. Name(long x, const Student y){ /*… to modify y is NOT allowed! 即 y 不可當左值 */ }; ü Const member function can NOT modify the object Return. Type Function. Name(param 1, param 2…) const; Return. Type Function. Name(param 1, param 2…) const { /*… */}; ü Constructors / Destructors cannot be const - They need to initialize variables (therefore modifying them) const 是不准變的變數! 也佔一塊記憶體! 那 #define nsize 99 呢? 交通大學資訓 程學系 蔡文能 11

Review: Constants 常數 • #define MAX_LOOP 500 – 此稱 define macro 巨集 – 是C的前處理器之句子,

Review: Constants 常數 • #define MAX_LOOP 500 – 此稱 define macro 巨集 – 是C的前處理器之句子, 結尾不必有分號 – 之後用到 MAX_LOOP 會被換成 500 • const double delta = 0. 0001; ^^^^^^^^ 不可變的變數叫const • const PI = 3. 14159; /* Error result? PI為 3*/ 12 交通大學資訓 程學系 蔡文能

Character Literal • 單引號夾住是 char – 'A' 相當於 65 (assume using ASCII) – 'a'

Character Literal • 單引號夾住是 char – 'A' 相當於 65 (assume using ASCII) – 'a' 相當於 97 (assume using ASCII) – '0' 相當於 48 (assume using ASCII) • Wide character ? • Escape Sequence 逃脫序列串 – 'n' – '101' – 'x 41' == '12 ' == 'A' 13 交通大學資訓 程學系 蔡文能

Escape Sequence 逃脫序列串 • • • 'a' 'b' 'f' 'n' 'r' 't' 'v' '

Escape Sequence 逃脫序列串 • • • 'a' 'b' 'f' 'n' 'r' 't' 'v' ' \' '? ' '' ' '" ' == '07' == CTRL_G == Alert (Bell) == '10' == CTRL_H == Back. Space == '14' == CTRL_L == Form. Feed == '12' == CTRL_J == New. Line == '15' == CTRL_M == Carriage RETURN == '11' == CTRL_I == TAB'60' (Horizontal Tab) == == Vertical Tab == == backslash 反斜線 'x 30' == == question mark == == single quote ( apostrophe ) == == double quote (quote) 參考K&R課本 2. 3節 交通大學資訓 程學系 蔡文能 14

Cast in C++ • C++ has 4 more separate, specific casts – Conventional static

Cast in C++ • C++ has 4 more separate, specific casts – Conventional static cast (C-Style): (type)expression ü static_cast - conversion between types • • type checking at compile time standard conversions: void* to char*, int to float, etc. base class pointers to derived class pointers Format: static_cast<type to convert to>(object to convert) ü const_cast - cast away const or volatile • cannot be used directly to cast away const-ness; use pointers ü dynamic_cast – for safe navigation of an inheritance hierarchy. • Can be used only for pointer or reference types ü reinterpret_cast - for nonstandard casts • one pointer type to another pointer type, void* to int*, etc. • cannot be used for standard casts (int to double, etc. ). 15 交通大學資訓 程學系 蔡文能

C ++ class Library <algorithm> <exception> <ios> <iterator> <map> <ostream> <set> <typeinfo> <cmath> <bitset>

C ++ class Library <algorithm> <exception> <ios> <iterator> <map> <ostream> <set> <typeinfo> <cmath> <bitset> <fstream> <iosfwd> <list> <memory> <queue> <sstream> <utility> <complex> <functional> <iostream> <locate> <new> <streambuf> <stack> <valarray> <deque> <iomanip> <istream> <limits> <numeric> <string> <stdexcept> <vector> 16 交通大學資訓 程學系 蔡文能

Standard C Library <stdio. h> <math. h> <stdlib. h> <string. h> <ctype. h> <time.

Standard C Library <stdio. h> <math. h> <stdlib. h> <string. h> <ctype. h> <time. h> <assert. h> <float. h> <limits. h> <stdarg. h> <stddef. h> <errno. h> <locale. h> <signal. h> <setjmp. h> • open, read, write, close 等不是 standard C Library, 而是 system call • C Library 在 UNIX 手冊第三章, System call 在 UNIX 手冊 第二章( 用 man 會看到 (2) ) • 所有 Library function 參看 K&R 附錄B 19 交通大學資訓 程學系 蔡文能

The C++ String Class • The C-style strings (arrays of char) that you’ve been

The C++ String Class • The C-style strings (arrays of char) that you’ve been using are not the only way of managing character data. • C++ allows you to work with a string class that eases many of the problems you’ve encountered with C-style strings. • In particular, you don’t have to worry about managing memory for the string data. 20 交通大學資訓 程學系 蔡文能

C++ String Basics • The basic character template class is basic_string<>. • It has

C++ String Basics • The basic character template class is basic_string<>. • It has two specializations (generated using typedefs), string and wstring. • string corresponds to the C-style string (I. e. , const *char). • wstring is an extension for languages that use characters. • You can copy, assign, and compare strings just like you would copy, assign, and compare primitive types (int, double) string a = “Hello”; string b = string(a); string c = a; bool d = (a==b); 21 交通大學資訓 程學系 蔡文能

using the String types • In the header file <string> – (Note, no. h)

using the String types • In the header file <string> – (Note, no. h) • All such functions and other names are in the namespace std. • The basic class name is a template class, basic_string<>. • String constructors string( ) // empty string(string s) // copy of s string(string s, int start) // substring(string s, int start, int len) // substring(char* a) // C-string(int cnt, char c) // one or more chars string(char* beg, char* end) // [beg, end) 22 交通大學資訓 程學系 蔡文能

Accessing Individual Characters • It’s almost like for a C-string s = “Harry”; s[0]

Accessing Individual Characters • It’s almost like for a C-string s = “Harry”; s[0] is ‘H’ s[1] is ‘a’ … s[5] is undefined!!!! – no ‘’ at the end 23 交通大學資訓 程學系 蔡文能

C++ string Operations • = is used to assign a value (char, C-string, or

C++ string Operations • = is used to assign a value (char, C-string, or string) to a string. • += is used to append a string, character, or C-string to a string. • + is used to concatenate two strings or a string with something else • Boolean operations do a dictionary order comparison • << and >> are used for input and output. On input, leading whitespace is skipped, and the input terminates with whitespace or end of file. 24 交通大學資訓 程學系 蔡文能

Other C++ string Operations swap(a, b); // swap the guts of a with b

Other C++ string Operations swap(a, b); // swap the guts of a with b s. append(s 2); // append s 2 to s s. c_str( ); // return a C-string s. push_back(c); // append a char s. erase(various); // erases substrings s. insert(various); // inserts substrings s. clear(); // removes all contents s. resize(cnt); // change the size of s to cnt s. replace(various); // replaces characters s. size(); // how many characters? s. length(); // how many characters? s. max_size(); // maximum number of char? s. empty(); // is s empty? s. capacity(); // size without reallocation s. reserve(cnt); // reserves memory 25 交通大學資訓 程學系 蔡文能

Using c++ string s = "Harry "; s. data() // returns s as a

Using c++ string s = "Harry "; s. data() // returns s as a data array, no ''. s. c_str() // returns s as a C-string with '' int i = atoi(s. c_str()); // conversion char *carray = new char[80]; s. copy(carray, 79); // copies up to 79 char 26 交通大學資訓 程學系 蔡文能

STL Algorithms <algorithm> • binary_search • sort • count: count(list. begin(), list: end(), val,

STL Algorithms <algorithm> • binary_search • sort • count: count(list. begin(), list: end(), val, num); • equal: compares containers • for_each: applies ftn to each element • copy: copies container • reverse • min/max • Some in <numeric> 27 交通大學資訓 程學系 蔡文能

Using vector <int> v; v. reserve (100); // allocate space for 100 integers //

Using vector <int> v; v. reserve (100); // allocate space for 100 integers // capacity 100, size 0 int i; while (cin >> i) // read from the standard input v. push_back (i); // will expand v if needed for (i = 0; i < v. size (); ++i) cout << v[i]; try { // use checked access cout << v. at (100); // may throw } catch (std: : out_of_range&) { cout << "doesn't have 101 elements" << endl; } for (int i = 0; i < v. size () / 2; ++i) v. pop_back (); // remove second half vector <int> v 1 (v); // copy to v 1. insert (v 1. begin ()+1, 117); // insert after first 29 交通大學資訓 程學系 蔡文能

Utilities: pair • a helper class template std: : pair, used a lot by

Utilities: pair • a helper class template std: : pair, used a lot by the standard library template <typename T 1, typename T 2> // simplified struct pair { T 1 first; T 2 second; pair () : first (T 1()), second (T 2()) {} // init pair (const T 1&, const T 2&); . . . // etc. }; • provides a full range of comparison operations: ==, <, etc. • a related helper function template to make pairs: std: pair <int, double> w = std: : make_pair (1, 1. 2); 30 交通大學資訓 程學系 蔡文能

Sequences • There are several kinds of sequences; choose ü vectors when – there

Sequences • There are several kinds of sequences; choose ü vectors when – there are random access operations, – most insertions and removals are at the end of the container ü deques when – there are frequent insertions and deletions at either end, – there are random access operations ü lists when – there are frequent insertions and deletions at positions other than at the end – there are few random access operations – want to guarantee iterators are valid after modifications 31 交通大學資訓 程學系 蔡文能

Deques • deques are similar to vectors • deque iterators are random access •

Deques • deques are similar to vectors • deque iterators are random access • additionally two operations to insert/remove elements in front: push_front () add new first element pop_front () remove the first element • deques do not have operations capacity () and reserve () 32 交通大學資訓 程學系 蔡文能

Linked Lists list <char> s; // empty list s. insert (s. end (), 'a');

Linked Lists list <char> s; // empty list s. insert (s. end (), 'a'); s. insert (s. end (), 'b') // s has (a, b) list <char> s 1; // empty list // copy s to s 1: s 1. insert (s 1. end (), s. begin (), s. end ()); s. clear (); cout << s 1. front (); s 1. erase (s 1. begin ()); // remove first element 33 交通大學資訓 程學系 蔡文能

Iterators again • an iterator provides access to objects stored in a container (points

Iterators again • an iterator provides access to objects stored in a container (points to an element); every iterator it has to support: *it to access the element currently pointed to by the iterator ++it to move to the next element of the container it = = it 1 to compare two iterators for pointer equality it ! = it 1 to compare two iterators for pointer inequality • every container type provides one or more iterators in a uniform way as standardized type names: std: : vector <string>: : iterator std: : vector <string>: : const_iterator begin () end () returns an iterator pointing to the first element returns an iterator pointing past the end; serves as a sentinel, i. e. , end marker. 35 交通大學資訓 程學系 蔡文能

Iterators again (cont. ) • the iterator operations are sufficient for iterating over any

Iterators again (cont. ) • the iterator operations are sufficient for iterating over any Container: Container c; . . . Container: : iterator it; for (it = c. begin (); it != c. end (); ++it) {. . *it. . it->op (). . } • a sequence of consecutive values in the container is determined by an iterator range, defined by two iterators, [first, last) • last is assumed reachable from first by using the ++ operator, and all iterators, including first but excluding last can be dereferenced • two iterators can be compared for equality and inequality 36 交通大學資訓 程學系 蔡文能

Associative Containers • STL associative containers: – represent sorted collections – have keys, and

Associative Containers • STL associative containers: – represent sorted collections – have keys, and are sorted on these keys • A map is a mapping from keys to values: – it stores pairs (key, value) – there may be at most one pair with the same key – e. g. : (123, "Bush") and (124, "Kerry") • A multimap: – may have more than one pair with the same key – e. g. , (123, "Bush") and (123, "Kerry") 37 交通大學資訓 程學系 蔡文能

map usage // map: string to doubles map <string, double> salaries; // map: string

map usage // map: string to doubles map <string, double> salaries; // map: string to doubles sorted by greater <string> map <string, double, greater <string> > salaries 1; • to access an element of a map, you can use an overloaded index operator [] (key): salaries 1 ["John"] = 10000; salaries 1 ["Mary"] = 20000; • operator [] can not be used for multimaps; for example multimap <string, string> mm; mm ["color"] = "blue"; • instead, you have to use insert (): mm. insert ("color", "blue"); mm. insert ("color", "green"); // compile-time error 38 交通大學資訓 程學系 蔡文能

STL e. g. : using map • Goal: store grades for group of students

STL e. g. : using map • Goal: store grades for group of students – ordered set of assignments – maybe students with same name • For each student, have grades – want fast access to each grade – use vector of chars – typedef vector<int> Grades; • First, create map of students: • map<string, Grades> roster; 39 交通大學資訓 程學系 蔡文能

Using map: add a student to map • map represents a function: key maps

Using map: add a student to map • map represents a function: key maps to value • map, basically: set of ordered pairs – pair<x, y> template • void Roster: : add. Student(const string &name) { //check if already exists if (roster. find(name) != roster. end()) return; //check for room if (roster. size() == MAX) wait. List. push_back(name); else { Grades grades; roster. insert( pair<string, Grades>(name, grades)); } 40 交通大學資訓 程學系 蔡文能

Using map: drop a student • void Roster: : drop. Student(String &name) { if

Using map: drop a student • void Roster: : drop. Student(String &name) { if (roster. find(name) == roster. end()) return; roster. erase(name); if (wait. List. size() > 0) { string wait = wait. List. pop_front(); wait. List. pop(); Grades grades; roster. insert( pair<string, Grades>(name, grades)); } } 41 交通大學資訓 程學系 蔡文能

Using map: set a grade • void Roster: : set. Grade(const &string name, const

Using map: set a grade • void Roster: : set. Grade(const &string name, const int assign, const char grade) { map<string, Grades> stud = roster. find(name); if (stud == roster. end()) { cerr << “not foundn”; return; } if (stud->second(). size() <= assign) stud->second(). resize(assign+1); stud->second[assign] = grade; } 42 交通大學資訓 程學系 蔡文能

Associative Containers (cont. ) • set is a map for which the key and

Associative Containers (cont. ) • set is a map for which the key and the value are identical therefore it stores logically single elements rather than pairs • multisets are sometimes called bags; they are like sets except there may be more than one occurrence of an element with the same key • elements in associative containers are sorted by the value of a key • associative containers use a binary predicate less <Key>, which compares two Key elements, using Key: : operator<. • the less predicate also determines the meaning of two keys being equivalent: two keys of an associative container are equivalent if neither is less than the other 43 交通大學資訓 程學系 蔡文能

Container Operations 47 交通大學資訓 程學系 蔡文能

Container Operations 47 交通大學資訓 程學系 蔡文能

http: //www. csie. nctu. edu. tw/~tsaiwn/cpp/ Thank You! 謝謝捧場 tsaiwn@csie. nctu. edu. tw 蔡文能

http: //www. csie. nctu. edu. tw/~tsaiwn/cpp/ Thank You! 謝謝捧場 tsaiwn@csie. nctu. edu. tw 蔡文能 交通大學資訓 程學系 蔡文能 51