Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 25

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 25 страницаB. Stroustrup - The C++ Programming Language (794319) страница 252019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 25)

First, a set of libraries isdeveloped. These then form the basis for further work. Most programs are tedious to write in thebare language, whereas just about any task can be rendered simple by the use of good libraries.Continuing from Chapters 2 and 3, this chapter and the next give a quick tour of key standardlibrary facilities.

I assume that you have programmed before. If not, please consider reading atextbook, such as Programming: Principles and Practice Using C++ [Stroustrup,2009], beforecontinuing. Even if you have programmed before, the libraries you used or the applications youwrote may be very different from the style of C++ presented here. If you find this ‘‘lightning tour’’confusing, you might skip to the more systematic and bottom-up language presentation starting inChapter 6. Similarly, a more systematic description of the standard library starts in Chapter 30.88A Tour of C++: Containers and AlgorithmsChapter 4I very briefly present useful standard-library types, such as string, ostream, vector, map (thischapter), unique_ptr, thread, regex, and complex (Chapter 5), as well as the most common ways ofusing them. Doing this allows me to give better examples in the following chapters.

As in Chapter2 and Chapter 3, you are strongly encouraged not to be distracted or discouraged by an incompleteunderstanding of details. The purpose of this chapter is to give you a taste of what is to come andto convey a basic understanding of the most useful library facilities.The specification of the standard library is almost two thirds of the ISO C++ standard. Exploreit, and prefer it to home-made alternatives. Much though have gone into its design, more still intoits implementations, and much effort will go into its maintenance and extension.The standard-library facilities described in this book are part of every complete C++ implementation.

In addition to the standard-library components, most implementations offer ‘‘graphical userinterface’’ systems (GUIs), Web interfaces, database interfaces, etc. Similarly, most applicationdevelopment environments provide ‘‘foundation libraries’’ for corporate or industrial ‘‘standard’’development and/or execution environments.

Here, I do not describe such systems and libraries.The intent is to provide a self-contained description of C++ as defined by the standard and to keepthe examples portable, except where specifically noted. Naturally, a programmer is encouraged toexplore the more extensive facilities available on most systems.4.1.1 Standard-Library OverviewThe facilities provided by the standard library can be classified like this:• Run-time language support (e.g., for allocation and run-time type information); see §30.3.• The C standard library (with very minor modifications to minimize violations of the typesystem); see Chapter 43.• Strings and I/O streams (with support for international character sets and localization); seeChapter 36, Chapter 38, and Chapter 39. I/O streams is an extensible framework to whichusers can add their own streams, buffering strategies, and character sets.• A framework of containers (such as vector and map) and algorithms (such as find(), sort(),and merge()); see §4.4, §4.5, Chapters 31-33.

This framework, conventionally called theSTL [Stepanov,1994], is extensible so users can add their own containers and algorithms.• Support for numerical computation (such as standard mathematical functions, complexnumbers, vectors with arithmetic operations, and random number generators); see §3.2.1.1and Chapter 40.• Support for regular expression matching; see §5.5 and Chapter 37.• Support for concurrent programming, including threads and locks; see §5.3 and Chapter 41.The concurrency support is foundational so that users can add support for new models ofconcurrency as libraries.• Utilities to support template metaprogramming (e.g., type traits; §5.4.2, §28.2.4, §35.4),STL-style generic programming (e.g., pair; §5.4.3, §34.2.4.1), and general programming(e.g., clock; §5.4.1, §35.2).• ‘‘Smart pointers’’ for resource management (e.g., unique_ptr and shared_ptr; §5.2.1, §34.3)and an interface to garbage collectors (§34.5).• Special-purpose containers, such as array (§34.2.1), bitset (§34.2.2), and tuple (§34.2.4.2).Section 4.1.1Standard-Library Overview89The main criteria for including a class in the library were that:• it could be helpful to almost every C++ programmer (both novices and experts),• it could be provided in a general form that did not add significant overhead compared to asimpler version of the same facility, and• that simple uses should be easy to learn (relative to the inherent complexity of their task).Essentially, the C++ standard library provides the most common fundamental data structurestogether with the fundamental algorithms used on them.4.1.2 The Standard-library Headers and NamespaceEvery standard-library facility is provided through some standard header.

