C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
Binary Search - Returns a boolean value indicating whether or not val was found.
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
Binary Search - Returns a boolean value indicating whether or not val was found.
binary_search
Header
<algorithm>
template<class ForwardIterator, class T>
bool binary_search(ForwardIterator first, ForwardIterator last, const T& val) ;
Returns a boolean value indicating whether or not val was found. A value of true indicates that it was found, false indicates it wasn't present. The non-predicate version of binary_search uses the operator< for comparison.
template<class ForwardIterator, class T, class Predicate>
bool binary_search(ForwardIterator first, ForwardIterator last, const T& val, BinaryPredicate pr) ;
Returns a boolean value indicating whether or not val was found. A value of true indicates that it was found, false indicates it wasn't present. The predicate version of binary_search uses the predicate function pr for comparison.
NOTE: binary_search needs to use the correct ordering function when searching through the input sequence for a match. If the input sequence was ordered using a predicate instead of operator< the same predicate object needs to be passed to binary_search via the BinaryPredicate parameter. If the sequence is not sorted according to the same algorithm used for search, the result is undefined.
Samples
#pragma warning (disable: 4786)
#include <algorithm>
#include <iostream>
#include <string>
struct PhoneBook
{
PhoneBook(std::string s, long num)
{
name = s ;
number = num ;
}
PhoneBook() {}
friend std::ostream& operator<<(std::ostream&, const PhoneBook&) ;
long number ;
std::string name ;
} ;
std::ostream& operator<<(std::ostream& os, const PhoneBook& rpb)
{
os << rpb.name << "\t" << rpb.number << std::endl ;
return os ;
}
bool compare(const PhoneBook& r1, const PhoneBook& r2)
{
return (r2.name > r1.name) ;
}
int main()
{
int Numbers[] = {100, 200, 330, 445, 500} ;
bool results ;
int i ;
std::cout << "Numbers = " ;
for(i = 0; i < 5; i++)
std::cout << Numbers[i] << "\t" ;
std::cout << std::endl ;
//non-predicate version
//does 250 exist in the array Numbers?
results = std::binary_search(Numbers, Numbers+5, 250) ;
if(results == true)
std::cout << "250 exists in array Numbers" << std::endl ;
else
std::cout << "250 does not exist in array Numbers" << std::endl ;
//non-predicate version
//does 445 exist in the array Numbers?
results = std::binary_search(Numbers, Numbers+5, 445) ;
if(results == true)
std::cout << "445 exists in array Numbers" << std::endl ;
else
std::cout << "445 does not exist in array Numbers" << std::endl ;
PhoneBook pb[5] ;
pb[0] = PhoneBook("Frank", 4651234) ;
pb[1] = PhoneBook("Jack", 3456218) ;
pb[2] = PhoneBook("Kevin", 8453445) ;
pb[3] = PhoneBook("Shaun", 4540082) ;
pb[4] = PhoneBook("Tom", 8771235) ;
PhoneBook pb1("Jack", 3456218) ;
std::cout << "Phone Book Entries: " << std::endl ;
for(i = 0; i < 5; i++)
std::cout << pb[i] << std::endl ;
//predicate version
results = std::binary_search(pb, pb+5, pb1, compare) ;
if(results == true)
std::cout << "Jack is listed in the PhoneBook" << std::endl ;
else
std::cout << "Jack is not listed in the PhoneBook" << std::endl ;
return 0 ;
}
Program Output
Numbers = 100 200 330 445 500
250 does not exist in array Numbers
445 exists in array Numbers
Phone Book Entries:
Frank 4651234
Jack 3456218
Kevin 8453445
Shaun 4540082
Tom 8771235
Jack is listed in the PhoneBook
Search range for subsequence. Searches the range [first1,last1) for the first occurrence of the sequence defined by [first2,last2), and returns an iterator to its first element, or last1 if no occurrences are found. The elements in both ranges are compared sequentially using operator== (or pred, in version (2)): A subsequence of [first1,last1) is considered a match only when this is true for all the elements of [first2,last2). This function returns the first of such occurrences. For an algorithm that returns the last instead, see find_end. The function shall not modify any of its arguments.
Test if value exists in sorted sequence. Returns true if any element in the range [first,last) is equivalent to val, and false otherwise. The elements are compared using operator< for the first version, and comp for the second. Two elements, a and b are considered equivalent if (!(a<b) && !(b<a)) or if (!comp(a,b) && !comp(b,a)). The elements in the range shall already be sorted according to this same criterion (operator< or comp), or at least partitioned with respect to val. The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted range, which is specially efficient for random-access iterators.
A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. If a function is defined as a friend function in C++ programming language, then the protected and private data of a class can be accessed using the function. By using the keyword friend compiler knows the given function is a friend function. For accessing the data, the declaration of a friend function should be done inside the body of a class starting with the keyword friend.
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.
#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.
Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result. • Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used.
In C++, classes and structs are blueprints that are used to create the instance of a class. Structs are used for lightweight objects such as Rectangle, color, Point, etc. Unlike class, structs in C++ are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct. C++ Structure is a collection of different data types. It is similar to the class that holds different types of data. A structure is declared by preceding the struct keyword followed by the identifier(structure name). Inside the curly braces, we can declare the member variables of different types.
An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C++ programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C++ array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.
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, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
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.
String is a "sequence of characters". char data type is used to represent one single character in C++. So if you want to use a String in your program then you can use an "array of chars".
As you can see that the output is missing the value 3, however the for loop 'iterate' though the num value 0 to 6. This is because we have set a condition inside loop in such a way, that
This C++ program, using recursion, displays the "Lowest Common Ancestor" in a binary search tree. lowest common ancestor is one in which the lowest common parent node of
Internal method to insert into a subtree. x is the item to insert. t is the node that roots the tree. Set the "New Root". Internal method to remove from subtree. x: the item to remove.