Download presentation
Presentation is loading. Please wait.
1
Обзор на стандартната библиотека Доц. д-р Владимир Димитров e-mail: cht@fmi.uni-sofia.bgcht@fmi.uni-sofia.bg Web: cht_co.tripod.com Wap: http://www.wapdrive.com/cht_co
2
Съдържание 1 1. Увод 2. Hello, world! 3. Пространство на имената на стандартната библиотека 1. Стандартен изход 4. Символни низове 1. Символни низове в C- стил 6. Стандартен вход 7. Контейнери 1. Вектор 2. Проверка на индекса 3. Списък 4. Карта 5. Стандартни контейнери
3
Съдържание 2 8. Алгоритми 1. Използване на итератори 2. Типове итератори 3. Итератори и входно- изходни операции 4. Предикати 5. Алгоритми използващи функции- членове 6. Алгоритми на стандартната библиотека 9. Math 1. Комплексни числа 2. Векторна аритметика 3. Поддръжка на основната аритметика 10. Средства на стандартната библиотека 11. Заключение
4
Hello, world! #include int main() { std::cout << "Hello, world!\n"; }
5
Пространство на имената на стандартната библиотека #include std::string s = "Four legs Good; two legs Baaad!; std::list slogans; #include // make the standard string facilities accessible using namespace std; // make names available without std:: prefix string s= "Ignorance is bliss!"; // ok: string is std::string
6
Стандартен изход 1 void f() { cout << 10; } void g() { int i = 10; cout << i; } void h(int i) { cout << "the value of i is "; cout << i; cout << '\n'; } Извежда, при i == 10: the value of i is 10
7
Стандартен изход 2 void k() { cout << 'a'; cout << 'b'; cout << 'c'; } Извежда: abc void h2(int i) { cout << "the value of i is " << i << '\n'; }
8
Символни низове 1 string s1 = "Hello"; string s2 = "world"; void m1() { string s3 = s1 + ", " + s2 + "!\n"; cout << s3; }
9
Символни низове 2 void m2 (string& s1, string& s2) { s1 = s1 + '\n'; // append newline s2 += '\n'; // append newline }
10
Символни низове 3 string incantation; void respond(const strings answer) { if (answer == incantation) { // perform magic } else if (answer == "yes") { // … }
11
Символни низове 4 string name = "Niels Stroustrup"; void m3() { string s = name.substr(6, 10); // s = "Stroustrup" name.replace (0, 5, "Nicholas"); // name becomes "Nicholas Stroustrup" }
12
Символни низове в C-стил void f() { printf("name %s\n", name.c_str()); }
13
Стандартен вход 1 void f() { int i; cin >> i; // read an integer into i double d; cin >> d; // read a double-precision, // floating-point number into d }
14
Стандартен вход 2 int main() { const float factor = 2 2.5 54 4; // 1 inch equals 2.54 cm float x, in, cm;char ch = 0; cout << "enter length: "; cin >> x; // read a floating-point number cin >> ch; // read a suffix switch(ch) { case 'i': // inch in = x;cm = x*factor;break; case 'c': // cm in = x/factor; cm = x; break; default: in = cm = 0;break; } cout << in << " in = " << cm << " cm\n"; }
15
Стандартен вход 3 int main() { string str; cout << "Please enter your name\n"; cin >> str; cout << "'Hello, " << str << "!\n"; } Вход: EricОтговор: Hello, Eric! Вход: Eric BloodaxeОтговор: Hello, Eric!
16
Стандартен вход 4 int main() { string str; cout << "Please enter your name\n"; getline(cin, str); cout << "'Hello, " << str << "!\n"; } Вход: EricОтговор: Hello, Eric! Вход: Eric BloodaxeОтговор: Hello, Eric Bloodaxe!
17
Вектор 1 struct Entry { string name; int number; }; Entry phone_book[1000]; void print_entry(int i) // simple use { cout << phone_book[i].name << ' ' << phone_book[i].number << '\n'; }
18
Вектор 2 vector phone_book(1000); void print_entry(int i) // simple use, exactly as for array { cout << phone_book[i].name << ' ' << phone_book[i].number << '\n'; } void add_entries(int n) // increase size by n { phone_book.resize(phone_book.size() + n); }
19
Вектор 3 vector book(1000); // vector of 1000 elements vector books[1000]; // 1000 empty vectors void f(vector & v) { vector v2 = phone_book; v = v2; //... }
20
Проверка на индекса 1 void f() { int i = phone_book[1001].number; // 1001 is out of range //... }
21
Проверка на индекса 2 template class Vec : public vector { public: Vec() : vector () { } Vec(int s) : vector (s) { } T& operator [] (int i) { return at(i); } //range-checked const T& operator [] (int i) const { return at(i); } //range-checked } Vec phone_book(1000);
22
Проверка на индекса 3 void print_entry(int i) // simple use, exactly as for vector { cout << phone_book[i].name << ' ' << phone_book[I].number << '\n'; } void f() { try { for (int i= 0; i<10000; i++) print_entry(i); } catch (out_of_range) { cout << "range error"; }
23
Проверка на индекса 4 int main() try { // your code } catch(out_of_range) { cerr << " range error\n"; } catch (...) { cerr << "unknown exception throw\n"; }
24
Списък 1 list phone_book; void print_entry(const string& s) { typedef list ::const_iterator LI; for (LI i = phone_book.begin(); i != phone_book.end(); ++i) { const Entry& e = *i; // reference used as shorthand if (s == e.name) { cout << e.name << ' ' << e.number << "\n"; return; }
25
Списък 2 void f(const Entry& e, list ::iterator i, list ::iterator p) { phone_book.push_front(e);// add at beginning phone_book.push_back(e);// add at end phone_book.insert(i, e);// add before the element referred to by 'i' phone_book.erase(p);// remove the element referred to by 'p' }
26
Карта map phone_book; void print_entry(const string& s) { if (int i = phone_book[s]) cout << s << ' ' << i << '\n'; }
27
Стандартни контейнери vector A variable-sized vector list A doubly-linked list queue A queue stack A stack deque A double-ended queue priority_queue A queue sorted by value set A set multiset A set in which a value can occur many times map An associative array multimap A map in which a key can occur many times
28
Алгоритми 1 void f(vector & ve, list & le) { sort (ve.begin(), ve.end()); unique_copy(ve.begin(), ve.end(), le.begin()); } void f(vector & ve, list & le) { sort (ve.begin(), ve.end()); unique_copy(ve.begin(), ve.end(), back_inserter(le)); // append to le }
29
Алгоритми 2 void f(vector & ve, list & le) { copy(ve.begin(), ve.end(), le); // error: le not an iterator copy(ve.begin(), ve.end(), le.end()); // bad: writes beyond the end copy(ve.begin(), ve.end(), le.begin()); // overwrite elements }
30
Използване на итератори 1 int count(const string& s, char c) // count occurrences of c in s { int n = 0; string::const_iterator i = find(s.begin(), s.end(), c); while (i != s.end()) { ++n; i = find(i + 1, s.end(), c); } return n; }
31
Използване на итератори 2 void f() { string m = "Mary had a little lamb"; int account = count(m, 'a'); } Maryhadalittlelamb
32
Използване на итератори 3 template int count (const C& v, T val) { typename C::const_iterator i = find(v.begin(), v.end(), val); int n = 0; while (i != v.end()) { ++n; ++i; // skip past the element we just found i = find(i, v.end(), val); } return n; }
33
Използване на итератори 4 void f(list & lc, vector & vs, string s) { int i1 = count(lc, complex(1, 3)); int i2 = count(vs, "Diogenes"); int i3 = count(s, 'x'); }
34
Типове итератори 1 PietHein Вектор: Итератор: p PietHein Вектор: Итератор: (start == p, position == 3)
35
Типове итератори 2 връзка P i e t … p итератор: списък: елементи:
36
Итераторите и входно/изходните операции 1 ostream_iterator oo(cout); int main() { *oo = "Hello, "; // meaning cout << "Hello, " ++oo; *oo = "world!\n"; // meaning cout << "world!\n" }
37
Итераторите и входно/изходните операции 2 istream_iterator ii(cin); istream_iterator eos; int main() { string s1 = *n; ++n; string s2 = *ii; cout << s1 << " " << s2 << '\n'; }
38
Итераторите и входно/изходните операции 3 int main() { string from, to; cin >> from >> to;// get source and target file names ifstream is(from.c_str());// input stream istream_iterator ii(is); // input iterator for stream istream_iterator eos; // input sentinel vector b(ii,eos); // b is a vector initialized from input sort(b.begin(), b.end());// sort the buffer ofstream os(to.c_str());// output stream ostream_iterator oo(os, "\n"); // output iterator for stream unique_copy(b.begin(), b.end(), oo);// copy buffer to output, // discard replicated values return !is.eof() || !os; // return error state }
39
Предикати 1 map histogram; void record(const string& s) { histogram[s]++;// record frequency of "s" } void print(const pair & r) { cout << r.first << ' ' << r.second << '\n'; } int main() { istream_iterator ii(cin); istream_iterator eos; for_each(ii, eos, record); for_each(histogram.begin(), histogram.end(), print); }
40
Предикати 2 bool gt_42(const pair & r) { return r.second>42; } void f(map & m) { typedef map ::const_iterator MI; MI i = find_if(m. begin(), m.end(), gt_42); //... } void g(const map & m) { int c42 = count_if(m.begin(), m.end(), gt_42); //... }
41
Алгоритми използващи функции-членове void draw(Shape* p) { p->draw(); } void f(list & sh) { for_each(sh. begin(), sh.end(), draw); } void g(list & sh) { for_each(sh.begin(), sh.end(), mem_fun(&Shape::draw)); }
42
Алгоритми от стандартната библиотека for_each()Invoke function for each element find() Find first occurrence of arguments find_if() Find first match of predicate count() Count occurrences of element count_if() Count matches of predicate replace() Replace element with new value replace_if()Replace element that matches predicate with new value copy() Copy elements unique_copy() Copy elements that are not duplicates sort() Sort elements equal_range() Find all elements with equivalent values merge() Merge sorted sequences
43
Комплексни числа template class complex { public: complex(scalar re, scalar im); //... } // standard exponentiation function from : template complex pow(const complex &, int); void f(complex fl, complex db) { complex ld = fl + sqrt(db); db += fl * 3; fl = pow(1/ fl, 2); //... }
44
Векторна аритметика template class valarray { //... T& operator [] (size_t) ; //... }; // standard absolute value function from : template valarray abs(const valarray &); void f (valarray & a1, valarray & a2) { valarray a = a1 * 3.14 + a2 / a1; a2 += a1 * 3.14; a = abs(a); double d = a2[7]; // … }
45
Заключение 1 Не преоткривай колелото - използвай библиотеките Не вярвай в магията, разбери какво правят библиотеките, как го правят и на какво цена Когато имаш избор предпочитай стандартната билиотека пред другите Не мисли, че стандартната библиотека е идеална за всичко Не забравяй да използваш #include за заглавните файлове на това, което използваш
46
Заключение 2 Не забравяй, че стандартната библиотека е дефинирана в пространството на имена std Използвай string вместо char* Ако имаш проблеми използвай вектор с проверка на индекса За предпочитане са vector, list, и map пред T[] Когато добавяш елементи към контейнера използвай push_back() или back_inserter() Използвай push_back() върху вектор вместо realloc() върху масив Хващай общите изключения в main()
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.