Category Archives: Libraries C ++

Working with localized strings




first, you need to be able to do with the localized strings - a record character constants broad localized characters and distinguish them from conventional lines char[]. For this line is written to the prior s qualifier L:

The result will be:

Pay attention, the string length (number characters) in this case, clearly less, than the number bytes allocated for the string (your operating system, their attitude may be different from, I show in Linux, but it does not affect the programming technique).

In such a line near with equal success may be symbols of diverse nature: different languages, special mathematical symbols, common in theirske designation of the Greek alphabet (a, e, i, Fr., p, l, Phi, Oh ...), musical notes, etc.. How are you, obviously, know, just as well as a part of wide character strings, with equal success, and can meet the characters of the Latin alphabet (ASCII main table), with each such symbol will also hold 2 or 4 bytes (depending on the agreements adopted in the operating system), in contrast to the usual 1 bytes.

We perform a number of operations with the Russian lines, but writing them (till) in traditional form arrays char:

perform:

It would seem, what (nearly) everything is working precisely a textbook, and why do we need any extensive localized strings? But this deceptive illusion! The point here is, that some traditional functions lowercase (strcat(), strcpy(), strdup(), strstr() and etc.) will return the correct results. This is because they perform operations on bytes, byte by byte, without delving into the internal structure of characters to copy.

But other operations (and false результат strlen() it has clearly points) will not work properly: strncpy(), strchr(), strsep(), strtok() and etc. And they will create you a very unexpected results, very difficult to interpret. Lookthey how to work byte string Reverse, and how to distinguish his work on the English and Russian line:

It works so, and this definitely not that, what you expected to receive:

nand this concludes our discussion of the possibility of representing the Russian-speaking lines of traditional arrays char[] and the processing of their traditional functions in lower case, and complete this examination output: _y to earn with Russian lines as an array char шt is possible only:

and). or when we use string constants unchanged, only as a line for their input-output unchanged;

b). or for the treatment of their functions (library or their own), which do not take into account the internal structure of the characters, without delving into the is contentit is strings, and operate with them simply as a meaningless sequence of bytes.

In all Otherwise correctI work with the Cyrillic alphabet available only as a broad array of localized characters wchar_t (with completingm row wide null symbol L’′). To work with localized representation of lines of C library provides wide a set of line features, completely similar to the traditional functions of the lower case, but instead of the prefix str in their names prefixed with wcs: wcslen() instead strlen(), wcsncpy() instead strncpy() etc.

Let's see how it works on the example of:

This illustration is quite enough, to see direct analogies manipulation functions with symbols wchar_t. the, who has some experience working with strings char effortlessly spread it wide strings. Setting language locale (call setlocale()) O devices (terminal) obligatory, because the C / C ++ program sets the default locale “C” (andto historically), which allows output only 128 characters younger half of the 8-bit ASCII characters.

In the illustrated writing function sets the locale, used in the default operating system - I'm guessing, that we are experimenting in the Russian-speaking the installed system. The new language standard (C99) and introduces a new format for the string formatting functions (printf(), sprintf()) %ls, This format strings wchar_t[].

Tinternally as well, As with arrays char, converts to C ++ from C, C ++ library introduces a complete analogue of the container class string, but containing in their composition wide localized characters, and is known as the class wstring:

Here, the output string of localized characters (ws) must is output to the output stream wcout (similar in meaning cout, but other than cout).

In the illustrated writing: locale::global( locale( “” ) )This locale setting by default in C ++ OOP way, similar to, as it has been shown before in the manner of C.

Atpolls IO wide character strings (to the terminal or to a file) separate complicated subject, therefore consideration will be deferred to a single note on this subject.

Newsletter of programming:

Working with files in C ++. Part 2 – Библиотека fstream.




class ofstream

Back class ifstream, which we reviewed earlier, and is designed to write to a file.

As in ifstream, to open or create a file using a constructor or method open().

or designer:

Parameter ios_base::app indicated, if you want to append to the end of an existing file. For example when the program keeps a log of their work

For checking a file open meets all the same is_open()

The principle is the same. You can check whether a file is opened, using in logical expression very variable file:

Statement <<

Forwards the formatted output to a file. The principle is the same, that of the analog in iostream.

It is intended to be displayed in text files. Controlled formatting operations such as width() or setf(). Their counterparts are fully methods of the same name iostream.

The sequence of output variables as indicated from left to right: The first variable will be output, listed closest to fillet, then following it.

operator endl

Similarly, the operator of iostream manufactures transfer record of the carriage to a new line in a text file.

