Here, we’ll list 11 C++ code snippets that can help you with your everyday programming problems. So, without further ado, let’s get started.
1. Find the Size of a Vector
You can find the size of a vector using the size() function.
Output:
2. Shuffle an Array
You can shuffle an array in C++ using the shuffle() function.
Output:
3. Swap Two Variables in C++
You can swap two variables in C++ by using the built-in swap() function of the C++ STL library.
Output:
4. Find the Sum of Digits of a Number
You can find the sum of digits of a number using the following process:
Initialize a sum variable to store the result. Find the remainder of the number by performing the modulus operation with 10. Add the remainder with the sum. Divide the number by 10. Repeat the process from step 2 while the number is greater than 10.
Output:
5. Copy a Vector to Another Vector
There are multiple ways to copy a vector to another vector in C++. You can use the assignment operator or pass the vector as a constructor to do the same.
Output:
6. Find the Maximum and Minimum Elements of an Array
You can find the maximum and minimum elements from an array using the max_element() and min_element() functions, respectively.
Output:
7. Insert Elements in a Set
You can insert elements in a set using the insert() function. This function accepts the element as a parameter that will be inserted in the set.
Output:
8. Remove Duplicate From String
You can remove the duplicate characters from a string using the following method:
Output:
9. Find the Length of a C++ String
You can find the length of a C++ string using the length() function. Alternatively, you can also use the size() function (it’s an alias of the length() function).
Output:
10. Delete an Element From the Array
You can delete an element from the array using the following approach:
Output:
Sometimes it isn’t easy to directly understand a complex code. You should follow some of the basic programming principles like documenting the code, refactoring, and so on to make your code more robust.
11. Iterate Through a Vector
You can iterate through a vector in multiple ways. Below are three of the most used ways to iterate through a vector:
Using range for
Using Indexing
Using Reference of the Iterator
The above three codes will display the same output:
If you want to have a look at the complete source code used in this article, here’s the GitHub repository.
Make Use of C++ Code Snippets
Make use of these C++ code snippets for your everyday programming problems. Whether you use C++ for writing simple programs or competitive programming, these code snippets can come in handy.
Alternatively, you should get started with Go if you want to try your hands dirty with robotics, DevOps, cloud programming, data science, or artificial intelligence. Go is an open-source, easy-to-learn programming language with several advantages over other programming languages.