C++
C++ is a programming language designed in 1979 by Bjarne Stroustrup. The intention of creating it was to extend the C programming language and add mechanisms that allow object manipulation. In that sense, from the point of view of object-oriented languages, C++ is a hybrid language.
Later, generic programming facilities were added, which were added to the paradigms of structured programming and object-oriented programming. This is why it is often said that C++ is a multi-paradigm programming language.
There is now a standard, called ISO C++, which most modern compiler manufacturers have adhered to. There are also some interpreters, such as ROOT.
The name "C++" It was proposed by Rick Mascitti in 1983, when the language was first used outside of a scientific laboratory. The name "C with classes" had been used before. In C++, the expression "C++" means "increase of C" and refers to C++ being an extension of C.
C++ Features
- Your syntax is inherited from C language.
- Object-oriented programme (POO).
- Allows the grouping of instructions.
- It is portable and has a large number of compilers on different platforms and operating systems.
- It allows the separation of a program in modules that support independent compilation.
- It's a high-level language.
Examples
The following is a sample Hello World program written in C++:
/* This header allows you to use the objects that encapsulate the stdout descriptorsand stdin: cout(associated) and cin(pursuative)*/# Include ▪using namespace std;int main(){ cout ; "Hello world" ; endl; return 0;!
Using the #include
directive tells the compiler to find and interpret all elements defined in the file that accompanies the directive (in this case, iostream
). To avoid overwriting elements already defined by giving them the same name, namespaces or namespace
of the English singular were created. In this case there is a namespace called std
, which is where the definitions of all the functions and classes that make up the C++ standard library are included. By including the using namespace std
statement we are telling the compiler that we will use the std
namespace, so we will not have to include it when using elements of this namespace, like can be the cout
and cin
objects, which represent standard output stream (typically the screen or a text window) and standard input stream (typically the keyboard).
The definition of functions is the same as in C, except for the feature that if main
is not going to take arguments, we don't have to put them, unlike in C, where you had to put them explicitly, even if they were not to be used. It only remains to comment that the symbol <<
is known as the insertion operator, and grosso modo is sending to cout
what we want to show by screen for it to paint, in this case the string "Hello world"
. The same <<
operator can be used several times in the same statement, so thanks to this feature we can concatenate the endl
object at the end, whose result will be to print a line return.
Data types
C++ has the following fundamental types:
- Characters:
char
(also an integer),wchar_t
- Enter:
short
,int
,long
,long long
- Numbers in floating coma:
float
,double
,long double
- Booleanos:
bool
- Empty:
void
The unsigned
modifier can be applied to integers to get unsigned numbers (integers are signed by default), thus achieving a larger range of natural numbers.
Associated sizes
Depending on the machine and the compiler used, the primitive types can occupy a certain size in memory. The following list illustrates the number of bits that the various primitive types occupy on the x86 architecture.
Type | Number of bits |
char | 8 |
short | 16 |
int | 32 |
float | 32 |
double | 64 |
Other architectures may require different sizes of primitive data types. C++ doesn't say anything about the number of bits in a byte, or the size of these types; rather, it offers only the following "type guarantees":
- According to the C99 standard, a type
char
must occupy exactly one byte composed of a minimum of 8 bits regardless of machine architecture. - The recognized size
char
It's 1. I mean,sizeof(char)
always returns 1. - A guy.
short
It has at least the same size than a typechar
. - A guy.
long
It has at least double size in bytes that a typeshort
. - A guy.
int
has a size betweenshort
and thelong
, both included, preferably the size of a machine memory pointer. Its maximum value is 2147483647, using 32 bits. - A guy.
unsigned
has the same size as your versionsigned
.
Wchar_t
For the version of the standard that was published in 1998, it was decided to add the data type wchar_t
, which allows the use of UNICODE characters, as opposed to the traditional char
, which simply covers the extended ASCII character code. In turn, a version has been defined for most of the functions and classes, both in C and C++, to work with wchar_t
, where the character w to the function name (sometimes the character is an infix). For example:
strcpy - wstrcpy
std::string - std::wstring
std::cout - std::wcout
It should be noted that in C wchar_t
is defined as:
typedef unsigned short wchar_t;
Whereas in C++ it is itself a data type.
The keyword "void"
The keyword void
defines in C++ the concept of non-existence or non-attribution of a type in a variable or declaration. That is, a function declared as void
will not return any value. This keyword can also be used to indicate that a function takes no parameters, as in the following declaration:
int operation (void);
Although the current trend is to not use the word "void".
Also used to determine that a function does not return a value, as in:
void operation (int parameter);
Note that void
is not a type. A function like the one declared above cannot return a value via return: the keyword goes by itself. A declaration of the type is not possible:
void t; It's wrong.
In this sense, void
behaves slightly differently than it does in C, especially in terms of its meaning in function declarations and prototypes.
However, the special form void * indicates that the data type is a pointer. For example:
void ♪memory;
Indicates that memory is a pointer to somewhere, where information of some kind is stored. The programmer is responsible for defining these "some", removing all ambiguity. An advantage of the "void *" is that it can represent several types of data at the same time, depending on the cast operation chosen. The memory that we have pointed to somewhere, in the example above, could well store an integer, a float, a text string or a program, or combinations of these. It is the programmer's responsibility to remember what kind of data is there and to ensure proper access.
The word "NULL"
In addition to the values that the aforementioned types can take, there is a value called NULL, be it the numeric case for integers, character for the char type, text string for the string type, etc. The NULL value usually expresses the representation of a Macro, assigned the value "0".
We then have that:
void♪ pointer = NULL;int whole = NULL;Bool Boleana = NULL;Char character = NULL;
The value of the above variables would give us 0. Unlike the "character" variable, which would give us the NULL equivalent, '', for characters.
To avoid ambiguity in overloaded functions, the nullptr keyword can be used. This keyword always represents a pointer. For example:
void f(int a);void f(Foo ♪a);int main(int argc, Char** argv) { f(NULL); // Runs f(int a) f(nullptr); // Runs f(foo *a) return 0;!
Principles
Every C++ program must have the main function main()
(unless another entry point is specified at compile time, which is actually the function that has the main()
)
int main(){cHFFFF}
The main source function main must have one of the following prototypes:
int main()
int main(int argc, char** argv)
Although not standard some implementations allow
int main(int argc, char** argv, char** env)
The first is the default form of a program that takes no parameters or arguments. The second form has two parameters: argc, a number describing the number of arguments to the program (including the name of the program itself), and argv, a pointer to an array. of pointers, of argc elements, where the argv[i] element represents the ith argument passed to the program. In the third case, the possibility of being able to access the execution environment variables is added in the same way that the program arguments are accessed, but reflected on the env variable.
The return type of main is an integer int value. At the end of the main
function, the return value must be included (for example, return 0;, although the standard provides for only two possible return values: EXIT_SUCCESS and EXIT_FAILURE, defined in the cstdlib file), or exit via the exit function. Alternatively it can be left blank, in which case the compiler is responsible for adding the appropriate output.
The concept of class
Objects in C++ are abstracted by a class. According to the object-oriented programming paradigm, an object consists of:
- Identity, which differentiates it from other objects (Name that will take the class to which the object belongs).
- Methods or functions.
- Member attributes or variables.
An example of a class we can take is the dog class. Each dog shares some characteristics (attributes). Its number of legs, the color of its fur or its size are some of its attributes. The functions that make it bark, change its behavior... those are the functions of the class.
This is another example of a class:
class Period{//by omission, members are 'private' so that they can only be modified from the class itself.private: // Variable private member int id;protected: // Protected member variables int x; int and;public: // Builder Period(); // Destroyer ~Period(); // Member functions or methods int GetX(); int GetY();};
Builders
They are special methods that are executed automatically when creating an object of the class. Their declaration does not specify the type of data they return, and they have the same name as the class to which they belong. Like other methods, there can be multiple overloaded constructors, although virtual constructors cannot exist.
As a special feature when implementing a constructor, just after the parameter declaration is what is called the "initializer list". Its purpose is to call the constructors of the attributes that make up the object to be constructed.
It should be noted that it is not necessary to declare a constructor as well as a destructor, as the compiler can do it, although it is not the best way to program.
Taking the example of the Point Class, if we want each time an object of this type is created class the coordinates of the point are equal to zero we can add a constructor as shown then:
class Period{ public: float x; // Point coordinates float and; // Builder Period() : x(0), and(0♪ // We start variables "x" and "y" !};// Main to demonstrate class performance# include ▪ // This allows us to use "cout"using namespace std;int main () { Period My point; // we create an element of the Point class called My Point cout ; "Coordinate X: " ; My point.x ; endl; // show the accumulated value in variable x cout ; "Coordinated And: " ; My point.and ; endl; // show the accumulated value in the variable and getchar(); // we tell the program to wait for the input buffer (stop) return 0;!
If we compile and run the above program, we get an output that should be similar to the following:
X coordinate: 0 Y coordinate: 0
There are several types of constructors in C++:
- Default builder. It is the builder who receives no parameter in the function. If no builder was defined, the system would provide a default. It is necessary for the construction of STL structures and containers.
- Copy builder. It is a builder who receives an object of the same class, and performs a copy of the attributes of it. Like the default, if not defined, the system provides one.
- Conversion Builder. This builder receives as a single parameter, an object or variable of another type other than his own. That is, it converts an object of a certain type to another object of the kind that we are generating.
Constructors + Heap Memory An object created in the way we have seen so far, is an object that lives within the scope (the braces { }) in which it was created. In order for an object to continue to live when it is taken out of the scope in which it was created, it must be created in heap memory. For this, the new operator is used, which allocates memory to store the created object, and also calls its constructor (so parameters can be sent to it). The new operator is used as follows:
int main() { Period ♪One point = new Period(); //this calls the builder described above Delete One point; //do not forget to release the memory occupied by the object(see the destroyer section, below) return 0;!
In addition, with the operator new[] you can create arrays (collections or ordered lists) of dynamic size:
Period ♪assign(int how many) { return new Period[chuckles]how many]; //Almost an array of 'how many' points(the builder is called above), and is returned.!
Destroyers
Destructors are special member functions called automatically at program execution, and therefore do not have to be called explicitly by the programmer. Its main tasks are:
- Release the computer resources that the object of this class has acquired in time of execution at the end of this class.
- Remove links that may have other resources or objects with it.
Destructors are called automatically when the program flow reaches the end of the scope in which the object is declared. The only case in which the destructor of an object must be explicitly called is when it was created using the new operator, that is, it lives in heap memory, and not in the execution stack of the object. Program. Invoking the destructor of an object that lives on the heap is done through the delete or delete[] operator for arrays. Example:
int main() { int ♪an Entero = new int(12); //assigned an integer in heap memory with value 12 int ♪arrayDeEnteros = new int[chuckles]25]; //assigned memory for 25 integers (not initialized) Delete an Entero; //release the memory of an Entero Delete[] arrayDeEnteros; //free the memory occupied by arrayDeEnteros return 0;!
If the delete and delete[] operators were not used in this case, the memory occupied by anInteger and arrayOfIntegers respectively, would be occupied without meaning. When a portion of memory is occupied by a variable that is no longer used, and there is no way to access it, it is called a 'memory leak'. In large applications, if there are a lot of memory leaks, the program can end up taking up a lot more RAM than it should, which is not good at all. This is why heap memory management must be used consciously.
There are two types of destructors, they can be public or private, depending on whether they are declared:
- If it is public it is called from anywhere in the program to destroy the object.
- If private, the destruction of the object by the user is not permitted.
The use of destructors is key to the Acquire Resources is Initialize concept.
Member functions
Member function is one that is declared in class scope. They are similar to regular functions, except that the compiler will perform the Name Mangling process: It will change the name of the function by adding a identifier of the class in which it is declared, and may include special characters or numeric identifiers. This process is invisible to the programmer. In addition, member functions implicitly receive an additional parameter: the this pointer, which references the object that executes the function.
Member functions are called by first accessing the object to which they refer, with the syntax: myobject.mymemberfunction(), this is a clear example of a member function.
Special case is static member functions. Although they are declared inside the class, using the static keyword will not receive the this pointer. Thanks to this, it is not necessary to create any instance of the class to call this function, however, it will only be possible to access the static members of the class since these are not associated to the object but to the type. The syntax for calling this static function is mytype::mystaticmember().
Templates
Templates are C++'s mechanism for implementing the generic programming paradigm. They allow a class or function to work with abstract data types, later specifying which ones to use. For example, it is possible to build a generic vector that can contain any type of data structure. In this way, objects of the class of this vector can be declared that contain integers, floats, polygons, figures, personnel files, etc.
The declaration of a template is done by preceding the declaration template <typename A,....> to the declaration of the desired structure (class, structure or function).
For example:
template template template template .typename T▪T max(const T "x, const T "and) { return (x ▪ and) ? x : and; //if x and, return x, but return!
The function max() is an example of generic programming, and given two parameters of a type T (which can be int, long, float, double, etc.) will return the largest of them (using the > operator). When executing the function with parameters of a certain type, the compiler will try to "match" the template to that data type, or it will generate an error message if it fails in that process.
Specialization
The following example:
template template template template .typename A▪ int myfunction(A a);
creates a template under which any specialized functions for a data type such as int myfunction(int), int myfunction(std::string), int myfunction(bool), etc.:
int myfunction (int a) { return a + 5;};int myfunction (std::string a) { return -a.size();};int myfunction (Bool a) { return (a " rand()); //If a is true, return a random number; otherwise return 0};
Each of these functions has its own definition (body). Each different, non-equivalent ("non-convertible") body corresponds to a specialization. If one of these functions is not defined, the compiler will try to apply whatever data type conversions it is allowed to "match" one of the templates, or it will generate an error message if it fails in that process.
All enabled definitions of a template must be available at compile time, so it is currently not possible to "compile" a template as an object file, but simply compile specializations of the template. Therefore, the templates are distributed together with the application source code. In other words, it is not possible to compile the template std::vector< > to object code, but it is possible, for example, to compile a std::vector<std::string> data type.
Abstract classes
In C++ it is possible to define abstract classes. An abstract class, or abstract base class (ABC), is one that is designed only as a parent class from which child classes must be derived. An abstract class is used to represent those entities or methods that will later be implemented in derived classes, but the abstract class itself does not contain any implementation -- it only represents the methods that should be implemented. Therefore, it is not possible to instantiate an abstract class, but it is possible to instantiate a concrete class that implements the methods defined in it.
Abstract classes are useful for defining interfaces, that is, a set of methods that define the behavior of a given module. These definitions can be used regardless of the implementation that will be made of them.
In C++ the methods of abstract classes are defined as pure virtual functions.
class Abstract{ public: virtual int Method() = 0;!class ConcreteA : public Abstract{ public: int Method() { //do something return Foo () + 2; !};class ConcreteB : public Abstract{ public: int Method() { //other implementation return baz () - 5; !};
In the example, class ConcreteA is an implementation of class Abstract, and class ConcreteB is another implementation. It should be noted that the = 0 is the notation that C++ uses to define pure virtual functions.
Namespaces
An addition to the features of C are namespaces, which can be described as virtual areas under which certain variable names or types are valid. This allows avoiding the occurrence of conflicts between names of functions, variables or classes.
The best-known example in C++ is the namespace std::, which stores all new definitions in C++ that differ from C (some structures and functions), as well as custom functionality. C++ (streams) and STL library components.
For example:
# include ▪// The functions in this header exist within the std namespace:namespace mi_paquete{ int mi_valor;};int main(){ int mi_valor = 3; mi_paquete::mi_valor = 4; std::cout ; mi_valor ; '; // print '3' std::cout ; mi_paquete::mi_valor ; '; // print '4' return 0;!
As you can see, direct calls to my_value will only give access to the locally described variable; to access the namespace variable my_package you need to specifically access the namespace. A recommended shortcut for simple programs is the using namespace directive, which allows you to access the variable names of the desired package directly, as long as there is no ambiguity or name conflict.
Inheritance
There are several types of inheritance between classes in the C++ programming language. These are:
Simple inheritance
Inheritance in C++ is an abstraction mechanism created to facilitate and improve the design of classes in a program. With it you can create new classes from already made classes, as long as they have a special type of relationship.
In inheritance, derived classes "inherit" the data and member functions of the base classes, and the derived classes can redefine these behaviors (polymorphism) and add new behaviors specific to the derived classes. In order not to break the principle of encapsulation (hiding data whose knowledge is not necessary for the use of the classes), a new mode of visibility of the data/functions is provided: "protected". Anything that has visibility protected will behave as public in the Base class and in those that make up the inheritance hierarchy, and as private in classes that are NOT in the inheritance hierarchy.
Before using inheritance, we have to ask ourselves a question, and if it makes sense, we can try using this hierarchy: If the phrase <classB> IS-A <class A> makes sense, then we are dealing with a possible case of inheritance where class A will be the base class and class B the derived one.
Example: Ship, Battleship, Freighter, etc. classes. A Battleship IS-A Ship, a Freighter IS-A Ship, an Ocean Liner IS-A Ship, etc.
In this example we would have the general things of a Ship (in C++)
class Barco { protected: Char♪ Name; float weight; public: //Builders and other basic ship functions};
and now the characteristics of the derived classes could (while inheriting the ship ones) add things specific to the ship subtype that we are going to create, for example:
class Charge: public Barco { // This is the way to specify that you inherit from Barco private: float load; //The rest of things};class Armored: public Barco { private: int Number; int Soldiers; // The rest of things};
Finally, it should be mentioned that there are 3 inheritance classes that differ in the way they handle the visibility of the components of the resulting class:
- Public heritage (class Derivada: public Base): This type of inheritance respects the original behaviors of the visibility of the base class in the Derived class.
- Private inheritance (Derived class: private Base): With this kind of inheritance every component of the Base class, it will be private in the Derived class (the inherited properties will be private even if they are public in the Base class)
- Protected heritage (Derived class: protected Base): With this type of inheritance, any public and protected component of the Base class will be protected in the Derived class, and private components remain private.
Multiple inheritance
Multiple inheritance is the mechanism that allows the programmer to make classes derived from not just one base class, but several. To understand this better, let's take an example: When you see the person who serves you in a store, as a person, you can assume that they can talk, eat, walk, but, on the other hand, as an employee, you can also assume that they have a boss, who can charge you money for the purchase, that he can return the change, etc. If we transfer this to programming, it would be multiple inheritance (employee_store class):
class Person { ... Talk(); Walk(); ...};class Employee { Person Chief; int salary; Cobrar(); ...};class Employee: public Person, Employee { ... StoreStock(); CheckExistences(); ...};
Therefore, it is possible to use more than one class so that another class inherits its characteristics.
Operator overloading
Operator overloading is a way of doing polymorphism. It is possible to define the behavior of a language operator to work with user-defined data types. Not all C++ operators are overloadable, and, among those that can be overloaded, special conditions must be met. In particular, the sizeof and :: operators are not overloadable.
It is not possible in C++ to create a new operator.
The behaviors of overloaded operators are implemented in the same way as a function, except that the function will have a special name: Return data type operator<operator token>(parameters)
The following operators can be overloaded:
- Unarios Operators
- Operator * (indirection)
- Operator - plan (indirection)
- Operator " (direction)
- Operator +
- Operator -
- Operator ++
- Operator --
- Binary operators
- Operator ==
- Operator +
- Operator -
- Operator *
- Operator /
- Operator %
- Operator
- Operator
- Operator "
- Operator ^
- Operator Δ
- Operator []
- Operator ()
- Assignment Operators
- Operator =
- Operator +=
- Operator -=
- Operator *
- Operator /=
- Operator %=
- Operator backwards =
- Operator ▪
- Operator >
- Operator ^=
- Operator Δ=
Since these operators are defined for a user-defined data type, the user is free to assign whatever semantics he wishes to them. However, it is considered of prime importance that the semantics be so close to the natural behavior of the operators that the use of the overloaded operators is intuitive. For example, the use of the unary operator - should change the "sign" of a "value".
The overloaded operators are still functions, so they can return a value, if this value is of the data type with which the operator works, it allows the chaining of statements. For example, if we have 3 variables A, B and C of a type T and we overload the operator = so that it works with the data type T, there are two options: if the operator does not return anything a statement like "A= B=C;" (without the quotes) would give an error, but if a data type of T was returned when implementing the operator, it would allow you to concatenate as many elements as you like, allowing something like "A=B=C=D=...;&# 3. 4;
Standard Template Library (STL)
Programming languages often have a number of built-in function libraries for data manipulation at the most basic level. In C++, in addition to being able to use the C libraries, you can use the native STL (Standard Template Library), typical of the language. It provides a series of templates (templates) that allow operations to be carried out on data storage, input/output processing.
Input and output library
The classes basic_ostream and basic_stream, and the objects cout and cin, provide the standard input and output data (keyboard/display). Also available is cerr, similar to cout, used for standard error output. These classes have overloaded operators << and >>, respectively, in order to be useful in inserting/extracting data to said streams. They are intelligent operators, since they are capable of adapting to the type of data they receive, although we will have to define the behavior of said input/output for classes/data types defined by the user. For example:
ostream" operator;(ostream" fs, const Period" point){ return fs ; point.x ; " ; point.and;!
In this way, to show a point, you only have to carry out the following expression:
//...Period p(4,5);//...cout ; "The coordinates are: ; p ; endl;//...
It is possible to format the input/output, indicating the number of decimal digits to display, if the texts will be converted to upper or lower case, if the received numbers are in octal or hexadecimal format, etc.
Fstreams
Flow type for handling files. The previous definition of ostreams/istreams is applicable to this section. There are three classes (read, write, or read/write files): ifstream, ofstream, and fstream.
How to open a file: (file_variable_name).open("file_name.dat/txt", ios::in); to open it in reading mode. (filevariablename).open("file_name.dat/txt", ios::out); to open it in write mode.
Example: f.open("data.txt", ios::in);
How to close the file: variable_name file.close();
Example: f.close();
Read a file:
1-If it is plain text file:
# Include ≥fstream # Include Δstring # Include ▪ using namespace std; int main() { ifstream Entry; Entry.open("textPlano.txt"); string aString; while(Entry ◊ aString) cout ; "Lei: " ; aString ; endl; return 0; !
2-If it is a binary file(.dat); name_variable_fichero.read(char*) unknown name_variable, sizeof(type_variable));
Example:
f.read((char*) strangere, sizeof(int));
Write a file:
1-If it is text file(.txt): "text"; where "text" can also be a variable of any primitive type, or a string.
Example: f;
2-If it is a binary file(.dat); name_variable_fichero.write((char*) fakenombre_variable, sizeof(type_variable));
Example:
f.write((char*) strangere, sizeof(int));
They can be opened by passing to the constructor the parameters related to the location of the file and the opening mode:
Streams
Two classes stand out, ostringstream and istringstream. All of the above is applicable to these classes.
They treat a string as if it were a stream of data. ostringstream allows you to build a string by inserting data as a stream, and istringstream can extract the information contained in a string (passed as a parameter to its constructor) with the >>
operator.
Examples:
ostringstream s;s ; Name ; " ; Age ; " ; height ; " ; point(5,6) ; endl;cout ; s.str();istringstream s(chain);s ◊ Name ◊ Age ◊ height ◊ p;
Containers
They are special template classes used to store generic data types, whatever they may be. All containers are homogeneous, that is, once they are declared to contain a specific data type, only elements of that type can be placed in that container. Depending on the nature of the storage, we have several types:
- Vectors: They are defined by
vector_de_dato voluntary name_del_vector;
They are arrays (or orderly lists) that are automatically redimensed by adding new elements, so they can be added "theoretically", infinite elements. Vectors allow us to access any element that contains, through the operator[]. It should be taken into account that if you try to access a position that exceeds the limits of the vector, it will not make any checks, so you should be careful when using this operator. To ensure safe access to the vector, you can use the at(int) method, which releases a std-type exception::out_of_range in case this happens.
To add elements to the end of the vector, the push_back(const T&) method is used. On the other hand, to remove an element from the end of the vector, the pop_back() method must be used.
# Include ≤2 //booking containing the vector class# Include ▪using namespace std;int main() { vector.int▪ intVector; //creates an integer vector (without elements) intVector.push_back(25); //Add the entire 25 to the vector cout ; "The first element is: " ; intVector.front() ; "and my vector has" ; intVector.size() ; " elements. " ; endl; //prints the first element, returned by the front() method intVector.push_back(32); //Add the whole 32 to the vector cout ; "The first element is: " ; intVector[chuckles]0] ; endl; / Print 25 intVector.pop_back(); //eliminates the last element of the vector (i.e. 32) cout ; "Now I have: " ; intVector.size() ; " elements. " ; endl; //print 1 return 0;!
- Double balls: they are similar to vectors, but have better efficiency to add or remove elements in the "points".
of which the type_de_dato voluntary name_de_la_cola;
In addition to the push_back(const T&) and pop_back() methods, the push_front(const T&) and pop_front() methods are added, which do the same as those already explained, but at the beginning of the queue.
# Include ≤2 //Talk bookletusing namespace std;int main() { of.int▪ intDeque; intDeque.push_front(25); intDeque.push_back(12); while(intDeque.size()) intDeque.pop_back(); //board all elements return 0;!
- Lists: They are efficient when adding items. The difference with double tails is that they are more efficient to remove elements that are not in any of the "puntas"
list index_de_dato voluntary name_de_la_lista;
- Sequence adapters.
- Associative containers: map and multimap, which allow to associate a "key" with a "value". map does not allow repeated values, while multimap does.
map index_de_llave, type_de_dato/2005 name_del_map; multimap variable type_de_llave, type_de_dato voluntary name_del_multimap;
# Include ≤3 //book containing map and multimap# Include Δstring //Crossbook# Include ▪ //input/output libraryusing namespace std;int main() { map.int, string▪ intAString; intAString[chuckles]1] = "one"; intAString[chuckles]10] = "ten"; cout ; "In intAString[1]: " ; intAString[chuckles]1] ; endl; cout ; "In intAString[10]: ; intAString[chuckles]10] ; endl; return 0;!
- Associative containers: set and multiset, which offer only the condition of "pertenence", without the need to guarantee a particular order of the elements they contain.
Iterators
They can be thought of as a generalization of the "pointer" class. An iterator is a data type that allows traversal and search of elements in containers. Since data structures (containers) are generic classes, and the operators (algorithms) that must operate on them are also generic (generic functions), Stepanov and his collaborators had to develop the concept of an iterator as an element or link between the two.. The new concept turns out to be a kind of pointers that point to the various members of the container (generic pointers that as such do not exist in the language).
Algorithms
Combining the use of templates and a specific style to denote types and variables, the STL offers a series of functions that represent common operations, and whose objective is to "parameterize" the operations in which these functions are involved so that their reading, understanding and maintenance are easier to perform.
An example is the copy function, which simply copies variables from one place to another. More strictly, it copies the contents whose locations are bounded by two iterators, to the space indicated by a third iterator. The syntax is:
copy (initiated_origin, fin_origin, beginning_destino);
In this way, all data between source_start and source_end, excluding the data located in the latter, are copied to a place described or pointed to by destination_start.
A very important algorithm that is implemented in the STL library is sort. The sort algorithm sorts any type of container, as long as it is passed as arguments, from where and to where you want to sort it.
# Include ≤2# Include ≤2# Include Δalgorithmint main() { vector.int▪ intVector; intVector.push_back(60); intVector.push_back(12); intVector.push_back(54); //for this moment, the vector has 60,12,54 draw(intVector.begin(), intVector.end()); //ready, orderly array, now has 12,54,60 /*Note that if instead of a vector, it was a deque, it would be ordered in the same way. */!
Among the well-known functions are swap (variable1, variable2), which simply swaps the values of variable1 and variable2; max (variable1, variable2) and its simile min (variable1, variable2), which return the maximum or minimum between two values; find (start, end, value) which searches for value in the variable space between start and end; etc.
Algorithms are very varied, some even have specific versions to operate with certain iterators or containers, and provide an extra level of abstraction that allows to obtain a "cleaner"code, which "describes& #3. 4; what is being done, instead of doing it step by step explicitly.
C++11
On August 12, 2011, Herb Sutter, Chairman of the C++ Standards Committee, reported the unanimous approval of the new standard. It was released sometime in 2011.
Among the characteristics of the new standard we can highlight:
- Lambda functions;
- Rvalue references;
- The word reserved car;
- Uniform initiation;
- Templates with variable number of arguments.
In addition, the standard language library has been updated.
Present and future
In 2011 C++11 inaugurated a new era in the history of C++, starting a three-year cycle of releasing new versions. C++11 was followed by C++14 and then C++17, which is the current version in 2019; C++20 is close to being standardized, and the C++23 version is already being worked on. Compilers try to get ahead of the game by experimentally incorporating some new features before official releases. But each new version of C++ includes so many additions that the most advanced compilers usually don't finish incorporating them until two or three years after the release of that version.
Type differences from C
In C++, any data type that is declared fully (fully qualified) is converted to a unique data type. The conditions for a data type T to be declared complete are broadly speaking the following:
- It is possible at the time of compilation to know the space associated with the type of data (i.e., the compiler must know the result of size(T)).
- T He has at least one builder, and a destroyer, well-declared.
- Yeah. T is a composite type, or is a derivative class, or is the specification of a template, or any combination of the above, then the two previously established conditions must apply for each type of constituent data.
In general, this means that any data type defined using the full headers is a full data type.
In particular, and unlike in C, types defined by struct or enum are fully qualified types. As such, they are now subject to overloading, implicit conversions, etc.
The enumerated types, then, are no longer simply aliases for integral types, but are unique data types in C++. The data type bool, likewise, becomes a unique data type, whereas in C it functioned in some cases as an alias for some integer data class.
Compilers
One of the free C++ compilers is the GNU G++ compiler (part of the GCC project, which encompasses several compilers for different languages). Other common compilers are Intel C++ Compiler, Xcode compiler, Borland C++ compiler, CodeWarrior C++ compiler, Cygwin g++ compiler, MinGW g++ compiler, Visual C++ compiler, Carbide.c++, among others.
Development environments
Under Microsoft Windows
- Visual Studio Code
- Code::Blocks
- Dev-C++
- Visual C++
- wxDev-C++
- Zinjai
- Open Watcom (IDE and Dialog Editor)
- CodeLite
Under MacOS
- Xcode
- Zinjai
- CodeLite
- Geany
Under DOS
- Turbo C, replaced by C++Builder
Under GNU/Linux
- Code::Blocks
- NetBeans
- Eclipse
- Geany
- Emacs
- Zinjai
- Kdevelop
- Open Watcom (IDE and Dialog Editor)
- CodeLite
- Clion (software)
Software Created and Programmed with C++
- Microsoft Edge
- Google Chrome
- Bitcoin
- μTorrent
- BitTorrent (programme)
- Haiku (operating system)
- Windows Phone 8.1
- Open Broadcaster Software
- Opera (navegador)
- CATIA
Criticism
Despite its widespread adoption, many programmers have criticized the C++ language, including Linus Torvalds, Richard Stallman, and Ken Thompson. Problems include a lack of reflection or garbage collection, slow compile times, perceived feature creep, and detailed error messages, particularly from template metaprogramming.
To avoid the problems that exist in C++, and to increase productivity, some people suggest alternative languages newer than C++, such as D, Go, Rust, and Vala.
Contenido relacionado
Vector (disambiguation)
Robotics
Database