Map cbegin() and cend() function in C++ STL
In this article, we will discuss the cbegin() and cend() functions in C++ with their syntaxes, examples, applications, and benefits.
What is cbegin() function?
The cbegin() function of the C++ STL (Standard Template Library) is used to get a constant iterator pointing to a container's beginning. It is offered for most common containers, including vector, list, set, map, etc. This function doesn't require any parameters.
Syntax:
It has the following syntax:
newmap.cbegin();
Return value: A constant iterator with read-only access to the container's elements results from the cbegin() method. It implies that using the returned iterator to alter the elements is impossible.
Example:
Let us see a simple example to understand the use of the cbegin() function in C++:
#include<iostream>
#include<map>
using namespace std;
int main()
{
map<int, string> map1;
// INSERTING FLOWERS NAMES
map1.insert({ 1, "JASMINE" });
map1.insert({ 2, "ROSE" });
map1.insert({ 3, "LILLY" });
map1.insert({ 4, "MARIEGOLD" });
map1.insert({ 5, "SUNFLOWER" });
auto it = map1.cbegin();
cout << "SNO\tFLOWERS\n";
for (auto it = map1.cbegin(); it != map1.cend(); it++)
{
cout << it->first<< '\t' << it->second << '\n';
}
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl1.png)
Example 2:
#include <iostream>
#include <map>
using namespace std;
int main (){
map<int, string> MyMap;
map<int, string>::const_iterator cit;
MyMap[50] = "c";
MyMap[51] = "c++";
MyMap[52] = "java";
MyMap[53] = "python";
MyMap[54] = "ruby";
cit = MyMap.cbegin();
cout<<cit->first<<" "<<cit->second<<"\n";
cit++;
cout<<cit->first<<" "<<cit->second<<"\n";
cit++;
cout<<cit->first<<" "<<cit->second<<"\n";
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl2.png)
Applications of Map cbegin() function in C++ STL:
In many scenarios where you need read-only access to the elements of a container, the C++ STL's cbegin() function comes in handy. It returns a constant iterator that forbids access to the elements of the container while iterating through it. The following are some typical uses of the cbegin() function in C++ STL:
- Debugging and logging: The cbegin() function will prevent you from unintentionally changing the container while analyzing its elements when you need to print a container's contents for debugging or logging purposes.
Example:
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int,string> myMap = {{1, "tutorial"}, {2, "and"}, {3, "example"}};
// Printing the contents of the map using cbegin() and cend().
for (auto it = myMap.cbegin(); it != myMap.cend(); ++it) {
cout << "Key: " << it->first << ", Value: " << it->second << endl;
}
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl3.png)
- Looping through a container in a read-only manner: Reading only when iterating through a container. Without running the danger of unintentionally changing a container's elements, you can iterate over its elements by using cbegin() and cend() function in a range-based for loop.
Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myVector = {1, 2, 3};
// Using cbegin() and cend() with range-based for loop to read the elements.
for (const auto& element : myVector) {
cout << element << " ";
}
return 0;
}
Output:
1, 2, 3
- Algorithmic functions: Iterators are a standard input for many algorithms in the C++ STL. You can give constant iterators to these algorithms to carry out read-only operations on containers by using the cbegin() function.
Example:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> myVector = {10, 1, 6, 2, 11};
// Using min_element with cbegin() to find the minimum element in the vector.
auto minElementIt = std::min_element(myVector.cbegin(), myVector.cend());
cout << "Minimum element: " << *minElementIt << std::endl; // Output: 1
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl4.png)
- Concurrency and multi-threading: When a container is accessed by several threads, utilizing the cbegin() function can give read-only access and guarantee safety when several threads read the same data at once.
In conclusion, the cbegin() function is especially helpful when you want to ensure that a container's elements are accessible in a read-only way, preventing erroneous alterations during iteration or when handing iterators to read-only algorithms.
Benefits of Map cbegin() function in C++ STL:
The C++ STL's cbegin() method has several advantages when working with containers. The following are a few significant advantages of using cbegin() in C++ STL:
- Thread safety: Read-only access to containers in multi-threaded programs can enhance thread safety. By using the cbegin() function, you can prevent data races and other synchronization problems brought on by concurrent read operations from various threads.
- Algorithm safety: Many C++ STL algorithms call for constant iterators for read-only operations. Bypassing the necessary iterators to these methods using the cbegin() function, you can avoid accidental changes to the container.
- Read-only access: It is ensured via the constant iterator that cbegin() returns, guaranteeing read-only access to the container's elements. It is helpful if you want to loop through the container without running the danger of changing any of its components unintentionally.
- Code readability: The cbegin() function makes your code more legible and self-documenting by explicitly stating that you intend to read the container parts without alteration.
- Compatibility with custom containers: If you develop a custom container or container adapter, you should include a member function called cbegin() that enables read-only access to the elements of your container by the rules of the standard library.
- Consistency with cend(): The cbegin() function is frequently used in conjunction with the cend() function to provide a range for iteration. It offers a straightforward and reliable method of looping across the entire container without changing its contents.
- Avoiding unintentional changes: When you use the cbegin() function, the compiler enforces const-correctness, aiding in avoiding unintentional changes to the container. It helps to lower the possibility of making unexpected changes when debugging or maintaining code.
Overall, the C++ STL's cbegin() function encourages the development of safer and more reliable code by requiring read-only access to container elements, lowering the possibility of unintentional changes, and guaranteeing compliance with accepted algorithms and practices.
What is the cend() function?
The cend() method in the C++ STL (Standard Template Library) is used to get a constant iterator pointing one place after the last element in a container. Most common containers support it, including vector, list, set, map, etc.
Syntax:
It has the following syntax:
map_name.cend()
Return value:
The container's end is indicated by the constant iterator that the cend() method returns. It should not be used to access or change the value it points to because it is not dereferenceable. When iterating through a container, the cend() function is typically used to specify the end condition of a loop.
Example:
Let us see a simple example to understand the use of the cend() function in C++:
#include <iostream>
#include <map>
using namespace std;
int main (){
map<int, string> MyMap;
map<int, string>::const_iterator cit;
MyMap[50] = "JASMINE";
MyMap[51] = "ROSE";
MyMap[52] = "LILLY";
MyMap[53] = "MARIEGOLD";
MyMap[54] = "SUNFLOWER";
cit = MyMap.cend();
cit--;
cout<<cit->first<<" "<<cit->second<<"\n";
cit--;
cout<<cit->first<<" "<<cit->second<<"\n";
cit--;
cout<<cit->first<<" "<<cit->second<<"\n";
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl5.png)
Applications of Map cend() function in C++ STL:
The C++ STL's cend() function has many uses, especially when dealing with containers and loops. The following are a few typical uses of cend() in C++ STL:
- Loop termination condition: The cend() and cbegin() function are frequently used together to establish the end condition of a loop while iterating through a container. It ensures the loop continues until it reaches the container's conclusion to prevent unauthorized access.
Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myVector = {5, 6, 7, 8, 9};
// Using cbegin() and cend() with a loop to print the elements.
for (auto it = myVector.cbegin(); it != myVector.cend(); ++it)
{
cout << *it << " ";
}
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl6.png)
- Range-based for loops: The end marker for a range-based for loop is implicitly by the cend() function. It assures that the loop iterates across the entire container without the possibility of accessing elements past the end and simplifies the loop syntax.
Example:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myVector = {5,6,7,8,9};
// Using a range-based for loop to print the elements.
for (const auto& element : myVector) {
cout << element << " ";
}
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl7.png)
- Algorithmic operations: The C++ STL's many algorithms demand the input of constant iterators. When using these algorithms for read-only operations, the cend() function is used to specify the end of a range.
Example:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> myVector = {5, 3, 1, 4, 2};
// Using find with cbegin() and cend() to search for an element
auto it = find(myVector.cbegin(), myVector.cend(), 2);
if (it != myVector.cend()) {
cout << "Element found: " << *it << std::endl;
}
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl8.png)
- Thread safety: When accessing a container from different threads in multi-threaded applications, the cend() function ensures that each thread uses the same end marker for its iterations, lowering the chance of data races.
- Debugging and logging: For logging or debugging reasons, the cend() function is helpful for printing a container's contents. It works best when paired with the cbegin() function to loop through the entire container.
Example:
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, std::string> myMap = {{1, "TUTORIAL"}, {2, "AND"}, {3, "EXAMPLE"}};
// Printing the contents of the map using cbegin() and cend().
for (auto it = myMap.cbegin(); it != myMap.cend(); ++it) {
cout << "Key: " << it->first << ", Value: " << it->second <<
endl;
}
return 0;
}
Output:
![Map cbegin() and cend() function in C++ STL](https://static.tutorialandexample.com/cpp/map-cbegin-and-cend-function-in-cpp-stl9.png)
In summary, the cend() function in C++ STL is a crucial tool for defining loop termination conditions, indicating the end of a range in algorithms, and ensuring safe and efficient container iteration without risking access out-of-bounds. It also contributes to code readability and consistency when working with containers in C++.
Benefits of Map cend() function in C++ STL:
When using containers and loops, the cend() method in the C++ STL has many advantages. The following are some significant advantages of using cend() in C++ STL:
- Thread safety: The cend() function in multi-threaded applications helps to ensure that each thread consistently uses the same end marker when iterating through the container, which promotes thread safety. Data races and synchronization problems are less likely as a result.
- Loop termination safety: The cend() function helps to prevent out-of-bounds access when iterating through a container and ensures the safety of loop termination. It ensures that the loop terminates to prevent ill-defined behavior and potential crashes when it reaches the end of the container.
- Read-only access guarantee: Use of the cend() function clarifies that you are only interested in read-only access to the container elements. Read-only access is guaranteed. It encourages consistency and lowers the possibility of accidental content adjustments to the container during iteration.
- Compatible with container modifications: While the cend() function guarantees read-only access, other non-const iterators, such as those obtained via begin() function or other member functions, can still change the container. It enables you to have read-only access to the container without limiting other actions.
- Clear end marker: The container range's end is explicitly indicated when the cend() function is used. It aids in the readability and clarity of the code by acting as a clear signal for loop termination situations.
- Ease of usage with standard algorithms: Numerous algorithms in the C++ STL execute read-only operations on constant iterators as inputs. You can quickly utilize these techniques with containers by using the cend() function, which improves code reuse and readability.
- Compatibility with custom containers: By including the cend() function in implementing a custom container, you ensure that your container is compatible with standard conventions and algorithms. It increases the flexibility of your container.
- Range-based for loops: The end marker for a range-based for loop is implicitly by the cend() function. It makes loop syntax more straightforward and ensures that you iterate across the entire container without defining the end condition in advance.
- Safety in debugging and logging: Using the cend() function when printing a container's contents assures that you don't unintentionally access or modify elements past the end of the container.
In conclusion, the C++ STL's cend() function has advantages like read-only access, compatibility with accepted algorithms, simplicity in range-based loops, thread safety, and understandable code semantics. It helps encourage const-correctness in your code and assure good and effective container iteration.