method write

It used in binary files for writing the memory block (byte array) in the file as they are. Any variable is also a array bytes, rather it can be seen as. Accordingly, this method writes to the file its machine representation (the kind of the way it looks in the memory).

This method takes two parameters: Pointer to a block of data and the number of bytes, that this unit takes. In the example, the string takes strlen() bytes, whole sizeof() (which will give 4 32-bit integer and for OSes 8 for real).

Once again I should emphasize the, that unlike the formatted output operator <<, method write() It does not display data in text form.

method close

Closes file method close(). for files, writable, as opposed to reading files, closing a file – mandatory ritual. Unclosed file can not obtain the data. This effect can occur due to the buffering itself OSes, when data, discharged into the file, They are stored in fact in mind and just do not come to a file. The operating system itself decides, when the data is time to merge.

Such “deferred” plums called “commit” (from the Latin commit). By the way this effect very well use a database management system, where to insert records fall into the storage memory (called transaction). It was only after a special command en masse written to the database file itself. Method close() just an example of a team closing a transaction with the file.

It is worth mentioning just in case, that if you want to commit to produce data without closing the file itself, you need to use the method flush()

These deposits will go on the record in the file, but it will still be open for entries. This method is not often used, but useful to know about it.

width formatting methods, precision

As in iostream, for the beautiful layout of data in data formatting file can be used to display operator << .

width() indicates the width in characters, which will be laid in the displayed value, and precision() the number of digits of the fractional part of a real. The simplest example: output table to a text file the values ​​of the trigonometric functions:

 

positioning methods seekp, tellp

To move a file as in the case of ifstream There is a function of the position of the permutation. it is called seekp() and receives the same parameters as described above for seekg().

To get the current position of a similar feature in bytes from the beginning of the file tellp().

Videos about working with files in C ++:

Newsletter of programming:

Working with files in C ++. Part 1 – Библиотека fstream.




header fstream It provides the functionality to read data from a file and write to the file. In general, it is very similar to the header iostream, who works with the console, because the console is also a file. Therefore, all the basic operations are the same, for small differences, as in the previous topic on iostream.

The most frequent operations following:

  1. Operators Redirection O – << and >>
  2. Methods of recording and reading rows getline() and get() c put()
  3. Streaming read and write methods write() and read()
  4. Public method creation and closing files open() and close()
  5. The methods of verification whether the file is opened is_open() and whether the file end is reached eof()
  6. Setting the formatted output for >> through width() and precision()
  7. positioning operation tellg(), tellp() and seekg(), seekp()

It's not all possibilities, which provides library fstream. Consider all now we do not, since their range of application is narrow enough. Acquainted with the above. Start by reading the class.

class ifstream

It provides opportunities to read files. Open the file in two ways: calling method open() or by entering the path to it in the constructor. You need to prepare a text file, before, start typing the code. On the disc d, create a folder named 1 and in it, create a file with the extension txt – “файл.txt”.

Opening a file in the constructor looks like this:

So we ask to open a file named file.txt txt, which is in the folder with the name 1, and the folder is on drive d.

Using the open method() conveniently, if the programmer does not want to be tied directly to a file. Suddenly you need a class property or global variable, well, then open the file already. If you need to open a file within a certain function, to work with him and to close, you can set the path to the file directly in the constructor. In general, depending on the situation.

opening file, desirable to prescribe by: if he opened? Since there are a number of reasons, on which the file can not be opened, and we do not see. For example, file with the specified name is not in the prescribed folder or path is not valid. You can go two ways: check the file in a variable logical expression (applying the operator “!”, for example) or to use the method is_open() :

So everything will work fine and the file will open:

