Guide | How To How to start programming in C++ (Part 4 of 5)

The associated guide may contain user-generated or external content.

JM Safe

Level 39
Thread author
Verified
Top Poster
Apr 12, 2015
2,882
Hi all!

Previous article here: [Tutorial] How to start programming in C++ (Part 3)

The cast

When you declare variables of different types you need to be careful that you do not tangled within the same algebraic expression, or assignment, values and/or variables of different types. The compiler reports generic type mismatch error (type mismatch) when you try to force a value of a type to a variable declared to be of type incompatible with that value. In some cases the compiler makes a stretch, for example, if you try to add a float value in a variable of type int: clearly the portion is truncated.

Sometimes, however, may affect make changes on the fly to keep the results of certain operations on variables of different types, primarily when you go from a smaller to a larger type. In such cases the C++ language programmer provides a construct called cast.

#include

using namespace std;



int main ()

{

int one, two;

float three;



one = 1;

two = 2;

three = one/two;

cout < < three < < endl;



return 0;

}



This program despite expectations (dictated by the fact that the variable three declared float) will produce a null result. The Division is made out of two values of type int, the result is stored temporarily in a variable of type int, and only at the end, kept in a float variable. It is clear at this point that the three variable will only contain the integer part (i.e. 0).

In order for the Division to produce the expected result, you must notify C++ to convert the intermediate result before storage in the destination variable.

All this is possible using the construct cast. The program, you would write:

#include

using namespace std;



int main ()

{

int one, two;

float three;



one = 1;

two = 2;

three = static_cast (a)/due;

cout < < three < < endl;



return 0;

}



In this case the result of running the program coincides with the wait. In fact, the quotient is calculated as float (the contents of the variable one is forced float) and then, later, assigned to three.

Ultimately using the unary static_cast applied to the variable one is strength, in the calculation of the expression, its value to be of a specific type (in this case integer division is forced to provide a floating-type result as a value of that type).

It is now proposed an interesting application of casting for the transformation of a lowercase character uppercase representation. The program leverages to achieve its result, the fact that a variable of type char, ultimately, retains a numeric code; Here it also used the casting to show that code.

#include

using namespace std;



int main ()

{

char min, ever;

const int offset = 32; /*1*/



"convert uppercase lowercase-" cout < < < < endl;

cout < < "Enter a lowercase";

CIN >> min; /*2*/



If (min > = ' a ' && min < = ' z ') {/* 3 */

never = min-offset; /*4*/

"\n uppercase Representation" cout < < < < never < < endl; /*5*/

cout < static_cast "ASCII code" < < < (never) * 6 */;/endl < <

}

else

"unconvertible Character \n" cout < < < < endl;



return 0;

}



In the line labeled 1 constant is defined. 32 value depends on whether, in ASCII code used in the representation of characters in the memory of a computer, that is the distance between upper and lower case (eg. ' A ' has code 65, ' a ' has code 97).

In the line labeled 2 you make the character input to process.

In the line labeled 3 checks if the input character is within the bounds of lowercase letters. Lowercase letters, in ASCII, code between 97 (lowercase a) and 122 (the lowercase letter z). The comparison could also be made on numerical representation:

If (min > = 97 && min < = 122)



In the line labeled 4 takes place in practice transformation into uppercase. The numeric code associated with the character is subtracted the value 32. In this case use the numeric code of the character. Note that in this context it makes sense to assign to a char, the result of a subtraction (numerical operation).

In the line labeled 5 making the output of never intended as a character (so it is in fact defines the variable), where in the row 6 making the output of its numeric code (it used a casting on the variable).

Introduction to classes and objects: carriers

The carrier is the first data structure (container, container) treated in computer science. We talk about data structure when referring to a set of data organized according to a specific law. A data structure is a set where, as in the commonly understood mathematics, membership and the law defined whose elements can be carried out certain tasks: creating the structure, inserting/deleting an item, search for an item, select a subset.

The carrier is the most commonly used data structure and is the one that is the foundation of almost everything else.

A vector is a collection of variables of the same type that can be accessed through a common name and referencing a specific item by using an index.

You can think of to the carrier as a series of numbered drawers: a way to access the contents of a drawer is to specify the place where the collection and the number next to the item (index) that indicates their relative position to the starting point of the structure. The first element of the vector has index 0.


In simple variables to access the value contained in them you must specify the name and, moreover, a variable that has to keep a different value will have a different name. In vector a name exists but this time identifies the entire structure.

The elements of the vector are allocated in adjacent memory locations.

C++, in the case of complex structures (container), provides a mechanism (classes) that allows, once declared an object of that type, to the object itself, to possess the typical behaviors of all objects in the same family for easier processing.

