Share
Embed
АФТИ ООП 2013-2014. Лекция I/12
Справка по стандартной библиотеке C++: http://www.cplusplus.com/reference/stl/, http://www.cplusplus.com/reference/algorithm/ и др.
Oleg Dashevskii
December 09, 2013
Transcript
17 slides
-
СТАНДАРТНАЯ БИБЛИОТЕКА C++ • Включает в себя стандартную библиотеку C.
• Содержит ОО-реализацию наиболее часто используемых структур данных и алгоритмов. • Показывает, что можно вытворять на C++. -
• АТД «Очередь». • Двойная абстракция: • …от деталей реализации
(способа хранения в памяти). • …от типа хранимых данных. -
class IntegerQueue { /* ... */ }; ! class DoubleQueue
{ /* ... */ }; ! class WTFElseQueue { /* ... */ }; -
template <class T> class Queue { /* ..... */ !
}; ! class Person { /* ...... */ }; ! Queue<double> doubleQ; Queue<int> intQ; Queue<Person> personQ; Шаблон класса -
ОПЕРАЦИИ class Vector2D { // .... }; ! Vector2D x,
y; Vector2D z = x.add(y); z = z.mul(x); z = z.sub(x.div(y)); z = x + y; z *= x; z -= x / y; -
z = operator+(x, y); z.operator*=(x); z.operator-=(operator/(x, y)); z = x
+ y; z *= x; z -= x / y; ! -
STD::VECTOR • АТД «Динамический массив» #include <vector> ! std::vector<int> intarray;
! intarray.resize(100); ! for (int i = 0; i < intarray.size(); ++i) intarray[i] = i; ! intarray.push_back(0); -
STD::STRING • Символьная строка #include <string> ! ! std::string s;
! s = "hello" + ", world"; s += "!"; -
STD::MAP • АТД «Двоичное дерево» #include <vector> #include <map> #include
<string> ! using namespace std; ! map<string, int> wordCounts; vector<string> words; ! for (int i = 0; i < words.size(); ++i) { const string &w = words[i]; map<string, int>::iterator it = wordCounts.find(w); ! if (it == wordCounts.end()) wordCounts[w] = 1; else ++it->second; } -
ИТЕРАТОРЫ for (vector<string>::const_iterator it = words.begin(); it != words.end(); ++it)
{ // *it - текущая строка } ! for (map<string, int>::const_iterator it = wordCounts.begin(); it != wordCounts.end(); ++it) { // it->first - текущий ключ // it->second - текущее значение } • Абстракция указателя/индекса. -
ДРУГИЕ АТД • std::deque – двусторонняя очередь. Похожа на std::vector,
но вставка/ удаление работает быстро с обоих концов. • std::list – «честный» двусвязный список. • std::queue – очередь (на базе deque/list). • std::stack – стек (на базе deque/list). • std::priority_queue – очередь с приоритетами (пирамида на базе std::vector). • std::set, std::multiset – (мульти-)множество. -
ВВОД / ВЫВОД #include <iostream> ! std::cin >> x >>
y; std::cout << x << y << "Hello !" << '\n'; ! double f = 3.14159; std::cout.precision(5); std::cout << f << '\n'; std::cout.precision(10); std::cout << f << '\n'; -
ФАЙЛЫ #include <fstream> // std::ofstream ! int main() { std::ofstream
ofs("test.txt"); ! ofs << "lorem ipsum"; ! ofs.close(); ! return 0; } -
АЛГОРИТМЫ • Шаблонизированы и работают с любыми типами и подходящими
контейнерами. • Обычно оперируют диапазоном между двух итераторов: начало, конец. • Поиск, сортировка, копирование, удаление, упорядочивание, … -
#include <iostream> // std::cout #include <algorithm> // std::sort #include <vector>
// std::vector ! bool myfunction(int i, int j) { return i < j; } ! struct myclass { bool operator() (int i,int j) { return i < j; } } myobject; ! int main () { int myints[] = {32,71,12,45,26,80,53,33}; std::vector<int> myvector(myints, myints+8); // 32 71 12 45 26 80 53 33 ! // using default comparison (operator <): std::sort(myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33 ! // using function as comp std::sort(myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80) ! // using object as comp std::sort(myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80) ! // print out content: std::cout << "myvector contains:"; for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; ! return 0; }