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

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

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

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

Such a string is terminated by a L'\0' character.Section 7.3.2.2Larger Character Sets179There are six kinds of character literals supporting Unicode (Unicode literals). This soundsexcessive, but there are three major encodings of Unicode: UTF-8, UTF-16, and UTF-32. For eachof these three alternatives, both raw and ‘‘ordinary’’ strings are supported.

All three UTF encodings support all Unicode characters, so which you use depends on the system you need to fit into.Essentially all Internet applications (e.g., browsers and email) rely on one or more of these encodings.UTF-8 is a variable-width encoding: common characters fit into 1 byte, less frequently usedcharacters (by some estimate of use) into 2 bytes, and rarer characters into 3 or 4 bytes. In particular, the ASCII characters fit into 1 byte with the same encodings (integer values) in UTF-8 as inASCII. The various Latin alphabets, Greek, Cyrillic, Hebrew, Arabic, and more fit into 2 bytes.A UTF-8 string is terminated by '\0', a UTF-16 string by u'\0', and a UTF-32 string by U'\0'.We can represent an ordinary English character string in a variety of ways.

Consider a filename using a backslash as the separator:"folder\\file"R"(folder\file)"u8"folder\\file"u8R"(folder\file)"u"folder\\file"uR"(folder\file)"U"folder\\file"UR"(folder\file)"// implementation character set string// implementation character raw set string// UTF-8 string// UTF-8 raw string// UTF-16 string// UTF-16 raw string// UTF-32 string// UTF-32 raw stringIf printed, these strings will all look the same, but except for the ‘‘plain’’ and UTF-8 strings theirinternal representations are likely to differ.Obviously, the real purpose of Unicode strings is to be able to put Unicode characters into them.For example:u8"The official vowels in Danish are: a, e, i, o, u, \u00E6, \u00F8, \u00E5 and y."Printing that string appropriately gives youThe official vowels in Danish are: a, e, i, o, u, æ, ø, å and y.The hexadecimal number after the \u is a Unicode code point (§iso.2.14.3) [Unicode,1996].

Such acode point is independent of the encoding used and will in fact have different representations (asbits in bytes) in different encodings. For example, u'0430' (Cyrillic lowercase letter ‘‘a’’) is the2-byte hexadecimal value D0B0 in UTF-8, the 2-byte hexadecimal value 0403 in UTF-16, and the4-byte hexadecimal value 00000403 in UTF-32. These hexadecimal values are referred to as universal character names.The order of the us and Rs and their cases are significant: RU and Ur are not valid string prefixes.7.4 Pointers into ArraysIn C++, pointers and arrays are closely related. The name of an array can be used as a pointer to itsinitial element.

For example:180Pointers, Arrays, and ReferencesChapter 7int v[] = { 1, 2, 3, 4 };int∗ p1 = v;// pointer to initial element (implicit conversion)int∗ p2 = &v[0];// pointer to initial elementint∗ p3 = v+4;// pointer to one-beyond-last elementor graphically:p1v:p2123p34Taking a pointer to the element one beyond the end of an array is guaranteed to work.

This isimportant for many algorithms (§4.5, §33.1). However, since such a pointer does not in fact pointto an element of the array, it may not be used for reading or writing. The result of taking theaddress of the element before the initial element or beyond one-past-the-last element is undefinedand should be avoided. For example:int∗ p4 = v−1; // before the beginning, undefined: don’t do itint∗ p5 = v+7; // beyond the end, undefined: don’t do itThe implicit conversion of an array name to a pointer to the initial element of the array is extensively used in function calls in C-style code.

For example:extern "C" int strlen(const char∗);// from <string.h>void f(){char v[] = "Annemarie";char∗ p = v;// implicit conversion of char[] to char*strlen(p);strlen(v);// implicit conversion of char[] to char*v = p;// error: cannot assign to array}The same value is passed to the standard-library function strlen() in both calls. The snag is that it isimpossible to avoid the implicit conversion. In other words, there is no way of declaring a functionso that the array v is copied when the function is called.

Fortunately, there is no implicit or explicitconversion from a pointer to an array.The implicit conversion of the array argument to a pointer means that the size of the array is lostto the called function. However, the called function must somehow determine the size to perform ameaningful operation. Like other C standard-library functions taking pointers to characters, strlen()relies on zero to indicate end-of-string; strlen(p) returns the number of characters up to and notincluding the terminating 0.