The vector definition is contained in the library vector that must be included in the code as many times as you need to define a variable of type vector. The library is part of what are called the Standard Template Library (STL).

The differences between the Declaration of a variable of type elementary, for example, a variable of type int, and an object, for example, the vector class can be summed up:

A type declaration:

int a;



acting, for reasons of the kind, defining some operations (the four elementary arithmetic and the module operation) that can be applied to the data contained in the variable that is a container for data on which you want to perform those operations.

A type declaration:

vector v;

declares an object of the class vector containing integers (type is specified between the angle brackets < >) as elements, but v as an object (an instance) of the vector class has all the behaviors defined in the class. You cannot directly manage the elements of the vector because you interact with an object using the methods defined for that class. The method is a skill, a feature that provides a particular processing on the data container. The method relies on the object (it sends a message to the object) and this will react in accordance with the method itself that is, will the items processing described.

The most common methods of vector class that will be used in examples of these notes are summarised in table:



Returns a Boolean value (true or false) indicating whether the vector is empty or contains at least one item



Returns the amount of elements in vector



Gets the location in memory of the first element of the vector



Returns the position in memory after the last element of the vector



Allows you to access the element of the vector that is in a certain position. You must specify the index as integer in parentheses (parameter).

push_back ()


Allows you to insert, queued in vector, a new item. The element must be specified as a parameter in parentheses and must be of the type provided for in the Declaration of the vector

Insert method ()


Allows the insertion of an element any carrier. In brackets you specify two variables/values (parameters) separated by commas: the pointer to the insertion position, the element to be inserted

erase method ()


Eliminates from the structure of an element. Takes as a parameter a pointer to the element.

A method is applied to the object by specifying it after the name of the object and, separated from this by the operator (the point).

For example:

...

vector v;

...

cout < <. size () v;

...

the line of code produces display the amount of items in the vector v.

Iterators

The iterator is an object that provides access to individual elements in a container of objects, for example a vector. Using an iterator you can scan linear of a vector, that is, scroll one after the other all items contained in a vector in order, for example, to perform certain processing. An iterator is a pointer to the element (i.e. gives an indication on where is in main memory element) and can be updated according to the rules of arithmetic in to point to the next element of the sequence still consist elements of the sequence.

As elementary example usage of iterators proposes a code snippet in which, using a sequential scan of a vector of integers, doubles the value of each item contained in it:

vector numbers;/* 1 */

vector :: iterator it;/* 2 */

...

for (it = numbers. begin (); it! = numeri.end (); it ++)/* 3 */

* it = * en * 2; /*4*/



In 1 declares a vector of type int. In 2 you declare an iterator that can iterate through the elements of a vector of the specified type. If there had been a vector of type float, you should define an iterator appropriate: vector :: iterator it.

The cycle of 3 uses the iterator in accordance with the same rules of integers: is taken as the initial value of the iterator the position of the first element of the array (NUM. begin ()), we then move on to the next item (it ++) until the iterator's value represents a valid position is different, that is, than that returned by end (). Advancing to the next item, in fact, the iterator points to the next element until the value returned by the method.

Access to the item (4) is obtained using the iterator deferenziando * (* it that is, the element pointed to by it). This way you can operate with the element for example doubles the value in the code proposed.

You can access the individual element by using the method at (). If for example you want to double the 4 position, which can be coded:

numbers.at (4) = numbers.at (4) * 2;



In this case is used as method parameter, the relative position of the item. You must have the element at the specified location. The index should indicate an existing item.

In conclusion can be summarized:

the iterator is used when it comes to sequential access to the elements of the collection

at () method is used if you need direct access to individual items.

The method at provides as a parameter an integer (the position of the element) and cannot therefore be used an iterator. However, you can calculate the relative position of an item within the carrier, knowing the value of the iterator that points to the element:

vector numbers;

vector :: iterator it;

int posRel;

...

for (it = numbers. begin (); it! = numers.end (); it ++) {

posRel = en-numbers. begin (); /*1*/

cout posRel "item location" < < < <;



The position of the element is obtained (1) by subtracting the present value of the iterator (the location in memory of the current item) the position of the first element of the vector. The subtraction between two iterators produces an integer because, as has been noted, iterators, follow the rules of arithmetic. The result of the difference is a number representing how many positions is moved to the current element relative to the position of the first element of the vector.

Use of vector methods

To show the applications of other methods of the vector, is offered a program that gained a vector, for example integers, ordered in ascending order, and an integer, put it inside the carrier, in the place it deserves. The program also allows, in the end, deleting an item, you specify the location, away.

#include <iostream>
#include <vector>
using namespace std;



int main ()

{

vector numbers;

vector: : iterator it,//vector scan process

standard operating procedures; ITER insertion position

const int qelem = 10; quantity elements contained in vector

int i,//loop counter

temp; var. for insertion into the vector

int what,//element to be inserted

p; relative POS items to delete



cout < < "inserts a number to a vector ordered and" < < endl;

cout < < "deletes an item, knowing the location \n\n";



Fill a vector containing 10 elements



cout "inserting sorted items" < < < < endl;

for (i = 0; i < qelem; i + +) {

cout < "element" < < < < < "-->";

CIN >> temp;



check ordering



If (! i | | temp > numbers.at (i-1))/* 1 */

numbers. push_back (temp); /*2*/

else {

cout < < "the sequence must be ordered" < < endl

"Repeat it" < < < < endl;

I--; /*3*/

};

};



cout "element to insert" < <;

CIN >> thing;



Location search



POS = numbers.end ();

for (it = numbers. begin (); it! = numbers.end (); it ++) {

If (thing < (* it)) {/* 4 */

POS = us;

break;

}

}



Inclusion in the found position



If (pos! = numbers.end ())/* 5 */

insert (pos, thing) numbers; /*6*/

else

numbers. push_back (thing); /*7*/



Vector with new element inserted



cout "\nNew carrier" < < endl < <;

for (it = numbers. begin (); it! = numbers.end (); it ++)/* 8 */

cout < * it "\t"; < < <

cout < < endl;



Deleting an element from the vector



cout < < "which positions remove?";

CIN >> p; /*9*/

numbers. erase (numbers. begin () + p); /* 10 */



New view



cout "\nNew carrier" < < endl < <;

for (it = numbers. begin (); it! = numbers.end (); it ++)/* 8 */

cout < * it "\t"; < < <

cout < < endl;



return 0;

}



Is the control in 1 that essentially allows you to determine whether the sequence is increasing. If this is the first element (i.e. If i is 0!) or the input is greater than the previously inserted element (the one with index i-1), queues (2). The last condition it would not make sense for the first item but, for the OR operator (| |), just that the first condition is verified to not proceed further. It uses the at to access the previous item.

If the value entered is greater than the previous one, simply decrementing the loop index (3). This is necessary because, in any case, due to the for construct, the index would be incremented before passing to the control of the cycle. In general it is not a good practice to change, inside a for loop, the variable that controls balance (can lead to errors that are difficult to track down) but here the variable is only used to display the tab order of the element. A better solution might be to use a while loop.

For the inclusion of items in the vector this time it used a for loop being put 10 items. Otherwise the loop is the same as the input loop treated before.

Also research the insertion position is formally identical to that considered in previous examples except (4) that here you find the first element of the vector which has greater value of the item to be inserted. The place, in vector, which the new element will be precisely this. If you found an element of the vector is larger than the value to insert (5) fits the element at that position (6). The insert method takes as its first argument an iterator to the position of insertion, which in this case will be the position of the first element of the vector with greater value. If there is no element of the vector, the new value will be appended (7) to those already present.

Even the erase method for removing an element from the vector, requires an iterator that points to that element. From input (9) you receive the relative position (offset): just (10) add this offset to the value of the pointer to the first element of the vector.

The cycles of 8 dealing with display effects, in vector, the operations carried out.

The string class

Variables of type char allow you to store a single character. If you want to store strings, sequences of characters, such as a word or phrase, you can use the string that contains the class definition string that allows the Declaration of objects of that type.

The string can be thought of as a vector of char and, from this point of view, an object of this class has all the above methods for a generic vector as, for example, deleting characters inside, access to individual characters that are part of it. An object of type string also has useful methods if the carrier is not a generic vector but a string:

length ()


Returns an integer representing the amount of characters in the string

empty ()


Returns a Boolean value indicating if the string is empty (true) or contains at least one character (false)

begin ()


Returns an iterator to the location in memory of the first character in the string

end ()


Returns an iterator to the position after the last character in the string

at ()


Provides access to the character that is in a certain position. You must specify the index as integer in parentheses.

Insert method ()


Allows the insertion of a string anywhere in a different string. In brackets you specify two parameters separated by commas: an insertion position, the string to insert

erase method ()


Allows the deletion of a substring from a string. Must be specified as parameters the starting position from which to delete characters, and the number of characters to delete

Find method ()


Returns an integer that indicates the position in which it was found the specified character. If the search fails, the method returns the value -1. The first parameter, which is required, specifies the character to search for within the string. The second optional parameter is an integer that indicates the position in the string at which to begin searching. If this parameter is not specified, it is assumed by default the starting position of the string (0)

substr ()


Returns a substring extracted. Parameters specify the starting position from which to draw characters, and the number of characters to extract. The characters are not deleted from the string but only copied in the new string

Positions referenced methods are counted from 0 (position of the first character in the string).

To facilitate some processing also in examples of these notes should be added, among the features available to string objects:

stoi ()

stof () stod ()


Features introduced in revision C + +11 to convert a string and return, respectively, an integer, a float or double. Not the methods and the string to convert fits as a parameter. Are used by directly specifying the function name and parameter.

For objects of class string is also known as the string concatenation operator +.

...

String s1, s2, s3;

s1 = "MalwareTips";

s2 = "Forum";

S3 = s1 + s2;

...



After the steps s3 will contain the string "MalwareTips Forum".

Example with strings:

The following program takes a string and a character, and returns the recurrences of the character within the string:

#include

#include /* 1 */

using namespace std;



int main ()

{

string where; /*2*/

char thing; character to search for

int times, pos; anniversaries, character position in the string

bool continues;



input string to search for and character to search for



cout < < "find a character in the string\n"

"and dumps recurrences" < <;



cout "\n\nresearch string\n\n" < <;

getline (cin, where); /*3*/

cout "\nWhat?"; < <

CIN >> thing;



initialize counter occurrences,

character position found and processing cycle control



times = 0;

POS = -1;

continue = true; /*4*/



continue processing until found a recurrence of the character



While (continued) {

POS = where. find (what, pos + 1); /*5*/



If (pos == -1)/* 6 */

continue = false; /*7*/

else

times + +;

}



cout \n\nil "character" what < < < "looks" < < <

"times" times < < < < < < endl;



return 0;

}

In order to declare objects of type string, as in 2, include its library (1).

The input of a string (3) could be made as to elementary variables using the extraction operator from the channel. This is fine if the string supplied as input are not special characters like the space character. In this case, as previously noted, the two parts of the string on the sides of the space would be perceived as two different inputs. Using the getline function can be gained a string containing special characters such as space or punctuation characters up (by default) to Send character terminating the string input. The function you use specifying in brackets at least two parameters: the channel from where to read and the variable to contain the characters from the channel. The third parameter, optional and not used in the examples, specifies the character that is meant as a string terminator. Unless that character is the character enter.

Assigning a value to a string is performed by means of the usual operator =, you only need to enclose the string between double quotes (where = "test string". In string comparison using the usual operators (<, < =, >, > =, ==,! =).

The Boolean variable continues, initialized in 4, check out the next cycle.

The find message, sent in 5 to the string where, in charge of trying the first parameter placed in parentheses, starting from the location specified as the second parameter. The result of this research comes as an integer value that is stored in pos. The starting position is 0 (the first character of the string: pos is initialized to -1 and, as a parameter, you are provided with pos + 1). Subsequent searches will begin at the next location to that found earlier.

If you do not find further recurrences, the member function find associated with where, provides the value -1 (6), and processing may end: the 7 makes sure to make false the loop control condition.

Previous article here: [Tutorial] How to start programming in C++ (Part 3)

Thanks for reading! ;)

I used Quote function to insert the code, to avoid view problems.
 

Razor555

Level 5
Verified
Sep 15, 2014
246
Yes, I made some threads, anyway even if I used Quote function, I don't understand why, when I write "#include..." to import libraries
there are some problems: when I post the thread, it becomes "#include", without the imported library.

Don't know any languages of that sort so you are asking the wrong person... Plus for the moment I am too lazy to even learn it.. :p
 

Avra_Neel

New Member
Apr 6, 2016
1
Your articles are good...by the way,you may even let users know of some good books to follow,like the C++ Primer,5th Edition, on this subject.It'll help them get a good grasp on the language.
 

JM Safe

Level 39
Thread author
Verified
Top Poster
Apr 12, 2015
2,882
Your articles are good...by the way,you may even let users know of some good books to follow,like the C++ Primer,5th Edition, on this subject.It'll help them get a good grasp on the language.
This is a tutorial done by me, not a post to share books links, anyway, maybe I can suggest a good C++ book in the next thread. ;)
 

About us

  • MalwareTips is a community-driven platform providing the latest information and resources on malware and cyber threats. Our team of experienced professionals and passionate volunteers work to keep the internet safe and secure. We provide accurate, up-to-date information and strive to build a strong and supportive community dedicated to cybersecurity.

User Menu

Follow us

Follow us on Facebook or Twitter to know first about the latest cybersecurity incidents and malware threats.

Top