- Examples
Let's look at how auto is being used in two different scenarios.
We'll cover the following...
Replacing basic data types #
Press + to interact
#include <iostream>#include <vector>int func(int){ return 2011;}int main(){auto i = 5;auto& intRef = i; // int&auto* intPoint = &i; // int*const auto constInt = i; // const intstatic auto staticInt = 10; // static intstd::vector<int> myVec;auto vec = myVec; // std::vector<int>auto& vecRef = vec; // std::vector<int>&int myData[10];auto v1 = myData; // int*auto& v2 = myData; // int (&)[10]auto myFunc = func; // (int)(*)(int)auto& myFuncRef = func; // (int)(&)(int)// define a function pointerint (*myAdd1)(int, int) = [](int a, int b){return a + b;};// use type inference of the C++11 compilerauto myAdd2 = [](int a, int b){return a + b;};std::cout << "\n";// use the function pointerstd::cout << "myAdd1(1, 2) = " << myAdd1(1, 2) << std::endl;// use the auto variablestd::cout << "myAdd2(1, 2) = " << myAdd2(1, 2) << std::endl;std::cout << "\n";}