C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
Set count - Return the number of elements in the set
Set count - Return the number of elements in the set
count
Header
<set>
size_type count(const Key& key) const
Return the number of elements in the set which match key. If key is present, the function returns 1, otherwise returns 0.
Sample
#pragma warning(disable: 4786)
#include <set>
#include <iostream>
int main()
{
//default constructor
std::set<int> c1 ;
int ai[] = {0, 1, 2, 3} ;
//construct from a range
std::set<int> c2(ai, ai + 4) ;
//copy constructor
std::set<int> c3(c2) ;
std::set<int>::iterator Iter ;
std::set<int>::reverse_iterator RevIter ;
//empty
if(c1.empty())
{
std::cout << "set c1 is empty" << std::endl ;
}
else
{
std::cout << "set c1 is not empty" << std::endl ;
}
//begin, end
std::cout << "c2 (using begin, end) = " ;
for(Iter = c2.begin(); Iter != c2.end(); Iter++)
{
std::cout << *Iter << " " ;
}
std::cout << std::endl ;
//rbegin, rend
std::cout << "c2 (using rbegin, rend) = " ;
for(RevIter = c2.rbegin(); RevIter != c2.rend(); RevIter++)
{
std::cout << *RevIter << " " ;
}
std::cout << std::endl ;
//insert
c1.insert(ai, ai+4) ;
std::pair<std::set<int>::iterator, bool> pr ;
pr = c1.insert(0) ;
if(pr.second == true)
{
std::cout << "element 0 was inserted in c1 successfully" << std::endl ;
}
else
{
std::cout << "element 0 already exists in c1 and *(pr.first) = "
<< *(pr.first) << std::endl ;
}
//find
std::set<int>::const_iterator constIter = c1.find(3) ;
if(constIter != c1.end())
{
std::cout << "c1 contains element 3, *constIter = "
<< *constIter << std::endl ;
}
//max_size
std::cout << "c1.max_size() = " << c1.max_size() << std::endl ;
//size
std::cout << "c1.size() = " << c1.size() << std::endl ;
//swap
c1.insert(4) ;
c2.swap(c1) ;
std::cout << "The last element of c2 = " << *(c2.rbegin())
<< std::endl ;
//clear
c1.clear() ;
std::cout << "After calling c1.clear(), c1.size() = "
<< c1.size() << std::endl ;
//get_allocator
std::set<int>::allocator_type a1 = c1.get_allocator() ;
//key_compare
std::set<int>::key_compare kc = c2.key_comp() ;
bool result = kc(2, 3) ;
if(result == true)
{
std::cout << "kc is function object used by c2. kc(2,3) = true" << std::endl ;
}
else
{
std::cout << "kc is function object used by c2. kc(2,3) = false" << std::endl ;
}
//value_comp
std::set<int>::value_compare vc = c2.value_comp() ;
result = vc(10, 4) ;
if(result == true)
{
std::cout << "vc is function object used by c2. vc(10,4) = true" << std::endl ;
}
else
{
std::cout << "vc is function object used by c2. vc(10,4) = false" << std::endl ;
}
//upper_bound
std::cout << "* (c2.upper_bound(3)) = "
<< *(c2.upper_bound(3)) << std::endl ;
//lower_bound
std::cout << "* (c2.lower_bound(3)) = "
<< *(c2.lower_bound(3)) << std::endl ;
//equal_range
std::pair<std::set<int>::const_iterator, std::set<int>::const_iterator> pr1 = c2.equal_range(3) ;
std::cout << "*(pr1.first) = " << *(pr1.first) << "\t"
<< "*(pr1.second) = " << *(pr1.second) << std::endl ;
//erase
if(c3.erase(1) != 0)
{
std::cout << "c3 does not contain 1 any more" << std::endl ;
}
else
{
std::cout << "No elements in c3 match key 1" << std::endl ;
}
if((c2.erase(c2.begin())) != c2.end())
{
std::cout << "c2 does not contain 0 any more" << std::endl ;
}
else
{
std::cout << "No elements in c2 match key 0" << std::endl ;
}
c3.erase(c3.begin(), c3.end()) ;
std::cout << "after c3.erase(c3.begin(), c3.end()), c3.size() = "
<< c3.size() << std::endl ;
return 0 ;
}
Program Output
set c1 is empty
c2 (using begin, end) = 0 1 2 3
c2 (using rbegin, rend) = 3 2 1 0
element 0 already exists in c1 and *(pr.first) = 0
c1 contains element 3, *constIter = 3
c1.max_size() = 1073741823
c1.size() = 4
The last element of c2 = 4
After calling c1.clear(), c1.size() = 0
kc is function object used by c2. kc(2,3) = true
vc is function object used by c2. vc(10,4) = false
* (c2.upper_bound(3)) = 4
* (c2.lower_bound(3)) = 3
*(pr1.first) = 3 *(pr1.second) = 4
c3 does not contain 1 any more
c2 does not contain 0 any more
after c3.erase(c3.begin(), c3.end()), c3.size() = 0
Return comparison object. The C++ set::key_comp function returns a copy of the comparison object used by the container. By default, it is a less object, which returns the same as operator<. Returns a copy of the comparison object used by the container. 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 container elements, 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 elements of a set are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
#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 iterator to beginning. Returns an iterator referring to the first element in the set container. Because set containers keep their elements ordered at all times, begin points to the element that goes first following the container's sorting criterion. The C++ set::begin function returns the iterator pointing to the first element of the set. Please note that, Set is an ordered data container which implies all its elements are ordered all the time. If the container is empty, the returned iterator value shall not be dereferenced. This function does not accept any parameter.
Get range of equal elements. C++ set equal_range() function is used to return the boundary of the range containing all elements in the container that are equal to val. Since there is no duplication of values in the set container, this range includes at most one element. If val does not match any value in the container, the return value range will be length 0 and both iterators will point to the nearest value greater than val. Otherwise, if val is greater than all elements in the container, it points to end. Returns the bounds of a range that includes all the elements in the container that are equivalent to val. Because all elements in a set container are unique, the range returned will contain a single element at most.
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.
Sets are part of the C++ STL (Standard Template Library). Sets are the associative containers that stores sorted key, in which each key is unique and it can be inserted or deleted but cannot be altered. Sets are containers that store unique elements following a specific order. In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container. Internally, the elements in a set are always sorted following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).
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.
Get allocator. Returns a copy of the allocator object associated with the set. get_allocator() function is an inbuilt function in C++ STL, which is defined in <set> header file. This function returns a copy of the allocator object of the set container associated with it. get_allocator() is used to allocate the memory chunks to a set container. Allocator is an object which is responsible of dynamically memory allocation of a set container. Function accepts no parameter. Function returns the allocator.
Return iterator to end. Returns an iterator referring to the past-the-end element in the set container. end() function returns an iterator pointing to past the last element of the set container. Since it does not refer to a valid element, it cannot de-referenced end() function returns a bidirectional iterator. The past-the-end element is the theoretical element that would follow the last element in the set 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 set::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as set::begin.
upper_bound() returns iterator to upper bound. The set::upper_bound() 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 next of last element (which can be identified using set end() function) in the set container. Returns an iterator pointing to the first element in the container which is considered to go after val. The function uses its internal comparison object (key_comp) to determine this, returning an iterator to the first element for which key_comp(val,element) would return true. If the set class is instantiated with the default comparison type (less), the function returns an iterator to the first element that is greater than val.
Get iterator to element. Searches the container for an element equivalent to val and returns an iterator to it if found, otherwise it returns an iterator to set::end. The set::find is a built-in function in C++ STL which returns an iterator to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set. Two elements of a set 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). Function returns an iterator to the element, if val is found, or set::end otherwise.
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.
Erase elements. Removes from the set container either a single element or a range of elements ([first,last)). C++ set erase() function is used to remove either a single element associated with given key or a range of elements ([first, last)) from the set container. Hence, the size will be reduced by the number of elements removed. This effectively reduces the container size by the number of elements removed, which are destroyed.
Return iterator to lower bound. C++ set lower_bound() function is used to return an iterator pointing to the key in the set container which is equivalent to val passed in the parameter. Returns an iterator pointing to the first element in the container which is not considered to go before val (i.e., either it is equivalent or goes after). The function uses its internal comparison object (key_comp) to determine this, returning an iterator to the first element for which key_comp(element,val) would return false. If the set class is instantiated with the default comparison type (less), the function returns an iterator to the first element that is not less than val.
Return comparison object. The C++ set::value_comp function returns a copy of the comparison object used by the container. By default, it is a less object, which returns the same as operator<. Returns a copy of the comparison object used by the container. 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 container elements, 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 elements of a set are considered equivalent if value_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments).
Return reverse iterator to reverse end. The C++ set::rend function returns the reverse iterator pointing to the element preceding the first element (reversed past-the-last element) of the set. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the set container. Similarly, decreasing a reverse iterator results into moving to the end of the set container. Returns a reverse iterator pointing to the theoretical element right before the first element in the set container (which is considered its reverse end). The range between set::rbegin and set::rend contains all the elements of the container (in reverse order).
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.
Return reverse iterator to reverse beginning. The C++ set::rbegin function returns the reverse iterator pointing to the last element of the set. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the set container. Similarly, decreasing a reverse iterator results into moving to the end of the set container. 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.
Return container size. Returns the number of elements in the set container. set::size() function is a predefined function, it is used to get the size of a set, it returns the total number of elements of the set container. Sets are containers that store unique elements following a specific order. Internally, the elements in a set are always sorted. Sets are typically implemented as binary search trees. This function does not accept any parameter.
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.
Swap content. Exchanges the content of the container by the content of x, which is another set of the same type. Sizes may differ. swap() function is used to exchange the contents of two sets but the sets 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 maximum size. Returns the maximum number of elements that the set 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. max_size() is an inbuilt function in C++ STL which is declared in <set> header file. max_size() returns the maximum size of the set container associated with it. In other words, it returns the maximum size that a container can reach, however there is no guarantee it can allocate the elements of that size, it can still fail to allocate the storage to a specific point of a set container.
Insert element. Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. Because elements in a set are unique, the insertion operation checks whether each inserted element is equivalent to 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). The C++ set::insert function is used to insert new elements in the container. This results into increasing the set size by the number of elements inserted. As the elements in a set are unique, therefore the insertion operation first checks if the inserted element is unique to the set then the element is inserted. For a similar container allowing for duplicate elements, see multiset.
Clear content. Removes all elements from the set container (which are destroyed), leaving the container with a size of 0. set::clear() function is a predefined function, it is used to clear the entire set irrespective of its elements. Erases all elements from the container. After this call, size() returns zero. Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterator remains valid. Function accepts no parameter. Function returns none.
Test whether container is empty. Returns whether the set 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 set container, see set::clear. set::empty() function is a predefined function, it is used to check whether a set is empty or not. If set is empty it returns true, if set is not empty it returns false. Function does not accept any parameter. Function returns true if the container size is 0, false otherwise.
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.
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
To calculate "area and circumference" of any circle in "C++", you have to ask to the user to enter the radius of circle, place the radius in a variable say r and make two variable, one for
C++ Program to generate 'random' numbers using Park-Miller algorithm. general formula of a random number generator (RNG) of this type is: 'X_{k+1} = g X(k) mod n'. To generate
A 'while loop' is used and will terminate when user will press esc key. To get the characters a function 'getche()' is used from conio.h which will store in 'char variable' & store into the file
Program print all the possible combination of each length from the given array in gray code order. The 'time complexity' of this algorithm is 'O(n*(2^n))'. This algorithm takes the input