рефераты конспекты курсовые дипломные лекции шпоры

Реферат Курсовая Конспект

Strings

Strings - раздел Философия, Data Structures and Algorithms in C++ В C ++, Тип Данных String Обеспечивает Необходимую Абстракцию, Чтобы Позволит...

В C ++, тип данных string обеспечивает необходимую абстракцию, чтобы позволить программистам работать со строками символов. В Java фактически образуют два отдельных класса.

В отличие от Java, C++ string тип не доступен для всех программ по умолчанию. Если C++ программа требует string тип, программист должен обратиться к библиотеке, которая определяет этот тип. Следующая распечатка иллюстрирует C ++ тип данных последовательности в действии.

 

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: #include <iostream>#include <string>#include <cstdlib> using namespace std; int main(int argc, char* argv[]) { string s1 = "first"; // Initialization string s2; s1 += " string"; // Concatenation s2 = s1; // Assignment cout << s1 << endl; // Stream output cout << s1.length() << endl; // Length return EXIT_SUCCESS;}Listing 3 string variables in use

 

The inclusion of the preprocessor directive found in line 2 in the above listing is necessary to allow the program access to the string data type. Notice also the various methods and functionality of the string variables that the example demonstrates. In line 9, a string literal initializes a string object. Lines 11 and 12 demonstrate concatenation and assignment. To display the contents of a string variable, we can use basic console output as shown in line 14. This listing demonstrates only some basic functionality of the string data type. Many other useful functions exist. Arrays C++ provides basic support for a sequence of homogeneous data objects through arrays. Both similarities and differences exist between Java arrays and arrays in C++. In Java, we can declare and initialize an array of ten ints using the following.
1: 2: 3: // declare and create two arrays of integersint[] javaArray1 = new int[10];int javaArray2[] = new int[10];
Listing 4 Arrays in Java

The C++ syntax equivalent to the above Java code looks similar, except for the use of the keyword new. The keyword new, in Java, creates an instance of an object. In C++, the keyword new has a different meaning, one that we address in 1.4.3 Dynamic Memory Management. The following listing demonstrates the declaration of an int array of size ten in C++.

1: 2: // declare and create an array of integersint cpp_array[10];
Listing 5 An array in C++

The double bracket ([]) in the declaration indicates that the line declares an array. Notice the placement of the double bracket ([]) in each of the examples. In Java, the double bracket can be placed after the name of the data type or after the name of the variable. In C++, it can only be placed after the name of the variable.

Accessing the elements stored in an array is done the same way in C++ as it is in Java. Both languages use the bracket operator ([]). A programmer encloses in brackets an index number of the element they wish to access. Indexing of arrays in C++, as in Java, begins with zero. This means that the first element of an array is accessed at index 0, the second element at index 1, the third element at index 2, and so on. The following listing demonstrates accessing the elements of a C++ array.

Включение директивы препроцессора, в линии 2, необходимо, чтобы позволить доступ программы к string data type. Заметьте также различные методы и функциональные возможности string переменных в примере. По линии 9, string инициализирует string объект. Линии 11 и 12 демонстрируют связь и назначение. Чтобы показать содержание переменной последовательности, мы можем использовать как показано в линии 14. Существуют много других полезных функций. Arrays C++ позволяет последовательностям гомогенных объектов данных выражать через массивы. И общие черты и различия существуют между Java массивами и массивами в C++. Сначала давайте рассмотрим синтаксис для объявления и инициализации массивов. В Java это можно сделать так:
1: 2: 3: // declare and create two arrays of integersint[] javaArray1 = new int[10];int javaArray2[] = new int[10];
Listing 4 Arrays in Java

C++ синтаксис, эквивалентный Java, за исключением использования нового ключевого слова. Новое ключевое слово, в Java, создает объект. В C++, у нового ключевого слова может быть различное значение см. 1.4.3 Dynamic Memory Management. Следующая распечатка демонстрирует объявление массива int в C++.

