C++ is one of the most widely used programming languages. It's used by millions of programmers every day and is the most preferred language for competitive programming.

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.

        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector <int> arr1 = {1, 2, 3, 4};
    vector <int> arr2 = {};
    vector <float> arr3 = {1.2, 3.8, 3.0, 2.7, 6.6};
 
    cout << "Size of arr1: " << arr1.size() << endl;
    cout << "Size of arr2: " << arr2.size() << endl;
    cout << "Size of arr3: " << arr3.size() << endl;
 
    return 0;
}

Output:

        Size of arr1: 4
Size of arr2: 0
Size of arr3: 5

2. Shuffle an Array

You can shuffle an array in C++ using the shuffle() function.

        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector <int> arr = {1, 2, 3, 4};
    unsigned seed = 0;
 
    cout << "Original array:";
 
    for (int ele: arr)
    {
        cout << ele << " ";
    }
 
    cout << endl;
 
    shuffle(arr.begin(), arr.end(), default_random_engine(seed));
 
    cout << "Shuffled array:";
 
    for (int ele: arr)
    {
        cout << ele << " ";
    }
 
    return 0;
}

Output:

        Original array:1 2 3 4
Shuffled array:2 3 1 4

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.

        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int x = 5, y = 10;
    string str1 = "MakeUseOf", str2 = "MUO";
 
    cout << "Before Swapping: " << endl;
    cout << "x: " << x << endl;
    cout << "y: " << y << endl;
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
 
    swap(x, y);
    swap(str1, str2);
 
    cout << "After Swapping: " << endl;
    cout << "x: " << x << endl;
    cout << "y: " << y << endl;
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
 
    return 0;
}

Output:

        Before Swapping:
x: 5
y: 10
str1: MakeUseOf
str2: MUO
After Swapping:
x: 10
y: 5
str1: MUO
str2: MakeUseOf

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.
        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int num = 4635, sum = 0, temp;
 
    while (num != 0)
    {
        temp = num%10;
        sum = sum+temp;
        num = num/10;
    }
 
    cout << "Sum: " << sum << endl;
    return 0;
}

Output:

        Sum: 18
    

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.

        #include <bits/stdc++.h>
using namespace std;
 
void printVector(vector <int> vec)
{
    for (auto ele: vec)
    {
        cout << ele << " ";
    }
 
    cout << endl;
}
 
int main()
{
    vector <int> vec = {1, 2, 3, 4, 5};
    printVector(vec);
 
    // Method 1: Using Assignment Operator
    vector <int> newVec1 = vec;
    printVector(newVec1);
 
    // Method 2: By passing vector as constructor
    vector <int> newVec2(vec);
    printVector(newVec2);
 
    return 0;
}

Output:

        1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

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.

        #include <bits/stdc++.h> 
using namespace std;
 
int main()
{
    int arr[] = {23, 56, 87, 12, 56};
    int size = sizeof(arr)/sizeof(arr[0]);
 
    cout << "Max element: " << *max_element(arr, arr+size) << endl;
    cout << "Min element: " << *min_element(arr, arr+size) << endl;
 
    return 0;
}

Output:

        Max element: 87
Min element: 12

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.

        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    set<string> st;
 
    st.insert("Make");
    st.insert("Use");
    st.insert("Of");
    st.insert("Of");
 
    for (auto it = st.begin(); it != st.end(); it++)
    {
        cout << *it << " ";
    }
 
    return 0;
}

Output:

        Make Of Use
    

8. Remove Duplicate From String

You can remove the duplicate characters from a string using the following method:

        #include <bits/stdc++.h>
using namespace std;
 
void removeDuplicateCharacters(char str[], int size)
{
    int newIndex=0;
 
    // Traversing through all the characters
    for (int i = 0; i < size; i++)
    {
        int j;
 
        // Traversing loop from the first character to current character
        for (j = 0; j < i; j++)
        {
            if (str[i] == str[j])
            {
                break;
            }
        }
 
        if (j == i)
        {
            str[newIndex++] = str[i];
        }
    }
 
    // After removing duplicates, we make
    // the vacant part of string to null
    str[newIndex] = '\0';
}


int main()
{
    char str[] = "MakeUseOf";
    int size = strlen(str);
 
    cout << "Original String: " << endl;
    cout << str << endl;
 
    removeDuplicateCharacters(str, size);
 
    cout << "New String: " << endl;
    cout << str << endl;
    return 0;
}

Output:

        Original String:
MakeUseOf
New String:
MakeUsOf

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).

        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string str1 = "MakeUseOf";
    cout << "Length of " << str1 << " : " << str1.length() << endl;
 
    string str2 = "lorem ipsum";
    cout << "Length of " << str2 << " : " << str2.size() << endl;
 
    return 0;
}

Output:

        Length of MakeUseOf : 9
Length of lorem ipsum : 11

10. Delete an Element From the Array

You can delete an element from the array using the following approach:

        #include <bits/stdc++.h>
using namespace std;
 
int deleteElementFromArray(int arr[], int size, int elementToBeDeleted)
{
    int i, j;
 
    // Search if elementToBeDeleted is present
    // in the array or not
    for (i = 0; i < size; i++)
    {
        if (arr[i] == elementToBeDeleted)
        {
            break;
        }
    }
 
    // If elementToBeDeleted is found in the array
    if (i < size)
    {
        // We need to reduce the size of the array
        // and shift the rest elements
        size = size - 1;
 
        for (j = i; j < size; j++)
        {
            arr[j] = arr[j+1];
        }
    }
 
    // New array size is returned
    return size;
}
 
void printArrayElements(int arr[], int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << arr[i] << " ";
    }
 
    cout << endl;
}


int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr)/sizeof(arr[0]);
 
    cout << "Original Array: " << endl;
    printArrayElements(arr, size);
 
    int elementToBeDeleted = 3;
    size = deleteElementFromArray(arr, size, elementToBeDeleted);
 
    cout << "New array: " << endl;
    printArrayElements(arr, size);
 
    return 0;
}

Output:

        Original Array:
1 2 3 4 5
New array:
1 2 4 5

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

        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector <int> vec = {1, 2, 3, 4, 5};
 
    // Method 1: Using range for
    for (auto element: vec)
    {
        cout << element << " ";
    }
 
    return 0;
}

Using Indexing

        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector <int> vec = {1, 2, 3, 4, 5};
 
    // Method 2: Using indexing
    for (int i = 0; i < vec.size(); i++)
    {
        cout << vec[i] << " ";
    }
 
    return 0;
}

Using Reference of the Iterator

        #include <bits/stdc++.h>
using namespace std;
 
int main()
{
    vector <int> vec = {1, 2, 3, 4, 5};
 
    // Method 3: Using reference of the iterator
    for (auto it = begin(vec); it != end(vec); it++)
    {
        cout << *it << " ";
    }
 
    return 0;
}

The above three codes will display the same output:

        1 2 3 4 5
    

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.