auto


Keyword: auto

The auto keyword in C++ is used for type inference, allowing the compiler to automatically deduce the type of a variable based on its initializer. This can help make code more concise and easier to read, especially in cases where the type is complex or verbose.

Example1: Basic Usage

#include <iostream>
#include <vector>

int main() {
    int x = 10;
    auto y = x;  // y is automatically deduced to be of type int

    std::vector<int> vec = {1, 2, 3, 4, 5};
    auto it = vec.begin();  // it is of type std::vector<int>::iterator

    for (auto elem : vec) {  // elem is deduced to be of type int
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

Example2: Complex Types

Consider a case where you are working with a map, and you want to iterate over its elements:

include <iostream>
include <map>

int main() {
    std::map<std::string, int> myMap = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};

    // Using auto to simplify iterator declaration
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    return 0;
}

Explanation

Example 3: Auto with Functions

auto can also be used in the context of function return types, especially with C++14 and later, where it can be combined with the decltype keyword or used in a trailing return type:

include <iostream>

auto add(int a, int b) -> int {
    return a + b;
}

int main() {
    auto result = add(5, 10);  // result is deduced to be of type int
    std::cout << "Result: " << result << std::endl;

    return 0;
}

Explanation

Example 4: Auto with Lambda Function

auto is often used in conjunction with lambda expressions, where the return type can be complex or unnecessary to specify explicitly

include <iostream>
include <vector>
include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    auto square = [](int x) { return x * x; };

    std::vector<int> squares;
    std::transform(numbers.begin(), numbers.end(), std::back_inserter(squares), square);

    for (auto num : squares) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

Explanation

Summary

Example 5: Usage with reference to const

include <iostream>

int main() {
    int x = 5;
    const int& ref_x = x;

    auto y = ref_x;    // y is an int (copy of x)
    auto& z = ref_x;   // z is a const int& (reference to x)

    std::cout << "y: " << y << std::endl;  // Outputs: y: 5
    std::cout << "z: " << z << std::endl;  // Outputs: z: 5

    return 0;
}

Explanation:

Summary

Previous Page | Course Schedule | Course Content