библиотека fstream, work with files in c ++, Programming for beginnersNow try to enter the name of the folder is not 1, and 2 ifstream file ("d:\\<span style="color: #ff0000;"><strong>2</strong>\\файл.txt”); and restart the program. Since the specified folder name, we did not create, then the file, naturally, It can not be opened:

библиотека fstream, work with files in c ++, Programming for beginners

The second embodiment checks using the method is_open() :

Method is_open() return 1, If the file is found and successfully opened. otherwise returns 0 and work code prescribed in the block else.

If the file is not open – desirable to handle the error. Usually, if all of the work program associated with the file they write a certain message to the console, and put out of the program. When serious errors common to return a code execution (number), which will characterize one or another mistake. The codes for each type of error the author of the program can invent their own. One of the ways to handle errors in the program, we have considered in the article Exceptions in c++.

If the file is opened successfully, from it you can read.

read the operator >>

As well as in iostream Reading can be arranged by the operator >>, that indicates in which variable will be made to read:

considers real, string and integer. row readout end, if there was a space or end of line. It is worth noting, that the operator >> It applied to text files. Reading from a binary file to make the best using the method read().

By the way, this statement is quite convenient, if the task is to split the file into words:

Methods getline() и get()

Reading the character string to the translation of the carriage is made the same as in iostream by getline(). Moreover, it is recommended to use the overloaded version of the function, if you read a line of type string:

If you need to read in an array of characters char[], either get() or getline() just as the methods:

The principle is generally the same, as in the analogs of iostream: Shown as a parameter buffer (variable, where the reading will be done), or rather a pointer to a block of memory (if the variable is declared statically: char buffer[255] for example, it is written in the parameters &buffer), specifies the maximum number of readable (in this example n), so as not to overflow has occurred and the output of the buffer limits and the separator character as required, to which will Proofreading (in this example the gap). I hope I did not hurt tread on the trunk fanatics C, if the soot that these two functions on 99% interchangeable, and 95% They may be replaced by read().

Method read()

Similar to the previous example?

Actually here the same result – It is considered to be a specified number of characters. The exception only, it is impossible to specify the delimiter. read() used for unformatted input. It is intended primarily to read binary files. Since the text file – a special case of a binary, this method is quite applicable to the text file.

Method close()

closes the file. Even nothing to add. Perhaps the only remark – on, that the file, opened for reading, will not be closed by this method usually does not become worse. Very rare situation, when opened for reading deteriorates file, if you complete the program without closing the file. This damage is associated primarily with non-standard devices such as tape drives Tape or what some artful stream of industrial controllers, but in Feng Shui to remember – open file should be closed. It is considered good form.

Method eof()

Checks whether the file end is reached. That is. whether it is possible from it to continue reading. The above example of the proofreading word operator >> just use this check.

Method seekg()

Installs the current position to the desired, indicates the number. This method is also transmitted positioning method:

  • ios_base::end – Read off a new position at the end of the file
  • ios_base::beg – Read off a new position from the beginning of the file (absolute positioning)
  • ios_base::cur – Jump to n bytes from the current position in the file (по умолчанию)

Method tellg()

Sometimes you need to get information about, as already read. This method will help tellg():

It returns a value of type int, which shows how much has already passed in bytes. It can be used in tandem with the method seekg(), To get the file size:

As an example of the binary reading methods can be dismantled so class:

Similar wrapper classes useful, if there are problems reading from a binary whole structure.

Videos about working with files in C ++:

Newsletter of programming:

sqrt() - Cmath function library




sqrt( value );

The function sqrt() cmath library (math.h) It takes the value parameter and returns the square root.

If the ( in our case – value) negative, an error.

The result is shown in the run online compiler ideone

example of the function sqrt c ++

Newsletter of programming:

pow() - Cmath function library




pow(a, b);

Функция pow() cmath library takes two parameters: a, b. The first number is a (basic) raised to the power b.

Returns the value of ab .

Execution result 23 , 53, 52 :

pow () - function of cmath library

 

Newsletter of programming:

fma () – function of cmath library




fma(a, b, c);

Function fma() of cmath library accepts three parameters: a, b – ​​for multiplying this values , c – to add value.

Returns the value of a * b + c.

Execution result ( 2 * 2 + 3):

fma () - function of cmath library

Newsletter of programming:

Pointers in containers. STL (part 16)




Indices in containers, STL, Programming for beginners

STL containers significantly reduce the complexity of writing code, working with dynamic data structures and, the most important thing, increase its inerrancy. But in some cases, when working with large data items in containers, This technique can produce the inevitable loss of productivity. This is because, that since the operation room a container element, and subsequent displacement elements may require a copy of elements.

Note: The severity of these effects depends on the type of container, and from the transactions. For example, interchange operation 2 elements in the sorting require 3 copyings type container vector and will not require additional copy for container list. But the operation of the initial space in the container (push_back(), insert() and etc.) always make a copy.

This can be a problem for an application, when operations on the containers is critical for runtime (or seem to you such). There are even more complicated cases, when a class container object is not picked up operation, or when the objects are referenced objects themselves, full backups for which you want to perform recursive procedures following all the links (then, in Python, and the other is called a deep copy).

Everything works well, as before - sort a set of records on arbitrary fields and in any order:

16-1

(Note, that completing this application you need for Ctrl + D - End Of File ... in the Widows, probably, по Ctrl + Z.)

But! ... Especially debugging "traces" positives were left constructors and destructors records, and recording constructed 8 times, and the destructor is only triggered 4, for local array at the exit point of the block. Local array generally not of interest to us. He was introduced to simplify the example, only as a set of initialization values. But for the record, placed in a container, records destruction does not occur, and we get a candid memory leak. But worse, after we remove the item from the container (without taking further action), we can not delete the record, calling for it delete. This is because, after call erase() We lost to a record only path through the iterator (the code shows a loop erase(), so graphically, that is equivalent to clear(), the effect of which, It is the same).

Conclusion, which can be made from Example, looks like that:

  • placing objects in containers not, and Indices on them, can significantly reduce the computational cost of the manipulation (but always principled whether these gains at the current computing power?).

  • replacement facilities pointers in containers makes the code is much more dangerous in the sense of hidden subtle bugs, And such a serious level, which can further lead to an application crash.

Here some help may have smart pointers of the latest C ++ standard (shared_ptr or weak_ptr, but not unique_ptr and not the good old and problematic auto_ptr), us for this in the previous code, just change 4 strings:

In Windows, shared_ptr needed #include <memory> , and in other systems, not necessarily.

And application behavior change significantly:

16-2

But we should not delude ourselves recklessly, so as smart pointers, removing some, generate other potential concerns (such as cyclic links etc.. about which much is written enough).

Newsletter of programming:

Adapters. STL (part 15)




stack, programming for beginners

A separate category of standard template library are adapters. Adapters - this is not a new concept or implementation, and the adaptation of existing concepts library for specific, commonly used target. Often this is done through the adaptation restrictions the functionality of the basic concepts for the adapter requests. The library presents the container adapter, iterators and functions.

The easiest way to show, both appear adapters example containers adapters: stack (stack), queue (queue), priority_queue (priority queue). Already it is clear from their listings, what:

  • It is widely and commonly used data structures;

  • They do not need any separate implementation. To ensure their functionality can be used (adapt) as base any from STL standard containers, which provides operations such as push_back, pop_back or pop_front (depending on the type of adapter);

  • The "extra" transaction in the arsenal of the base container should be excluded adapter (not to create such temptations ..., indexing operation, if the vector is used to adapt the stack);

And, instead of cumbersome template syntax definitions (header files <stack>, <queue> and t. P.), Refer to the example…

Let's start from the stack: characterized in stack, that access its elements can only be from one end, called the top of the stack. This is a collection of data, functioning on the principle of LIFO (Last In — First Out). Here's a simple example reveals little all stack functionality:

Let us analyze the code and make some conclusions:

  • first definition stack<string> (we do not use it on) declares a variable stack, whose elements are strings. Please note, what string objects are themselves STL containers. In this way, stack can contain elements of any nesting containers (which is characteristic of, and any other STL containers).

  • This definition ( stack<string> ) you can see, a stack description in the majority of examples. Many authors are unaware, that may be different. But we will use a different definition: stack< string, vector<string> > - A stack of strings (largely equivalent to the previous), but built on the base class vector<string>. As base can be used, for example, vector, list and and, or even your own container class, expanding base. Default (since 1st determining) used deque base. Sometimes people ask: why not write (defined as in the implementation of the stack): stack< vector<string> > (removing duplicate string)? Because (and it is quite possible) This description is an entirely different type: stack vectors strings (cm. above remark on the structural nesting containers).

  • Then follows initialization initial state vector of strings. Mark, that such a trick is only valid in C ++ 11 standard.

  • Next we see almost all operations (methods), required from the stack: push() – pushing of an object on the stack, top() – obtaining a reference to an element in the top of the stack, pop() – ejection of the upper member, size() – the current size of the stack, empty() – on the void check.

  • It is easy to understand, adapter stack lost inherent base container methods (at(), [ ] and etc.), but acquired (redefinition) own (push(), pop()).

Now let's see what came of it:

stack, programming for beginners

Having dealt with a stack of elementary Now just move the analogy to all. In contrast to stack – is a collection of data, functioning according to the FIFO principle (First In — First Out). (It is such a "pipe", one end of which something flows, and then from the other end follows.)

Special leave for example the queue is almost unchanged, making changes, required language semantics:

From us demanded change:

  • The line can not be built on the base vector container that does not have a method pop_front(), but may be based on the list, and, or any other container, implements a basic set of methods (front(), push_back(), pop_front()), by default and.

  • There is no method queue adapter top(), and a method similar import front().

And as a result we get (compare the results for the stack!):

stack, programming for beginners

Newsletter of programming:

Generalized numerical algorithms. STL (part 14)




Generalized numerical algorithms STL c ++The next, very necessary and very powerful group algorithms STL are generalized numerical algorithms (header <numeric>). This is not some kind of special computational methods, as one might think based on the name. It algorithms, allow to use the well-known library or their own computing activities to the totality of the container elements. And because so, then they are called like all other algorithms STL. Used algorithms are generalized, mainly in mathematical calculations with respect to the containers, contains numeric elements. But this does not necessarily. And if you are not interested in the numerical calculation (for example from the field of digital signal processing), then you can just safely skip this part of the presentation…

STL's list presented generalized numerical algorithms: iota (the creation of a monotonically increasing sequence), accumulate (accumulation), inner_product (scalar multiplying the product), partial_sum (partial sum), adjacent_difference (adjacent difference).

Illustration works best to hold on to the used and intuitive algorithm accumulate. This algorithm reduces (reduces the dimension) container with the accumulation values. In particular, for simple numerical values, he turns vector<> or list<> to a single scalar result value.

Algorithm accumulate (how, however, most other) It has 2 syntactic forms:

In the 1st form (it is less interesting) algorithm summarizes the the value of the container elements. Do not forget at the same time, such that string, for example, operation ‘+‘ It means concatenation, gluing). In the 2nd form the algorithm collects the result of a binary operation (function of 2 variables), used to accumulate value (battery) and in turn to each of the container element.