1: 2: // declare and create an array of integersint cpp_array[10];
Listing 5 An array in C++

Двойная скобка ([]) указывает, что в строке объявляется массив. Заметьте размещение двойной скобки ([]) в каждом из примеров. В Java двойная скобка может быть помещена после названия типа данных или после названия переменной. В C++, это может быть помещено только после названия переменной.

Обращение к элементам сохраненных в массиве, в C++ осуществляется аналогично, как и в Java. Оба языка используют оператор двойной скобки ([]). Программист записывает в скобках индекс элемента, означающий величину массива. Индексация массива в C ++, как в Java, начинается с нуля. Это означает, что первый элемент массива всегда имеет индекс 0, второй элемент индекс 1, третий элемент индекс 2, и так далее. Следующая распечатка демонстрирует вызов к элементам массива в C++.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: #include <iostream>#include <cstdlib> using namespace std; int main(int argc, char* argv[]) { int arr[25]; for (int i = 0; i < 25; i++) { arr[i] = i; } cout << "The first element equals: " << arr[0] << endl; cout << "The second element equals: " << arr[1] << endl; cout << "The last element equals: " << arr[24] << endl; return EXIT_SUCCESS;}Listing 6 Accessing elements of a C++ array

 

One inherent danger that exists in using C++ arrays is the lack of bounds checking. This is not the case in C++, since boundary checking of arrays is not supported. If we have an array of ten elements in C++, we can attempt to access the 12th, or 20th, or even 100th index of the array. Depending on a few different things, the program may or may not "crash" as a result of our out-of-bounds access. We can be sure, however, that the data we obtain from an out of bounds access will not be meaningful. The following listing shows an out-of-bounds array access in C++.

1: 2: int arr[10];cout << arr[11] << endl;
Listing 7 Out of bounds access

The code in the above listing, in the context of an actual C++ program, definitely compiles, and it may even run without error. This is clearly a dangerous practice, and one that we will always avoid.

– Конец работы –

Эта тема принадлежит разделу:

Data Structures and Algorithms in C++

Compiling and Running a C Program C Background History C is a modern object oriented programming language that supports... Table Different problems with similar solutions Each of the problems... Vectors...

Если Вам нужно дополнительный материал на эту тему, или Вы не нашли то, что искали, рекомендуем воспользоваться поиском по нашей базе работ: Strings

Что будем делать с полученным материалом:

Если этот материал оказался полезным ля Вас, Вы можете сохранить его на свою страничку в социальных сетях:

Все темы данного раздела:

Assessments
· Multiple-Choice Quiz 1 Recommended Exercise 1 1.3.1 Data Types Fundamental Data Types As in most other programming languages including Java, C+

Strings
In C++, the string data type provides the necessary abstraction to allow C++ programmers to work with character strings. The Java counterpart is actually two separate classes. Unlike its J

Creating New Data Type Names
It is possible in C++ for a programmer to create additional names for existing data types. Creating another name uses the keyword typedef. The syntax to create a new name is as follows. typed

Создание новых имен типов данных.
В C++ есть возможность создать дополнительно к существующим собственные типы данных с новым именем. Для этого необходимо использовать ключевое слово typedef. Синтаксис, чтобы создать новое имя след

Constructors
Constructors are the methods of a class that define what actions to take when creating an object. A C++ class can have multiple constructors. This allows variation in object instantiation since dif

The Destructor
A destructor is a special member function of a C++ class called when an object's lifetime ends. Like a copy constructor, only one destructor can exist for a class. Since they execute when an object

Declaration vs. Definition
In this discussion on the specification of classes in C++, the term "definition" has been used regarding functions. When we "define" a function, we dictate the function's behavi

Basic Syntax
Класс - основная единица абстракции в C++. Давайте сначала рассмотрим простой класс, определенный в Java, и затем соответствующую версию в C++. ………………………………………………………………………………… Сле

