C++ Programming Code Examples
C++ > Code Snippets Code Examples
Search for all occurrences of key
/* Search for all occurrences of key */
#include <algorithm>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;
class PC
{
public:
enum PC_type { Dell, HP, IBM, Compaq };
PC( PC_type appliance = Dell, int model = 220,
int serial = 0 );
bool operator<( const PC& rhs ) const;
PC_type appliance() const;
int model() const;
string name() const;
void print() const;
int serial() const;
private:
PC_type appliance_;
int model_;
int serial_;
};
inline
PC::PC( PC::PC_type appliance, int model,
int serial )
: appliance_( appliance ), model_( model ), serial_( serial )
{} // empty
inline
bool PC::operator<( const PC& rhs ) const
{ return appliance() < rhs.appliance() ||
( appliance() == rhs.appliance() && model() < rhs.model() );
}
inline
PC::PC_type PC::appliance() const
{ return appliance_; }
inline
int PC::model() const
{ return model_; }
string PC::name() const
{
string what;
switch( appliance() )
{
case Dell: what = "Dell"; break;
case HP: what = "HP"; break;
case IBM: what = "IBM"; break;
case Compaq: what = "Compaq"; break;
default: what = "Unknown appliance"; break;
}
return what;
}
inline
void PC::print() const
{
char oldfill = cout.fill();
cout << name() << " - Model "
<< model() << ", Serial number "
<< serial() << endl;
}
inline
int PC::serial() const
{ return serial_; }
bool greater_model( const pair<PC::PC_type,PC> p,int min_model );
int main( )
{
const PC::PC_type kind[] = { PC::IBM,PC::IBM, PC::Dell, PC::HP,PC::HP, PC::HP };
const int num_appliances = 3;
vector<PC> v;
for( int i = 0; i < num_appliances; ++i )
v.push_back( PC( kind[i], i, i ) );
map<int,PC> sold;
transform( kind, kind+num_appliances, v.begin(),inserter( sold, sold.end() ),make_pair<int,PC> );
map<int,PC>::const_iterator sold_end = sold.end();
// work with a multimap. key is appliance type, value is PC
typedef multimap<PC::PC_type,PC> PC_multimap_type;
PC_multimap_type stock;
const PC desired( PC::HP );
// load the appliances into the multimap
transform( kind, kind+num_appliances, v.begin(),inserter( stock, stock.end() ), make_pair<PC::PC_type,PC> );
PC_multimap_type::const_iterator stock_end = stock.end();
// search for first occurrence of key
PC_multimap_type::const_iterator spot = stock.find( desired.appliance() );
if( spot != stock_end )
spot->second.print();
else
cout << "Don't have a " << desired.name() << " in stock\n";
}
inline
bool greater_model( const pair<PC::PC_type,PC> p,int min_model )
{ return p.second.model() >= min_model; }
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. Maps are part of the C++ STL (Standard Template Library). Maps are the associative containers that store sorted key-value pair, in which each key is unique and it can be inserted or deleted but cannot be altered. Values associated with keys can be changed. The key values are good for sorting and identifying elements uniquely. The mapped values are for storing content associated with the key. The two may differ in types, but the member type combines them via a pair type that combines both.
Normally cout fills the empty field created by a call to width() with spaces, as shown above. At times you may want to fill the area with other characters, such as asterisks. To do this, you call fill() and pass in as a parameter the character you want used as a fill character. It is used to get/set fill character. The fill character is the character used by output insertion functions to fill spaces when padding results to the field width. Function returns the value of the fill character before the call. Member type char_type is the type of characters used by the stream (i.e., its first class template parameter, charT).
In C++, pair is defined as a container in a header library <utility> which combines the two data elements having either the same data types or different data types. In general, the pair in C++ is defined as a tuple in Python programming language which also can give the output as a combined result of joining the two items specified by the pair container and it consists of the first element will be first and the second element will be second only it cannot be disturbed in the order or sequence of elements specified and are always accessed by the dot operator followed by the keyword "first" and "second" elements respectively. In C++ the pair is a container in <utility> header and is also a container class in STL (Standard Template Library) which uses "std" namespace so it will be as std::pair template class for demonstrating pair as a tuple.
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.
Construct insert iterator. Constructs an insert iterator that inserts new elements into x in successive locations starting at the position pointed by it. An insert interator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at a specific position in the container. The type of x needs to have an insert member function (such as most standard containers). Using the assignment operator on the returned iterator (either dereferenced or not), causes insert to be called on the container, attempting to insert one element at the current insert position with the value assigned. This effectively expands the container by one element when successful.
Return iterator to end. Returns an iterator referring to the past-the-end element in the multimap container. multimap::end() is a built-in function in C++ STL which returns an iterator to the theoretical element that follows last element in the multimap. Since multimap container contains the element in an ordered way, end() will point to that theoretical position which follows the last element according to the container's sorting criterion. The past-the-end element is the theoretical element that would follow the last element in the multimap container. It does not point to any element, and thus shall not be dereferenced.
Inline function is one of the important feature of C++. So, let's first understand why inline functions are used and what is the purpose of inline function? When the program executes the function call instruction the CPU stores the memory address of the instruction following the function call, copies the arguments of the function on the stack and finally transfers control to the specified function. The CPU then executes the function code, stores the function return value in a predefined memory location/register and returns control to the calling function. This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run. However, for small, commonly-used functions, the time needed to make the function call is often a lot more than the time needed to actually
Enumeration is a user defined datatype in C/C++ language. It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword "enum" is used to declare an enumeration. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The C++ enum constants are static and final implicitly. C++ Enums can be thought of as classes that have fixed set of constants.
Get type name. name() returns a null-terminated character sequence that may identify the type. The particular representation pointed by the returned value is implementation-defined, and may or may not be different for different types. This function does not accept any parameter.
Return iterator to end. Returns an iterator referring to the past-the-end element in the map container. The past-the-end element is the theoretical element that would follow the last element in the map container. It does not point to any element, and thus shall not be dereferenced. Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with map::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as map::begin.
Return iterator to beginning. Returns an iterator pointing to the first element in the vector. Notice that, unlike member vector::front, which returns a reference to the first element, this function returns a random access iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. The C++ function std::vector::begin() returns a random access iterator pointing to the first element of the vector. This function does not accept any parameter.
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.
Multiple-key map. Multimaps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order, and where multiple elements can have equivalent keys. In a multimap, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. The types of key and mapped value may differ, and are grouped together in member type value_type, which is a pair type combining both. Internally, the elements in a multimap are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).
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.
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. This function does not return any value.
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case in a block of a switch has a different name/number which is referred to as an identifier. The value provided by the user is compared with all the cases inside the switch block until the match is found. If a case match is NOT found, then the default statement is executed, and the control goes out of the switch block. • The expression can be integer expression or a character expression. • Value-1, 2, n are case labels which are used to identify each case individually. Remember that case labels should not be same as it may create a problem while executing a program. Suppose we have two cases with the same label as '1'. Then while executing the program, the case that appears first will be executed even though you want the program to execute a second case. This creates problems in the program and
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. The vector class provides various methods to perform different operations on vectors. Add Elements to a Vector: To add a single element into a vector, we use the push_back() function. It inserts an element into the end of the vector. Access Elements of a Vector: In C++, we use the index number to access the vector elements. Here, we use the at() function to access the element from the specified index.
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.
#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.
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.
The cout is a predefined object of ostream class. It is connected with the standard output device, which is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display the output on a console. On most program environments, the standard output by default is the screen, and the C++ stream object defined to access it is cout. The "c" in cout refers to "character" and "out" means "output". Hence cout means "character output". The cout object is used along with the insertion operator << in order to display a stream of characters.
Get iterator to element. Searches the container for an element with a key equivalent to k and returns an iterator to it if found, otherwise it returns an iterator to multimap::end. multimap::find() is a built-in function in C++ STL which returns an iterator or a constant iterator that refers to the position where the key is present in the multimap. In case of multiple same keys being present, the iterator that refers to one of the keys (typically the first one). In case we wish to get all the items with a given key, we may use equal_range(). If the key is not present in the multimap container, it returns an iterator or a constant iterator which refers to multimap.end(). Notice that this function returns an iterator to a single element (of the possibly multiple elements with equivalent keys). To obtain the entire range of equivalent elements, see multimap::equal_range.
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.
Transform range. Applies an operation sequentially to the elements of one (1) or two (2) ranges and stores the result in the range that begins at result. The transform() function in C++ sequentially applies an operation to the elements of an array(s) and then stores the result in another output array. The transform function is used in two forms: Unary operation: The operation is applied to each element in the input range, and the result is stored in the output array. The transform() function takes the pointer to the starting and ending position of a single input array and to the starting position of the output array.
Program, using recursion, evaluates a Prefix Expression in an "Expression Tree". A binary expression tree is a specific application of a 'binary tree' to evaluate certain expressions.
To 'delete particular words' from the string or sentence in C++ language, enter the string or sentence, and then enter the 'word to delete' all the given/entered word from the sentence
'C++ program' in which user enter a number, program reverse it and display the reversed number on the console. If the 'input number' is 12345 Then reversed number will be 54321