Unclear? This powerful technique, and now everything will be clear from the example…

In mathematical statistics are used several types of average values ​​for the numerical sequence:

  • Average:

    SA1

  • geometric mean:

    sg2

  • harmonic mean:

    sr3

  • The average quadratic:

    sq4

We will not delve into the meaning of each option. We will make an application, which calculates the average and some more characteristics (dispersion, standard deviation) to input a numerical sequence. The input serial input or a terminal, or redirection of pre-prepared data file:

It is easy to see, each of complex mathematical formulas written above is calculated only on one string, using the technique of generalized algorithms:

Generalized numerical algorithms in stl c ++

Here we can see the well-known relation, which confirms the correctness of our calculations. It consists in the fact, that for any sequence of numbers arithmetic mean is greater than or equal to the geometric mean, which, in its turn, greater than or equal to the harmonic mean. And equality in these statements can only be achieved if all members of a sequence of numbers are equal:

Generalized numerical algorithms in stl c ++

We return to the study of the code. The first call of the algorithm accumulate( b, e, 0. ) It shows the 1st form of use: container values ​​are added to the initial value 0.0.

A warning!: Record points to the constant initial value, indicating, what is it real value - fundamentally important. Without this code will compile even without warnings, but done with completely incorrect and extremely difficult under interpretation results! This is because, algorithms that are defined as template, and the type of third parameter determines the accumulation of internal operations will be used for any type of data.