Constructors
Конструктор создает и инициализирует новый экземпляр класса. В C++ класс может иметь несколько конструкторов. Это позволяет вносить изменение в экземпляры класса включая типы параметров и значения,

Declaration vs. Definition
В обсуждении о спецификации классов, термин "definition" ("определение") был использован относительно функции. Когда мы "definition" функцию, мы определяем поведение ф

Streams
Input and output in C++ is based on the concept of a stream. A stream is a sequence of bytes that flow from something to something else. The process of output involves moving bytes, one at a time,

Using the Standard Streams
Three specific streams are always available throughout the lifetime of every C++ program. These are the standard input, standard output, and standard error streams. Each of these standard streams h

File Input and Output
File based input and output is similar to the mechanisms for keyboard and screen I/O. The main difference is that programmers must explicitly open and close files. In pseudocode, a generic program

Some Common Pitfalls
  A common mistake for many new C++ programmers is to reverse the << and >> operators. A good way to remember which operator to use is to think of them as arrows. You alwa

Streams
Ввод и вывод в C ++ основан на понятии потока. Поток - последовательность байтов, которые вытекают из одного в другое. Процесс продукции вовлекает байты, по одному, с программы на устройство. Это у

Using the Standard Streams
Три определенных потока всегда доступны всюду в C ++ программах. Это standard input, standard output, and standard error потоки. У каждого из этих стандартных потоков есть определенное использовани

File Input and Output
Файл вход и выход подобен механизмам для ввода / вывода экрана и клавиатуры. Главное различие - то, что программисты должны явно открыть и закрыть файлы. В псевдокоде главная программа, которая чит

Some Common Pitfalls
Частая ошибка для многих новых C ++ программисты состоит в том, чтобы полностью изменить << и >> операторы. Хороший способ помнить, какой оператор использовать должен думать о них как о

Text Substitution
The preprocessor is a tool that C++ programmers use to manipulate the contents of source code files prior to compilation. In the most general sense, the preprocessor performs text substitution and

File Inclusion
File inclusion is a feature of the C++ preprocessor that allows a source code file to use shared code. We consider shared code to be classes or functions declared in other files. In C++, we can onl

Macro Substitution
The C++ preprocessor can perform a programmer defined text substitution throughout an entire source code file. This is known as macro substitution. Programmers define a macro using the #define prep

Conditional Compilation
Beyond macro substitution, a more important reason to use #define is to support conditional compilation. Using #define, and some other preprocessor directives, we can instruct the compiler to compi

An Example: Assumption Verification
Verifying assumptions using assertions is an example of a common use of the preprocessor and its features. An assertion is a statement placed in source code to verify an assumption. Usually, progra

Text Substitution
Препроцессор это инструмент, чтобы управлять содержанием файлов исходного текста до компиляции. В самом общем смысле препроцессор выполняет текстовую замену и текстовую модификацию. Высокоуровневые

File Inclusion
Включение файла - особенность C++ препроцессор, который позволяет файлу исходного текста использовать разделенные коды. Мы полагаем, что разделенный код это классы или функции, объявленные в других

Macro Substitution
C++ препроцессор может определить текстовую замену всюду по всему файлу исходного текста. Это известно как макро-замена. Программисты реализуют макро-замену директивой #define препроцессора, котора

Conditional Compilation
Вне макро-замены важная причина использовать #define состоит в том, чтобы поддержать условную трансляцию. Используя #define, и некоторые другие директивы препроцессора, мы можем проинструктировать

An Example: Assumption Verification
Подтверждение предположений, используя утверждения является примером обычного использования препроцессора и его особенностей. assertion - утверждение, помещенное в исходный текст, чтобы проверить п

Хотите получать на электронную почту самые свежие новости?
Education Insider Sample
Подпишитесь на Нашу рассылку
Наша политика приватности обеспечивает 100% безопасность и анонимность Ваших E-Mail
Реклама
Соответствующий теме материал
  • Похожее
  • Популярное
  • Облако тегов
  • Здесь
  • Временно
  • Пусто
Теги