C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
Map clear - Erases the elements of the map container.
Map clear - Erases the elements of the map container.
clear
Header
<map>
void clear() const
Erases the elements of the map container. The member function calls erase(begin(), end()).
Sample
#pragma warning(disable: 4786)
#include <map>
#include <iostream>
#include <string>
typedef std::map<int, std::string> MAP_INT_STR ;
typedef MAP_INT_STR::iterator MAP_ITERATOR ;
typedef MAP_INT_STR::reverse_iterator MAP_REVERSE_ITERATOR ;
typedef std::pair<int, std::string> PAIR_INT_STR ;
template <class ITERATOR>
void print_map_item(ITERATOR it)
{
std::cout << (*it).first << ", " <<
(*it).second << std::endl ;
}
int main()
{
//default constructor
MAP_INT_STR c1 ;
PAIR_INT_STR pairs[5] = { PAIR_INT_STR(1, std::string("one")),
PAIR_INT_STR(2, std::string("two")),
PAIR_INT_STR(3, std::string("three")),
PAIR_INT_STR(4, std::string("four")),
PAIR_INT_STR(5, std::string("five"))
};
//construct from a range
MAP_INT_STR c2(pairs, pairs + 5) ;
//copy constructor
MAP_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 ;
MAP_ITERATOR Iter1 ;
for(Iter1 = c2.begin(); Iter1 != c2.end(); Iter1++)
{
print_map_item(Iter1) ;
}
//rbegin, rend
std::cout << "c2 (using rbegin, rend) = " << std::endl ;
MAP_REVERSE_ITERATOR RevIter1 ;
for(RevIter1 = c2.rbegin(); RevIter1 != c2.rend(); RevIter1++)
{
print_map_item(RevIter1) ;
}
//insert
std::pair<MAP_ITERATOR, bool> result ;
result = c1.insert(MAP_INT_STR::value_type(6, std::string("six"))) ;
if(result.second == true)
{
std::cout << "a pair of key/data was inserted in c1, *(result.first) = " ;
print_map_item(result.first);
}
else
{
std::cout << "pair(6, \"six\") was not inserted in c1" << std::endl ;
}
c1.insert(pairs, pairs + 5) ;
c1.insert(c1.begin(), PAIR_INT_STR(0, std::string("zero"))) ;
//find
std::cout << "Does c1 contain any pair with key = 6?" << std::endl ;
Iter1 = c1.find(6) ;
if(Iter1 != c1.end())
{
std::cout << "c1 contains pair:" ;
print_map_item(Iter1) ;
}
else
{
std::cout << "c1 does not contain any element with key = 6" << std::endl ;
}
//operator[]
c1[8] = "eight" ;
std::cout << "Last key/data pair in c1 = " ;
print_map_item(c1.rbegin()) ;
//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_map_item(c1.rbegin()) ;
//clear
c3.clear() ;
std::cout << "after calling c3.clear(), number of elements in c3 = "
<< c3.size() << std::endl ;
//get_allocator
MAP_INT_STR::allocator_type a1 = c3.get_allocator() ;
//key_comp
MAP_INT_STR::key_compare kc = c1.key_comp() ;
std::cout << "use function object kc to find less of (10, 4)..."
<< std::endl ;
if (kc(10, 4) == true)
std::cout << "kc(10, 4) == true, which means 10 < 4" << std::endl ;
else
std::cout << "kc(10, 4) == false, which means 10 > 4" << std::endl ;
//value_comp
MAP_INT_STR::value_compare vc = c1.value_comp() ;
std::cout << "use function object vc to compare int-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(6) ;
std::cout << "first map element with key > 6 = " ;
print_map_item(Iter1) ;
//lower_bound
Iter1 = c2.lower_bound(6) ;
std::cout << "first map element with key 6 = " ;
print_map_item(Iter1) ;
//equal_range
std::pair<MAP_ITERATOR, MAP_ITERATOR> pair2 = c2.equal_range(6) ;
std::cout << "using c2.equal_range(6),first map element with key > 6 = " ;
print_map_item(pair2.second) ;
std::cout << "using c2.equal_range(6), first map element with key = 6 = " ;
print_map_item(pair2.first) ;
//count
std::cout << "does c2 contain an element with key 8 ?" << std::endl ;
if(c2.count(8) == 1)
{
std::cout << "c2 contains element with key 8" << std::endl ;
}
else
{
std::cout << "c2 does not contain element with key 8" << std::endl ;
}
//erase
c2.erase(c2.begin()) ;
std::cout << "first key/data pair of c2 is: " ;
print_map_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(8) == 1)
{
std::cout << "element with key 8 in c2 was erased" << std::endl ;
}
else
{
std::cout << "c2 does not contain any element with key 8" << std::endl ;
}
return 0 ;
}
Program Output
c1 is empty
c2 (using begin, end) =
1, one
2, two
3, three
4, four
5, five
c2 (using rbegin, rend) =
5, five
4, four
3, three
2, two
1, one
a pair of key/data was inserted in c1, *(result.first) = 6, six
Does c1 contain any pair with key = 6?
c1 contains pair:6, six
Last key/data pair in c1 = 8, eight
max elements which c1 can hold uisng current allocator = 268435455
number of elements in c1 = 8
Last key/data pair in c1 = 5, five
after calling c3.clear(), number of elements in c3 = 0
use function object kc to find less of (10, 4)...
kc(10, 4) == false, which means 10 > 4
use function object vc to compare int-string pairs...
pairs[0] = (1, one)
pairs[1] = (2, two)
pairs[0] < pairs[1]
first map element with key > 6 = 8, eight
first map element with key 6 = 6, six
using c2.equal_range(6),first map element with key > 6 = 8, eight
using c2.equal_range(6), first map element with key = 6 = 6, six
does c2 contain an element with key 8 ?
c2 contains element with key 8
first key/data pair of c2 is: 1, one
after c1.erase(c1.begin(), c2.end()), number of elements in c1 = 0
element with key 8 in c2 was erased
Erase elements. Removes from the map container either a single element or a range of elements ([first,last)). The C++ map::erase function is used to delete either a single element or a range of elements from the map. It reduces the size of the map by number of elements deleted from the container. This effectively reduces the container size by the number of elements removed, which are destroyed.
Return key comparison object. Returns a copy of the comparison object used by the container to compare keys. The C++ function std::map::key_comp() returns a function object that compares the keys, which is a copy of this container's constructor argument comp. The comparison object of a map object is set on construction. Its type (member key_compare) is the third template parameter of the map template. 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. Two keys are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).
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 std::map::value_comp() is a function in C++ STL. It returns a function object that compares objects of type std::map::value. The arguments taken by this function object are of member type value_type (defined in map 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. The comparison object returned is an object of the member type map::value_compare, which is a nested class that uses the internal comparison object to generate the appropriate comparison functional class.
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.
Insert elements. Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. Because element keys in a map are unique, the insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the function returns a value). For a similar container allowing for duplicate elements, see multimap. An alternative way to insert elements in a map is by using member function map::operator[].
Clear content. Removes all elements from the map container (which are destroyed), leaving the container with a size of 0. map::clear() function is an inbuilt function in C++ STL, which is defined in header file. clear() is used to remove all the content from the associated map container. Function removes all the values and makes the size of the container as 0. Function accepts no parameter. Function returns nothing
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
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 map::upper_bound() is a built-in function in C++ STL which returns an iterator pointing to the immediate next element just greater than k. If the key passed in the parameter exceeds the maximum key in the container, then the iterator returned points to the number of elements in the map container as key 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 map 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 maximum size. Returns the maximum number of elements that the map container can hold. The map::max_size() is a built-in function in C++ STL which returns the maximum number of elements a map 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. Function returns the maximum number of elements a map container can hold as content.
Return container size. Returns the number of elements in the map container. map::size() function is an inbuilt function in C++ STL, which is defined in header file. size() is used to check the size of the map container. This function gives size or we can say gives us the number of elements in the map container associated. This function does not accept any parameter. Function returns the number of elements in the container.
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.
Swap content. Exchanges the content of the container by the content of x, which is another map of the same type. Sizes may differ. swap() function is used to exchange the contents of two maps but the maps must be of same type, although sizes may differ. 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.
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.
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.
Get allocator. Returns a copy of the allocator object associated with the map. map::get_allocator() is a built in function in C++ STL which is used to get allocator of container map. The map::get_allocator( ) is a function which comes under <map> header file. get_alloctaor() is used to get the allocator object which is associated with the map container. This function returns the copy of the allocator object of the given map. Function accepts no parameter. Function returns the allocator.
Return reverse iterator to reverse end. Returns a reverse iterator pointing to the theoretical element right before the first element in the map container (which is considered its reverse end). The range between map::rbegin and map::rend contains all the elements of the container (in reverse order). The rend() function is an inbuilt function in C++ STL which returns a reverse iterator pointing to the theoretical element right before the first key-value pair in the map(which is considered its reverse end). This function does not accept any parameter. Function returns a reverse iterator to the reverse end of the sequence container.
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 map::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. 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. If the map class is instantiated with the default comparison type (less), the function returns an iterator to the first element whose key is not less than k.
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.
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 C++ map::equal_range function returns the bounds of a range which includes all elements in the map container with keys that are equivalent to the specified value. It returns a pair, with pair::first member as the lower_bound of the range, and pair::second member as the upper_bound of the range. This contains all elements with key in the range [pair::first, pair::second). Because the elements in a map container have unique keys, the range returned will contain a single element at most. 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).
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.
Test whether container is empty. Returns whether the map container is empty (i.e. whether its size is 0). This function does not modify the container in any way. To clear the content of a map container, see map::clear. map::empty() function is an inbuilt function in C++ STL, which is defined in header file. empty() is used to check whether the associated map container is empty or not. This function checks if the size of the container is 0 then returns true, else if there are some values then it returns false.
Return iterator to beginning. Returns an iterator referring to the first element in the map container. Because map 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. This function does not accept any parameter. Function returns an iterator to the first element in the container. If the map object is const-qualified, the function returns a const_iterator. Otherwise, it returns an iterator.
Access element. If k matches the key of an element in the container, the function returns a reference to its mapped value. This operator is used to reference the element present at position given inside the operator. It is similar to the at() function, the only difference is that the at() function throws an out-of-range exception when the position is not in the bounds of the size of map, while this operator causes undefined behavior. If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value. Notice that this always increases the container size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor). A similar member function, map::at, has the same behavior when an element with the key exists, but throws an exception when it does not.
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 map::end. Two keys are considered equivalent if the container's comparison object returns false reflexively (i.e., no matter the order in which the elements are passed as arguments). Another member function, map::count, can be used to just check whether a particular key exists. The function accepts one mandatory parameter key which specifies the key to be searched in the map container.
#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 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.
Count elements with a specific key. Searches the container for elements with a key equivalent to k and returns the number of matches. The map::count() is a built-in function in C++ STL which returns 1 if the element with key K is present in the map container. It returns 0 if the element with key K is not present in the container. Because all elements in a map container are unique, the function can only return 1 (if the element is found) or zero (otherwise). 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). Function returns 1 if the container contains an element whose key is equivalent to k, or zero otherwise.
Return reverse iterator to reverse beginning. Returns a reverse iterator pointing to the last element in the container (i.e., its reverse beginning). 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. The std::map::rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map. This function does not accept any parameter.
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.
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.
See in this case the output is Woof, which is what we expect. What happens in this case? Since we marked the function animalSound() as virtual, the call to the function is resolved
We create a queue for BFS. Mark the current node as visited and enqueue it. It will be used to get all adjacent vertices of a vertex. Get all adjacent vertices of the dequeued vertex s. If