Other (4 pieces) challenges accumulate() use the 2nd form of call – 4th transmit parameter function accumulation. As seen from the examples, it takes the current parameters of the accumulated value and the next element in the container. And returns the accumulating operation. For clarity, accumulating all functions are written in the example of a simple and clear form. On practice, to avoid dependence on the type of processed data, they are also usually written, as a template function. Then it might look like this:

Finally, note, if not noticed until now, that the accumulation of amounts we use the initial value 0 (3-First option accumulate() ), and the accumulation of works, naturally, 1, with the corresponding data type.

Newsletter of programming:

Sorting structures. STL Part 13




sorting structures c ++, stl beginnersShown in the previous section various sorting - Flexible and beautiful mechanism for all occasions. That's just in practice, sort sequence almost never have a pure. This is all from the field of educational and demonstration tasks. In practice, the more often the problem is sorted quite voluminous data structures (even bulky in size, and according to the number of its fields). And sort (or resorting) they will have on the values ​​for the different fields of these same structures. But here come to the aid STL algorithms, especially when used in conjunction with the functors.

Let's see the typical model problem, which we've seen before - a description of the training group or faculty:

The program requests the field number data, on which sorting will be carried out (actually - comparison). If this number is entered, as a positive number, then sort by that field goes in ascending order. If the number is entered with a minus sign - the sort order is reversed:

sorting structures c ++, stl beginnerssorting structures c ++, stl beginners

Note, that the sorting algorithm does not care that sort: if the numeric data, the largest, and if lowercase, in order leksograficheskom.

Newsletter of programming: