C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
Multimap swap - Swaps all the elements of the multimap container with
Multimap swap - Swaps all the elements of the multimap container with
swap
Header
<map>
void swap(multimap& x)
Swaps all the elements of the multimap container with the elements of x.
Sample
#pragma warning(disable: 4786)
#include <map>
#include <iostream>
#include <string>
typedef std::multimap<char, std::string> multimap_INT_STR ;
typedef multimap_INT_STR::iterator multimap_ITERATOR ;
typedef multimap_INT_STR::reverse_iterator multimap_REVERSE_ITERATOR ;
typedef std::pair<char, std::string> PAIR_INT_STR ;
template <class ITERATOR>
void print_multimap_item(ITERATOR it)
{
std::cout << (*it).first << ", " <<
(*it).second << std::endl ;
}
int main()
{
//default constructor
multimap_INT_STR c1 ;
PAIR_INT_STR pairs[5] = { PAIR_INT_STR('a', std::string("ATL")),
PAIR_INT_STR('a', std::string("ADO")),
PAIR_INT_STR('b', std::string("BASIC")),
PAIR_INT_STR('c', std::string("COM")),
PAIR_INT_STR('d', std::string("DAO"))
};
//construct from a range
multimap_INT_STR c2(pairs, pairs + 5) ;
//copy constructor
multimap_INT_STR c3(c2) ;
//empty
if(c1.empty())
{
std::cout << "c1 is empty" << std::endl ;
}
else
{
std::cout << "c1 is not empty" << std::endl ;
}
//begin, end
std::cout << "c2 (using begin, end) = " << std::endl ;
multimap_ITERATOR Iter1 ;
for(Iter1 = c2.begin(); Iter1 != c2.end(); Iter1++)
{
print_multimap_item(Iter1) ;
}
//rbegin, rend
std::cout << "c2 (using rbegin, rend) = " << std::endl ;
multimap_REVERSE_ITERATOR RevIter1 ;
for(RevIter1 = c2.rbegin(); RevIter1 != c2.rend(); RevIter1++)
{
print_multimap_item(RevIter1) ;
}
//insert
Iter1 = c1.insert(multimap_INT_STR::value_type('i', std::string("Internet"))) ;
if(Iter1 != c1.end())
{
std::cout << "a pair of key/data was inserted in c1, *Iter1 = " ;
print_multimap_item(Iter1);
}
else
{
std::cout << "pair('i', \"Internet\") was not inserted in c1" << std::endl ;
}
c1.insert(pairs, pairs + 5) ;
c1.insert(c1.begin(), PAIR_INT_STR('j', std::string("java"))) ;
//find
std::cout << "Does c1 contain any pair with key = j?" << std::endl ;
Iter1 = c1.find('j') ;
if(Iter1 != c1.end())
{
std::cout << "c1 contains pair:" ;
print_multimap_item(Iter1) ;
}
else
{
std::cout << "c1 does not contain any element with key = j" << std::endl ;
}
//max_size
std::cout << "max elements which c1 can hold uisng current allocator = "
<< c1.max_size() << std::endl ;
//size
std::cout << "number of elements in c1 = " << c1.size() << std::endl ;
//swap
c1.swap(c2) ;
std::cout << "Last key/data pair in c1 = " ;
print_multimap_item(c1.rbegin()) ;
//clear
c3.clear() ;
std::cout << "after calling c3.clear(), number of elements in c3 = "
<< c3.size() << std::endl ;
//get_allocator
multimap_INT_STR::allocator_type a1 = c3.get_allocator() ;
//key_comp
multimap_INT_STR::key_compare kc = c1.key_comp() ;
std::cout << "use function object kc to find less of ('a', 'b')..."
<< std::endl ;
if (kc('a', 'b') == true)
std::cout << "kc('a', 'b') == true, which means 'a' < 'b'" << std::endl ;
else
std::cout << "kc('a', 'b') == false, which means 'a' > 'b'" << std::endl ;
//value_comp
multimap_INT_STR::value_compare vc = c1.value_comp() ;
std::cout << "use function object vc to compare char-string pairs..."
<< std::endl ;
std::cout << "pairs[0] = (" << pairs[0].first << ", "
<< pairs[0].second << ")" << std::endl ;
std::cout << "pairs[1] = (" << pairs[1].first << ", "
<< pairs[1].second << ")" << std::endl ;
if ( vc(pairs[0], pairs[1]) == true)
std::cout << "pairs[0] < pairs[1]" << std::endl ;
else
std::cout << "pairs[0] > pairs[1]" << std::endl ;
//upper_bound
Iter1 = c2.upper_bound('c') ;
std::cout << "first multimap element with key > 'c' = " ;
print_multimap_item(Iter1) ;
//lower_bound
Iter1 = c2.lower_bound('c') ;
std::cout << "first multimap element with key 'c' = " ;
print_multimap_item(Iter1) ;
//equal_range
std::pair<multimap_ITERATOR, multimap_ITERATOR> pair2 = c2.equal_range('c') ;
std::cout << "using c2.equal_range('c'),first multimap element with key > 'c' = " ;
print_multimap_item(pair2.second) ;
std::cout << "using c2.equal_range('c'), first multimap element with key = 'c' = " ;
print_multimap_item(pair2.first) ;
//count
std::cout << "number of pairs in c2 with key 'a' = " << c2.count('a') << std::endl ;
//erase
c2.erase(c2.begin()) ;
std::cout << "first key/data pair of c2 is: " ;
print_multimap_item(c2.begin()) ;
c1.erase(c1.begin(), c1.end()) ;
std::cout << "after c1.erase(c1.begin(), c2.end()), number of elements in c1 = "
<< c1.size() << std::endl ;
if(c2.erase('j') == 1)
{
std::cout << "element with key 'j' in c2 was erased" << std::endl ;
}
else
{
std::cout << "c2 does not contain any element with key 'j'" << std::endl ;
}
return 0 ;
}
Program Output
c1 is empty
c2 (using begin, end) =
a, ATL
a, ADO
b, BASIC
c, COM
d, DAO
c2 (using rbegin, rend) =
d, DAO
c, COM
b, BASIC
a, ADO
a, ATL
a pair of key/data was inserted in c1, *Iter1 = i, Internet
Does c1 contain any pair with key = j?
c1 contains pair:j, java
max elements which c1 can hold uisng current allocator = 268435455
number of elements in c1 = 7
Last key/data pair in c1 = d, DAO
after calling c3.clear(), number of elements in c3 = 0
use function object kc to find less of ('a', 'b')...
kc('a', 'b') == true, which means 'a' < 'b'
use function object vc to compare char-string pairs...
pairs[0] = (a, ATL)
pairs[1] = (a, ADO)
pairs[0] > pairs[1]
first multimap element with key > 'c' = d, DAO
first multimap element with key 'c' = c, COM
using c2.equal_range('c'),first multimap element with key > 'c' = d, DAO
using c2.equal_range('c'), first multimap element with key = 'c' = c, COM
number of pairs in c2 with key 'a' = 2
first key/data pair of c2 is: a, ADO
after c1.erase(c1.begin(), c2.end()), number of elements in c1 = 0
element with key 'j' in c2 was erased
The stringstream, ostringstream, and istringstream objects are used for input and output to a string. They behave in a manner similar to fstream, ofstream and ifstream objects. The function str() can be used in two ways. First, it can be used to get a copy of the string that is being manipulated by the current stream string. This is most useful with output strings. The first form (1) returns a string object with a copy of the current contents of the stream. The second form (2) sets s as the contents of the stream, discarding any previous contents. The object preserves its open mode: if this includes ios_base::ate, the writing position is moved to the end of the new sequence. Internally, the function calls the str member of its internal string buffer object.
A C++ template is a powerful feature added to C++. It allows you to define the generic classes and generic functions and thus provides support for generic programming. Generic programming is a technique where generic types are used as parameters in algorithms so that they can work for a variety of data types. We can define a template for a function. For example, if we have an add() function, we can create versions of the add function for adding the int, float or double type values. Where Ttype: It is a placeholder name for a data type used by the function. It is used within the function definition. It is only a placeholder that the compiler will automatically replace this placeholder with the actual data type. class: A class keyword is used to specify a generic type in a template declaration.
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.
This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. A copy of the original iterator (the base iterator) is kept internally and used to reflect the operations performed on the reverse_iterator: whenever the reverse_iterator is incremented, its base iterator is decreased, and vice versa. A copy of the base iterator with the current state can be obtained at any time by calling member base. Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element
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.
Swap content. Exchanges the content of the container by the content of x, which is another multimap of the same type. Sizes may differ. The multimap::swap() is a built-in function in C++ STL which swaps two multimap container. The contents of multimap1 are in multimap2 and contents of multimap2 are in multimap1 after swap() function is called. After the call to this member function, the elements in this container are those which were in x before the call, and the elements of x are those which were in this. All iterators, references and pointers remain valid for the swapped objects. Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function. Whether the internal container allocators are swapped is not defined, unless in the case the appropriate allocator trait indicates explicitly that they shall propagate.
Erase elements. Removes elements from the multimap container. multimap::erase() function is an inbuilt function in C++ STL, which is defined in <map> header file. erase() is used to remove or erase elements from a multimap container. This function can remove or erase the elements by its key, position or the given range. When we run this function the size of the multimap container is reduced by the number of elements being removed. This effectively reduces the container size by the number of elements removed, which are destroyed. The parameters determine the elements removed:
Test whether container is empty. Returns whether the multimap container is empty (i.e. whether its size is 0). multimap::empty() function is an inbuilt function in C++ STL, which is defined in <map>header file. empty() is used to check whether the associated multimap container is empty or not. Function checks if the size of the container is 0 then returns true, else if there are some values then it returns false. No parameter is required. This function does not modify the container in any way.
Return iterator to beginning. Returns an iterator referring to the first element in the multimap container. multimap::begin() is a built-in function in C++ STL which returns an iterator referring to the first element in the multimap container. Since multimap container contains the element in an ordered way, begin() will point to that element that will come first according to the container's sorting criterion. Because multimap containers keep their elements ordered at all times, begin points to the element that goes first following the container's sorting criterion. If the container is empty, the returned iterator value shall not be dereferenced. No parameter is required.
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.
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).
Return reverse iterator to reverse beginning. Returns a reverse iterator pointing to the last element in the container (i.e., its reverse beginning). multimap::rbegin() is a built-in-function in C++ STL which returns an iterator pointing to the last element of the container. Reverse iterators iterate backwards: increasing them moves them towards the beginning of the container. rbegin points to the element preceding the one that would be pointed to by member end. No parameter is required. Function returns a reverse iterator to the reverse beginning of the sequence container.
Insert element. Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. Internally, multimap containers keep all their elements sorted by key following the criterion specified by its comparison object. The elements are always inserted in its respective position following this ordering. The relative ordering of elements with equivalent keys is preserved, and newly inserted elements follow those with equivalent keys already in the container. The parameters determine how many elements are inserted and to which values they are initialized:
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.
Clear content. Removes all elements from the multimap container (which are destroyed), leaving the container with a size of 0. multimap::clear() function is an inbuilt function in C++ STL, which is defined in <map> header file. clear() is used to remove all the content from the associated multimap container. This function removes all the values and makes the size of the container 0. No parameter is required. This function returns nothing.
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.
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.
Templates are powerful features of C++ which allows us to write generic programs. Similar to function templates, we can use class templates to create a single class to work with different data types. Class templates come in handy as they can make our code shorter and more manageable. A class template starts with the keyword template followed by template parameter(s) inside <> which is followed by the class declaration. T is the template argument which is a placeholder for the data type used, and class is a keyword. Inside the class body, a member variable var and a member function functionName() are both of type T.
Return iterator to upper bound. Returns an iterator pointing to the first element in the container whose key is considered to go after k. The multimap::upper_bound(k) is a built-in function in C++ STL which returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to key+1 and element=0. The function uses its internal comparison object (key_comp) to determine this, returning an iterator to the first element for which key_comp(k,element_key) would return true. If the multimap class is instantiated with the default comparison type (less), the function returns an iterator to the first element whose key is greater than k.
Return container size. Returns the number of elements in the multimap container. The multimap::size() is a built-in function in C++ STL which returns the number of elements in the multimap container. Multimap is an ordered data container which implies all its elements are ordered all the time. The function does not accept any parameter. Function returns the number of elements in the container.
Count elements with a specific key. Searches the container for elements with a key equivalent to k and returns the number of matches. Two keys are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the keys are passed as arguments). The C++ multimap::count function returns the number of occurrences of a specified key in the multimap container. The function accepts one mandatory parameter key which specifies the key whose count in multimap container is to be returned.
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.
Return iterator to lower bound. Returns an iterator pointing to the first element in the container whose key is not considered to go before k (i.e., either it is equivalent or goes after). The multimap::lower_bound(k) is a built-in function in C++ STL which returns an iterator pointing to the key in the container which is equivalent to k passed in the parameter. In case k is not present in the multimap container, the function returns an iterator pointing to the immediate next element which is just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to key+1 and element = 0. The function uses its internal comparison object (key_comp) to determine this, returning an iterator to the first element for which key_comp(element_key,k) would return false.
Return key comparison object. Returns a copy of the comparison object used by the container to compare keys. The multimap::key_comp( ) is a function which comes under <map> header file. This function returns a copy of a key comparison object. This is by default a less than an object which works the same as a less than operator <. The object checks the order of the element keys in the multimap container. This function takes the two arguments and checks its keys and returns true if the first element is smaller and should go before the second element, else will return false. By default, this is a less object, which returns the same as operator<. This object determines the order of the elements in the container: it is a function pointer or a function object that takes two arguments of the same type as the element keys, and returns true if the first argument is considered to go before the second in the strict weak ordering it defines, and false otherwise.
Get range of equal elements. Returns the bounds of a range that includes all the elements in the container which have a key equivalent to k. The multimap::equal_range() is a built-in function in C++ STL which returns an iterator of pairs. The pair refers to the bounds of a range that includes all the elements in the container which have a key equivalent to k. If there are no matches with key K, the range returned is of length 0 with both iterators pointing to the first element that has a key considered to go after k according to the container's internal comparison object (key_comp). If no matches are found, the range returned has a length of zero, with both iterators pointing to the first element that has a key considered to go after k according to the container's internal comparison object (key_comp).
Get allocator. Returns a copy of the allocator object associated with the multimap. multimap::get_allocator() function is an inbuilt function in C++ STL, which is defined in <map> header file. get_allocator() is used to allocate the memory chunks to a multimap container. This function returns a copy of the allocator object of the container associated with it. An allocator is an object which is responsible for dynamically memory allocation of a container. No parameter is required.
Return maximum size. Returns the maximum number of elements that the multimap container can hold. The multimap::max_size() is a built-in function in C++ STL which returns the maximum number of elements a multimap container can hold. This is the maximum potential size the container can reach due to known system or library implementation limitations, but the container is by no means guaranteed to be able to reach that size: it can still fail to allocate storage at any point before that size is reached. No parameter is required.
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.
#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.
Return value comparison object. Returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second. The multimap::value_comp() method returns a comparison object that can be used to compare two elements to get whether the key of the first one goes before the second. Here the 1st object compares the object of type std::multimap::type. The arguments taken by this function object are of member type type. It is defined in multimap as an alias of pair. The arguments taken by this function object are of member type value_type (defined in multimap as an alias of pair<const key_type,mapped_type>), but the mapped_type part of the value is not taken into consideration in this comparison.
Return reverse iterator to reverse end. Returns a reverse iterator pointing to the theoretical element right before the first element in the multimap container (which is considered its reverse end). multimap::rend() is a built-in function in C++ STL which returns a reverse iterator pointing to the theoretical element preceding to the first element of the multimap container. The range between multimap::rbegin and multimap::rend contains all the elements of the container (in reverse order). No parameter is required. Function returns a reverse iterator to the reverse end of the sequence container.
See that problem. Even though we have the parent class pointer pointing to the instance of child class, the parent class version of the function is invoked. You may thinking why I