For example:#include<string>#include<list>This makes the standard string and list available.The standard library is defined in a namespace (§2.4.2, §14.3.1) calledlibrary facilities, the std:: prefix can be used:std.To use standardstd::string s {"Four legs Good; two legs Baaad!"};std::list<std::string> slogans {"War is peace", "Freedom is Slavery", "Ignorance is Strength"};For simplicity, I will rarely use the std:: prefix explicitly in examples. Neither will I always#include the necessary headers explicitly. To compile and run the program fragments here, youmust #include the appropriate headers (as listed in §4.4.5, §4.5.5, and §30.2) and make the namesthey declare accessible. For example:#include<string>using namespace std;// make the standard string facilities accessible// make std names available without std:: prefixstring s {"C++ is a general−purpose programming language"};// OK: string is std::stringIt is generally in poor taste to dump every name from a namespace into the global namespace.However, in this book, I use the standard library almost exclusively and it is good to know what itoffers.

So, I don’t prefix every use of a standard library name with std::. Nor do I #include theappropriate headers in every example. Assume that done.Here is a selection of standard-library headers, all supplying declarations in namespace std:Selected Standard Library Headers (continues)<algorithm><array><chrono><cmath><complex><fstream><future><iostream>copy(), find(), sort()arrayduration, time_pointsqrt(), pow()complex, sqrt(), pow()fstream, ifstream, ofstreamfuture, promiseistream, ostream, cin, cout§32.2§34.2.1§35.2§40.3§40.4§38.2.1§5.3.5§38.1§iso.25§iso.23.3.2§iso.20.11.2§iso.26.8§iso.26.8§iso.27.9.1§iso.30.6§iso.27.490A Tour of C++: Containers and AlgorithmsChapter 4Selected Standard Library Headers (continued)<map><memory><random><regex><string><set><sstream><thread><unordered_map><utility><vector>map, multimapunique_ptr, shared_ptr, allocatordefault_random_engine, normal_distributionregex, smatchstring, basic_stringset, multisetistrstream, ostrstreamthreadunordered_map, unordered_multimapmove(), swap(), pairvector§31.4.3§5.2.1§40.7Chapter 37Chapter 36§31.4.3§38.2.2§5.3.1§31.4.3.2§35.5§31.4§iso.23.4.4§iso.20.6§iso.26.5§iso.28.8§iso.21.3§iso.23.4.6§iso.27.8§iso.30.3§iso.23.5.4§iso.20.1§iso.23.3.6This listing is far from complete; see §30.2 for more information.4.2 StringsThe standard library provides a string type to complement the string literals.

Thevides a variety of useful string operations, such as concatenation. For example:stringtype pro-string compose(const string& name, const string& domain){return name + '@' + domain;}auto addr = compose("dmr","bell−labs.com");Here, addr is initialized to the character sequence dmr@bell−labs.com. ‘‘Addition’’ of strings meansconcatenation. You can concatenate a string, a string literal, a C-style string, or a character to astring. The standard string has a move constructor so returning even long strings by value is efficient (§3.3.2).In many applications, the most common form of concatenation is adding something to the endof a string. This is directly supported by the += operation. For example:void m2(string& s1, string& s2){s1 = s1 + '\n'; // append newlines2 += '\n';// append newline}The two ways of adding to the end of a string are semantically equivalent, but I prefer the latterbecause it is more explicit about what it does, more concise, and possibly more efficient.A string is mutable.

In addition to = and +=, subscripting (using []) and substring operations aresupported. The standard-library string is described in Chapter 36. Among other useful features, itprovides the ability to manipulate substrings. For example:Section 4.2Strings91string name = "Niels Stroustrup";void m3(){string s = name.substr(6,10);name.replace(0,5,"nicholas");name[0] = toupper(name[0]);}// s = "Stroustrup"// name becomes "nicholas Stroustrup"// name becomes "Nicholas Stroustrup"The substr() operation returns a string that is a copy of the substring indicated by its arguments.The first argument is an index into the string (a position), and the second is the length of the desiredsubstring.

Характеристики

Тип файла
PDF-файл
Размер
18,76 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6508
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее