C++ Programming Code Examples
C++ > Computer Graphics Code Examples
C++ Program to Find the Maximum Size Clique in a Graph
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/* C++ Program to Find the Maximum Size Clique in a Graph
This is a C++ Program to find the cliques of size k in a a graph. An undirected graph is formed by a finite set of vertices and a set of unordered pairs of vertices, which are called edges. By convention, in algorithm analysis, the number of vertices in the graph is denoted by n and the number of edges is denoted by m. A clique in a graph G is a complete subgraph of G; that is, it is a subset S of the vertices such that every two vertices in S are connected by an edge in G. A maximal clique is a clique to which no more vertices can be added; a maximum clique is a clique that includes the largest possible number of vertices, and the clique number ?(G) is the number of vertices in a maximum clique of G. */
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
bool removable(vector<int> neighbor, vector<int> cover);
int max_removable(vector<vector<int> > neighbors, vector<int> cover);
vector<int> procedure_1(vector<vector<int> > neighbors, vector<int> cover);
vector<int> procedure_2(vector<vector<int> > neighbors, vector<int> cover,
int k);
int cover_size(vector<int> cover);
ifstream infile("graph.txt");
ofstream outfile("cliques.txt");
int main()
{
//Read Graph (note we work with the complement of the input graph)
cout << "Clique Algorithm." << endl;
int n, i, j, k, K, p, q, r, s, min, edge, counter = 0;
infile >> n;
vector<vector<int> > graph;
for (i = 0; i < n; i++)
{
vector<int> row;
for (j = 0; j < n; j++)
{
infile >> edge;
if (edge == 0)
row.push_back(1);
else
row.push_back(0);
}
graph.push_back(row);
}
//Find Neighbors
vector<vector<int> > neighbors;
for (i = 0; i < graph.size(); i++)
{
vector<int> neighbor;
for (j = 0; j < graph[i].size(); j++)
if (graph[i][j] == 1)
neighbor.push_back(j);
neighbors.push_back(neighbor);
}
cout << "Graph has n = " << n << " vertices." << endl;
//Read maximum size of Clique wanted
cout << "Find a Clique of size at least k = ";
cin >> K;
k = n - K;
//Find Cliques
bool found = false;
cout << "Finding Cliques..." << endl;
min = n + 1;
vector<vector<int> > covers;
vector<int> allcover;
for (i = 0; i < graph.size(); i++)
allcover.push_back(1);
for (i = 0; i < allcover.size(); i++)
{
if (found)
break;
counter++;
cout << counter << ". ";
outfile << counter << ". ";
vector<int> cover = allcover;
cover[i] = 0;
cover = procedure_1(neighbors, cover);
s = cover_size(cover);
if (s < min)
min = s;
if (s <= k)
{
outfile << "Clique (" << n - s << "): ";
for (j = 0; j < cover.size(); j++)
if (cover[j] == 0)
outfile << j + 1 << " ";
outfile << endl;
cout << "Clique Size: " << n - s << endl;
covers.push_back(cover);
found = true;
break;
}
for (j = 0; j < n - k; j++)
cover = procedure_2(neighbors, cover, j);
s = cover_size(cover);
if (s < min)
min = s;
outfile << "Clique (" << n - s << "): ";
for (j = 0; j < cover.size(); j++)
if (cover[j] == 0)
outfile << j + 1 << " ";
outfile << endl;
cout << "Clique Size: " << n - s << endl;
covers.push_back(cover);
if (s <= k)
{
found = true;
break;
}
}
//Pairwise Intersections
for (p = 0; p < covers.size(); p++)
{
if (found)
break;
for (q = p + 1; q < covers.size(); q++)
{
if (found)
break;
counter++;
cout << counter << ". ";
outfile << counter << ". ";
vector<int> cover = allcover;
for (r = 0; r < cover.size(); r++)
if (covers[p][r] == 0 && covers[q][r] == 0)
cover[r] = 0;
cover = procedure_1(neighbors, cover);
s = cover_size(cover);
if (s < min)
min = s;
if (s <= k)
{
outfile << "Clique (" << n - s << "): ";
for (j = 0; j < cover.size(); j++)
if (cover[j] == 0)
outfile << j + 1 << " ";
outfile << endl;
cout << "Clique Size: " << n - s << endl;
found = true;
break;
}
for (j = 0; j < k; j++)
cover = procedure_2(neighbors, cover, j);
s = cover_size(cover);
if (s < min)
min = s;
outfile << "Clique (" << n - s << "): ";
for (j = 0; j < cover.size(); j++)
if (cover[j] == 0)
outfile << j + 1 << " ";
outfile << endl;
cout << "Clique Size: " << n - s << endl;
if (s <= k)
{
found = true;
break;
}
}
}
if (found)
cout << "Found Clique of size at least " << K << "." << endl;
else
cout << "Could not find Clique of size at least " << K << "." << endl
<< "Maximum Clique size found is " << n - min << "." << endl;
cout << "See cliques.txt for results." << endl;
return 0;
}
bool removable(vector<int> neighbor, vector<int> cover)
{
bool check = true;
for (int i = 0; i < neighbor.size(); i++)
if (cover[neighbor[i]] == 0)
{
check = false;
break;
}
return check;
}
int max_removable(vector<vector<int> > neighbors, vector<int> cover)
{
int r = -1, max = -1;
for (int i = 0; i < cover.size(); i++)
{
if (cover[i] == 1 && removable(neighbors[i], cover) == true)
{
vector<int> temp_cover = cover;
temp_cover[i] = 0;
int sum = 0;
for (int j = 0; j < temp_cover.size(); j++)
if (temp_cover[j] == 1 && removable(neighbors[j], temp_cover)
== true)
sum++;
if (sum > max)
{
max = sum;
r = i;
}
}
}
return r;
}
vector<int> procedure_1(vector<vector<int> > neighbors, vector<int> cover)
{
vector<int> temp_cover = cover;
int r = 0;
while (r != -1)
{
r = max_removable(neighbors, temp_cover);
if (r != -1)
temp_cover[r] = 0;
}
return temp_cover;
}
vector<int> procedure_2(vector<vector<int> > neighbors, vector<int> cover,
int k)
{
int count = 0;
vector<int> temp_cover = cover;
int i = 0;
for (int i = 0; i < temp_cover.size(); i++)
{
if (temp_cover[i] == 1)
{
int sum = 0, index;
for (int j = 0; j < neighbors[i].size(); j++)
if (temp_cover[neighbors[i][j]] == 0)
{
index = j;
sum++;
}
if (sum == 1 && cover[neighbors[i][index]] == 0)
{
temp_cover[neighbors[i][index]] = 1;
temp_cover[i] = 0;
temp_cover = procedure_1(neighbors, temp_cover);
count++;
}
if (count > k)
break;
}
}
return temp_cover;
}
int cover_size(vector<int> cover)
{
int count = 0;
for (int i = 0; i < cover.size(); i++)
if (cover[i] == 1)
count++;
return count;
}
If Else Statement in C++
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++:
• if statement,
• if...else statement,
• if...else if...else statement,
Syntax for If Statement in C++
if (condition) {
// body of if statement
}
Syntax for If...Else Statement
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
Syntax for If...Else...Else If Statement in C++
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Syntax for If Else If Ladder in C++
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* If Else Statement in C++ Language */
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
#include Directive in C++
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Syntax for #include Directive in C++
#include "user-defined_file"
#include <header_file>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* using #include directive in C language */
#include <stdio.h>
int main()
{
/*
* C standard library printf function
* defined in the stdio.h header file
*/
printf("I love you Clementine");
printf("I love you so much");
printf("HappyCodings");
return 0;
}
Vectors in C++ Language
In C++, vectors are used to store elements of similar data types. However, unlike arrays, the size of a vector can grow dynamically. That is, we can change the size of the vector during the execution of a program as per our requirements. Vectors are part of the C++ Standard Template Library. To use vectors, we need to include the vector header file in our program.
Declaration for Vectors in C++
std::vector<T> vector_name;
Initialization for Vectors in C++
// Vector initialization method 1
// Initializer list
vector<int> vector1 = {1, 2, 3, 4, 5};
// Vector initialization method 2
vector<int> vector3(5, 12);
vector<int> vector2 = {8, 8, 8, 8, 8};
Syntax for Vector Iterators in C++
vector<T>::iterator iteratorName;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* Vectors in C++ language */
// C++ program to illustrate the capacity function in vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> myvector;
for (int i = 1; i <= 5; i++)
myvector.push_back(i);
cout << "Size : " << myvector.size();
cout << "\nCapacity : " << myvector.capacity();
cout << "\nMax_Size : " << myvector.max_size();
// resizes the vector size to 4
myvector.resize(4);
// prints the vector size after resize()
cout << "\nSize : " << myvector.size();
// checks if the vector is empty or not
if (myvector.empty() == false)
cout << "\nVector is not empty";
else
cout << "\nVector is empty";
// Shrinks the vector
myvector.shrink_to_fit();
cout << "\nVector elements are: ";
for (auto it = myvector.begin(); it != myvector.end(); it++)
cout << *it << " ";
return 0;
}
For Loop Statement in C++
In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Syntax of For Loop Statement in C++
for (initialization; condition; update) {
// body of-loop
}
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition.
A new range-based for loop was introduced to work with collections such as arrays and vectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* For Loop Statement in C++ Language */
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers
#include <iostream>
using namespace std;
int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
sum += i;
}
cout << "Sum = " << sum << endl;
return 0;
}
C++ Files and Streams
In C++ programming we are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively. To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is:
• ofstream: This data type represents the output file stream and is used to create files and to write information to files.
• ifstream: This data type represents the input file stream and is used to read information from files.
• fstream: This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. File streams in C++ are basically the libraries that are used in the due course of programming. The programmers generally use the iostream standard library in the C++ programming as it provides the cin and cout methods that are used for reading from the input and writing to the output respectively. In order to read and write from a file, the programmers are generally using the standard C++ library that is known as the fstream.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cin object.
'ifstream' data type of 'fstream' library is used to read the files of C++. But before reading, there are several tasks which are performed sequentially like opening the file, reading and closing it. Different data types are used for the specific purpose. We can simply read the information from the file using the operator ( >> ) with the name of the file. We need to use the fstream or ifstream object in C++ in order to read the file. Reading of the file line by line can be done by simply using the while loop along with the function of ifstream 'getline()'.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* C++ files and streams */
/* writing to a file and reading from a file in C++ language */
#include <fstream>
#include <iostream>
using namespace std;
int main () {
char data[100];
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat");
cout << "Writing to the file" << endl;
cout << "Enter your name: ";
cin.getline(data, 100);
// write inputted data into the file.
outfile << data << endl;
cout << "Enter your age: ";
cin >> data;
cin.ignore();
// again write inputted data into the file.
outfile << data << endl;
// close the opened file.
outfile.close();
// open a file in read mode.
ifstream infile;
infile.open("afile.dat");
cout << "Reading from the file" << endl;
infile >> data;
// write the data at the screen.
cout << data << endl;
// again read the data from the file and display it.
infile >> data;
cout << data << endl;
// close the opened file.
infile.close();
return 0;
}
While Loop Statement in C++
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute, this happens repeatedly until the condition returns false. When condition returns false, the control comes out of loop and jumps to the next statement in the program after while loop.
The important point to note when using while loop is that we need to use increment or decrement statement inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false. This way we can end the execution of while loop otherwise the loop would execute indefinitely. A while loop that never stops is said to be the infinite while loop, when we give the condition in such a way so that it never returns false, then the loops becomes infinite and repeats itself indefinitely.
Syntax for While Loop Statement in C++
while (condition) {
// body of the loop
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* While Loop Statement in C++ language */
// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0) {
// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum is " << sum << endl;
return 0;
}
Vector Library size() Function in C++
Return size. Returns the number of elements in the vector. This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity. vector::size() is a library function of "vector" header, it is used to get the size of a vector, it returns the total number of elements in the vector.
The dynamic array can be created by using a vector in C++. One or more elements can be inserted into or removed from the vector at the run time that increases or decreases the size of the vector. The size or length of the vector can be counted using any loop or the built-in function named size().
Syntax for Vector size() Function in C++
#include <vector>
size_type size() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* get the size of a vector, it returns the total number of elements in the vector by vector::size() library function. */
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Initializing a vector of string type
vector<string> vec = { "Happy", "8)", "Codings" };
// Clearing the vector
// Now size is equal to 0
vec.clear();
// Typecasting vec.size() to int
for (int i = 0; i < (int)vec.size() - 1; i++)
cout << vec[i] << ' ';
cout << "Happy8)Codings";
return 0;
}
Standard Input Stream (cin) in C++
The cin object is used to accept input from the standard input device i.e. keyboard. It is defined in the iostream header file. C++ cin statement is the instance of the class istream and is used to read input from the standard input device which is usually a keyboard. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.
Syntax for Standard Input Stream (cin) in C++
cin >> var_name;
>>
is the extraction operator.
var_name
is usually a variable, but can also be an element of containers like arrays, vectors, lists, etc.
The "c" in cin refers to "character" and "in" means "input". Hence cin means "character input".
The cin object is used along with the extraction operator >> in order to receive a stream of characters.
The >> operator can also be used more than once in the same statement to accept multiple inputs.
The cin object can also be used with other member functions such as getline(), read(), etc. Some of the commonly used member functions are:
• cin.get(char &ch): Reads an input character and stores it in ch.
• cin.getline(char *buffer, int length): Reads a stream of characters into the string buffer, It stops when:
it has read length-1 characters or
when it finds an end-of-line character '\n' or the end of the file eof.
• cin.read(char *buffer, int n): Reads n bytes (or until the end of the file) from the stream into the buffer.
• cin.ignore(int n): Ignores the next n characters from the input stream.
• cin.eof(): Returns a non-zero value if the end of file (eof) is reached.
The prototype of cin as defined in the iostream header file is: extern istream cin; The cin object in C++ is an object of class istream. It is associated with the standard C input stream stdin.
The cin object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed.
After the cin object is constructed, cin.tie() returns &cout. This means that any formatted input operation on cin forces a call to cout.flush() if any characters are pending for output.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* Standard Input Stream (cin) in C++ language */
// cin with Member Functions
#include <iostream>
using namespace std;
int main() {
char name[20], address[20];
cout << "Name: ";
// use cin with getline()
cin.getline(name, 20);
cout << "Address: ";
cin.getline(address, 20);
cout << endl << "You entered " << endl;
cout << "Name = " << name << endl;
cout << "Address = " << address;
return 0;
}
Vector Library push_back() Function in C++
Add element at the end. Adds a new element at the end of the vector, after its current last element. The content of val is copied (or moved) to the new element.
This effectively increases the container size by one, which causes an automatic reallocation of the allocated storage space if -and only if- the new vector size surpasses the current vector capacity.
push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1.
Syntax for Vector push_back() Function in C++
#include <vector>
void push_back (const value_type& val);
void push_back (value_type&& val);
val
Value to be copied (or moved) to the new element. Member type value_type is the type of the elements in the container, defined in vector as an alias of its first template parameter (T).
This function does not return any value.
If a reallocation happens, the storage is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Complexity
Constant (amortized time, reallocation may happen). If a reallocation happens, the reallocation is itself up to linear in the entire size.
Iterator validity
If a reallocation happens, all iterators, pointers and references related to the container are invalidated.
Otherwise, only the end iterator is invalidated, and all iterators, pointers and references to elements are guaranteed to keep referring to the same elements they were referring to before the call.
Data races
The container is modified. If a reallocation happens, all contained elements are modified.
Otherwise, no existing element is accessed, and concurrently accessing or modifying them is safe.
Exception safety
If no reallocations happen, there are no changes in the container in case of exception (strong guarantee).
If a reallocation happens, the strong guarantee is also given if the type of the elements is either copyable or no-throw moveable.
Otherwise, the container is guaranteed to end in a valid state (basic guarantee).
If allocator_traits::construct is not supported with val as argument, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* vector::push_back() is a library function of "vector" header, it is used to insert/add an element at the end of the vector, it accepts an element of the same type and adds the given element at the end of the vector and increases the size of the vector. */
//C++ STL program code example to demonstrate example of vector::push_back() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
//vector declaration
vector<int> v1;
//inserting elements and printing size
cout << "size of v1: " << v1.size() << endl;
v1.push_back(10);
cout << "size of v1: " << v1.size() << endl;
v1.push_back(20);
v1.push_back(30);
v1.push_back(40);
v1.push_back(50);
cout << "size of v1: " << v1.size() << endl;
//printing all elements
cout << "elements of vector v1..." << endl;
for (int x : v1)
cout << x << " ";
cout << endl;
return 0;
}
Namespaces in C++ Language
Consider a situation, when we have two persons with the same name, jhon, in the same class. Whenever we need to differentiate them definitely we would have to use some additional information along with their name, like either the area, if they live in different area or their mother's or father's name, etc.
Same situation can arise in your C++ applications. For example, you might be writing some code that has a function called xyz() and there is another library available which is also having same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.
A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, you can define the context in which names are defined. In essence, a namespace defines a scope.
Defining a Namespace
A namespace definition begins with the keyword namespace followed by the namespace name as follows:
namespace namespace_name {
// code declarations
}
name::code; // code could be variable or function.
Using Directive
You can also avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace.
Discontiguous Namespaces
A namespace can be defined in several parts and so a namespace is made up of the sum of its separately defined parts. The separate parts of a namespace can be spread over multiple files.
So, if one part of the namespace requires a name defined in another file, that name must still be declared. Writing a following namespace definition either defines a new namespace or adds new elements to an existing one:
namespace namespace_name {
// code declarations
}
Nested Namespaces
Namespaces can be nested where you can define one namespace inside another name space as follows:
namespace namespace_name1 {
// code declarations
namespace namespace_name2 {
// code declarations
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/* namespaces in C++ language */
// A C++ code to demonstrate that we can define
// methods outside namespace.
#include <iostream>
using namespace std;
// Creating a namespace
namespace ns
{
void display();
class happy
{
public:
void display();
};
}
// Defining methods of namespace
void ns::happy::display()
{
cout << "ns::happy::display()\n";
}
void ns::display()
{
cout << "ns::display()\n";
}
// Driver code
int main()
{
ns::happy obj;
ns::display();
obj.display();
return 0;
}
Vector Relational Operators in C++
Relational operators for vector. Performs the appropriate comparison operation between the vector containers lhs and rhs. In C++, relational and logical operators compare two or more operands and return either true or false values.
The equality comparison (operator==) is performed by first comparing sizes, and if they match, the elements are compared sequentially using operator==, stopping at the first mismatch (as if using algorithm equal).
The less-than comparison (operator<) behaves as if using algorithm lexicographical_compare, which compares the elements sequentially using operator< in a reciprocal manner (i.e., checking both a<b and b<a) and stopping at the first occurrence.
Syntax for Vector Relational Operators in C++
#include <vector>
//(1)
template <class T, class Alloc>
bool operator== (const vector<T,Alloc>& lhs, const vector<T,Alloc>& rhs);
//(2)
template <class T, class Alloc>
bool operator!= (const vector<T,Alloc>& lhs, const vector<T,Alloc>& rhs);
//(3)
template <class T, class Alloc>
bool operator< (const vector<T,Alloc>& lhs, const vector<T,Alloc>& rhs);
//(4)
template < class T, class Alloc>
bool operator<= (const vector<T,Alloc>& lhs, const vector<T,Alloc>& rhs);
//(5)
template <class T, class Alloc>
bool operator> (const vector<T,Alloc>& lhs, const vector<T,Alloc>& rhs);
//(6)
template <class T, class Alloc>
bool operator>= (const vector<T,Alloc>& lhs, const vector<T,Alloc>& rhs);
lhs, rhs
vector containers (to the left- and right-hand side of the operator, respectively), having both the same template parameters (T and Alloc).
The other operations also use the operators == and < internally to compare the elements, behaving as if the following equivalent operations were performed:
operation and equivalent operation
• a!=b !(a==b)
• a>b b<a
• a<=b !(b<a)
• a>=b !(a<b)
These operators are overloaded in header <vector>.
Function returns true if the condition holds, and false otherwise.
Complexity
For (1) and (2), constant if the sizes of lhs and rhs differ, and up to linear in that size (equality comparisons) otherwise.
For the others, up to linear in the smaller size (each representing two comparisons with operator<).
Iterator validity
No changes
Data races
Both containers, lhs and rhs, are accessed. Up to all of their contained elements may be accessed. In any case, the function cannot modify its arguments (const-qualified).
Exception safety
If the type of the elements supports the appropriate operation with no-throw guarantee, the function never throws exceptions (no-throw guarantee).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* Relational and equality operators (<, <=, >, >=, ==, !=) are defined to operate on scalars and produce scalar Boolean results. For vector results, use the following built-in functions. In all cases, the sizes of all the input and return vectors for any particular call must match. */
/* vector comparisons by vector relational operators code example */
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> foo (3,100); // three ints with a value of 100
std::vector<int> bar (2,200); // two ints with a value of 200
if (foo==bar) std::cout << "foo and bar are equal\n";
if (foo!=bar) std::cout << "foo and bar are not equal\n";
if (foo< bar) std::cout << "foo is less than bar\n";
if (foo> bar) std::cout << "foo is greater than bar\n";
if (foo<=bar) std::cout << "foo is less than or equal to bar\n";
if (foo>=bar) std::cout << "foo is greater than or equal to bar\n";
return 0;
}
main() Function in C++
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Syntax for main() Function in C++
void main()
{
............
............
}
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library.
In place of void we can also use int return type of main() function, at that time main() return integer type value.
1) It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
b) its address cannot be taken
2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace).
3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static.
4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.
5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program).
6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed).
7) (since C++20) The main function cannot be a coroutine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* simple code example by main() function in C++ */
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}
Break Statement in C++
Break statement in C++ is a loop control statement defined using the break keyword. It is used to stop the current execution and proceed with the next one. When a compiler calls the break statement, it immediately stops the execution of the loop and transfers the control outside the loop and executes the other statements. In the case of a nested loop, break the statement stops the execution of the inner loop and proceeds with the outer loop. The statement itself says it breaks the loop. When the break statement is called in the program, it immediately terminates the loop and transfers the flow control to the statement mentioned outside the loop.
Syntax for Break Statement in C++
// jump-statement;
break;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* break statement with while loop code example */
// program to find the sum of positive numbers
// if the user enters a negative numbers, break ends the loop
// the negative number entered is not added to sum
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
while (true) {
// take input from the user
cout << "Enter a number: ";
cin >> number;
// break condition
if (number < 0) {
break;
}
// add all positive numbers
sum += number;
}
// display the sum
cout << "The sum is " << sum << endl;
return 0;
}
Logical Operators in C++
Logical Operators are used to compare and connect two or more expressions or variables, such that the value of the expression is completely dependent on the original expression or value or variable.
We use logical operators to check whether an expression is true or false. If the expression is true, it returns 1 whereas if the expression is false, it returns 0.
Assume variable A holds 1 and variable B holds 0:
&&
Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false.
The logical AND operator && returns
true - if and only if all the operands are true.
false - if one or more operands are false.
||
Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true.
The logical OR operator || returns
true - if one or more of the operands are true.
false - if and only if all the operands are false.
!
Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make false. !(A && B) is true.
The logical NOT operator ! is a unary operator i.e. it takes only one operand.
It returns true when the operand is false, and false when the operand is true.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* The operator ! is the C++ operator for the Boolean operation NOT. It has only one operand, to its right, and inverts it, producing false if its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean value of evaluating its operand.
The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The operator && corresponds to the Boolean logical operation AND, which yields true if both its operands are true, and false otherwise. */
#include <iostream>
using namespace std;
main() {
int a = 5;
int b = 20;
int c ;
if(a && b) {
cout << "Line 1 - Condition is true"<< endl ;
}
if(a || b) {
cout << "Line 2 - Condition is true"<< endl ;
}
/* Let's change the values of a and b */
a = 0;
b = 10;
if(a && b) {
cout << "Line 3 - Condition is true"<< endl ;
} else {
cout << "Line 4 - Condition is not true"<< endl ;
}
if(!(a && b)) {
cout << "Line 5 - Condition is true"<< endl ;
}
return 0;
}
If Else If Ladder in C/C++
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements.
In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
Syntax of if...else Ladder in C++
if (Condition1)
{ Statement1; }
else if(Condition2)
{ Statement2; }
.
.
.
else if(ConditionN)
{ StatementN; }
else
{ Default_Statement; }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* write a C program which demonstrate use of if-else-if ladder statement */
/* Program to Print Day Names using Else If Ladder in C++*/
#include <iostream>
using namespace std;
int main()
{
int day;
cout << "Enter Day Number: ";
cin >> day;
cout << "Day is ";
if (day == 1)
cout << "Sunday" << endl;
else if (day == 2)
cout << "Monday" << endl;
else if (day == 3)
cout << "Tuesday" << endl;
else if (day == 4)
cout << "Wednesday" << endl;
else if (day == 5)
cout << "Thursday" << endl;
else if (day == 6)
cout << "Friday" << endl;
else
cout << "Saturday" << endl;
return 0;
}
Vector Library Operator Index [] in C++
Access element. Returns a reference to the element at position n in the vector container.
A similar member function, vector::at, has the same behavior as this operator function, except that vector::at is bound-checked and signals if the requested position is out of range by throwing an out_of_range exception.
Portable programs should never call this function with an argument n that is out of range, since this causes undefined behavior.
Syntax for Vector Operator Index [] in C++
#include <vector>
reference operator[] (size_type n);
const_reference operator[] (size_type n) const;
n
Position of an element in the container. Notice that the first element has a position of 0 (not 1). Member type size_type is an unsigned integral type.
Function returns the element at the specified position in the vector.
If the vector object is const-qualified, the function returns a const_reference. Otherwise, it returns a reference.
Member types reference and const_reference are the reference types to the elements of the container (see vector member types).
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). The reference returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
If the container size is greater than n, the function never throws exceptions (no-throw guarantee). Otherwise, the behavior is undefined.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* Returns a reference to the element at specified location pos. No bounds checking is performed. Unlike std::map::operator[], this operator never inserts a new element into the container. Accessing a nonexistent element through this operator is undefined behavior. */
/* Access element from a vector by vector::operator[] code example */
#include <iostream>
#include <vector>
int main ()
{
std::vector<int> myvector (10); // 10 zero-initialized elements
std::vector<int>::size_type sz = myvector.size();
// assign some values:
for (unsigned i=0; i<sz; i++) myvector[i]=i;
// reverse vector using operator[]:
for (unsigned i=0; i<sz/2; i++)
{
int temp;
temp = myvector[sz-1-i];
myvector[sz-1-i]=myvector[i];
myvector[i]=temp;
}
std::cout << "myvector contains:";
for (unsigned i=0; i<sz; i++)
std::cout << ' ' << myvector[i];
std::cout << '\n';
return 0;
}
Nested Loop Statement in C++
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
A loop inside another loop is called a nested loop. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.
Syntax for Nested Loop Statement in C++
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* nested loop statement in C++ language */
// C++ program that uses nested for loop to print a 2D matrix
#include <bits/stdc++.h>
using namespace std;
#define ROW 3
#define COL 3
// Driver program
int main()
{
int i, j;
// Declare the matrix
int matrix[ROW][COL] = { { 4, 8, 12 },
{ 16, 20, 24 },
{ 28, 32, 36 } };
cout << "Given matrix is \n";
// Print the matrix using nested loops
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++)
cout << matrix[i][j];
cout << "\n";
}
return 0;
}