This is all pretty low-level. The standard-library vector (§4.4.1, §13.6,§31.4), array (§8.2.4, §34.2.1), and string (§4.2) don’t suffer from this problem. These library typesgive their number of elements as their size() without having to count elements each time.Section 7.4.1Navigating Arrays1817.4.1 Navigating ArraysEfficient and elegant access to arrays (and similar data structures) is the key to many algorithms(see §4.5, Chapter 32). Access can be achieved either through a pointer to an array plus an index orthrough a pointer to an element. For example:void fi(char v[]){for (int i = 0; v[i]!=0; ++i)use(v[i]);}void fp(char v[]){for (char∗ p = v; ∗p!=0; ++p)use(∗p);}The prefix ∗ operator dereferences a pointer so that ∗p is the character pointed to by p, and ++ increments the pointer so that it refers to the next element of the array.There is no inherent reason why one version should be faster than the other.

With modern compilers, identical code should be (and usually is) generated for both examples. Programmers canchoose between the versions on logical and aesthetic grounds.Subscripting a built-in array is defined in terms of the pointer operations + and ∗. For everybuilt-in array a and integer j within the range of a, we have:a[j] == ∗(&a[0]+j) == ∗(a+j) == ∗(j+a) == j[a]It usually surprises people to find that a[j]==j[a]. For example, 3["Texas"]=="Texas"[3]=='a'. Suchcleverness has no place in production code. These equivalences are pretty low-level and do nothold for standard-library containers, such as array and vector.The result of applying the arithmetic operators +, −, ++, or −− to pointers depends on the type ofthe object pointed to.

When an arithmetic operator is applied to a pointer p of type T∗, p is assumedto point to an element of an array of objects of type T; p+1 points to the next element of that array,and p−1 points to the previous element. This implies that the integer value of p+1 will be sizeof(T)larger than the integer value of p. For example:template<typename T>int byte_diff(T∗ p, T∗ q){return reinterpret_cast<char∗>(q)−reinterpret_cast<char∗>(p);}void diff_test(){int vi[10];short vs[10];182Pointers, Arrays, and ReferencesChapter 7cout << vi << ' ' << &vi[1] << ' ' << &vi[1]−&vi[0] << ' ' << byte_diff(&vi[0],&vi[1]) << '\n';cout << vs << ' ' << &vs[1] << ' ' << &vs[1]−&vs[0] << ' ' << byte_diff(&vs[0],&vs[1]) << '\n';}This produced:0x7fffaef0 0x7fffaef4 1 40x7fffaedc 0x7fffaede 1 2The pointer values were printed using the default hexadecimal notation.

This shows that on myimplementation, sizeof(short) is 2 and sizeof(int) is 4.Subtraction of pointers is defined only when both pointers point to elements of the same array(although the language has no fast way of ensuring that is the case). When subtracting a pointer pfrom another pointer q, q−p, the result is the number of array elements in the sequence [p:q) (aninteger).

One can add an integer to a pointer or subtract an integer from a pointer; in both cases, theresult is a pointer value. If that value does not point to an element of the same array as the originalpointer or one beyond, the result of using that value is undefined.

For example:void f(){int v1[10];int v2[10];int i1 = &v1[5]−&v1[3];int i2 = &v1[5]−&v2[3];// i1 = 2// result undefinedint∗ p1 = v2+2;int∗ p2 = v2−2;// p1 = &v2[2]// *p2 undefined}Complicated pointer arithmetic is usually unnecessary and best avoided. Addition of pointersmakes no sense and is not allowed.Arrays are not self-describing because the number of elements of an array is not guaranteed tobe stored with the array.

This implies that to traverse an array that does not contain a terminator theway C-style strings do, we must somehow supply the number of elements. For example:void fp(char v[], int size){for (int i=0; i!=size; ++i)use(v[i]);for (int x : v)use(x);const int N = 7;char v2[N];for (int i=0; i!=N; ++i)use(v2[i]);for (int x : v2)use(x);}// hope that v has at least size elements// error : range-for does not work for pointers// range-for works for arrays of known sizeSection 7.4.1Navigating Arrays183This array concept is inherently low-level.

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

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

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

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