auto/auto2.cc - Sample use of auto in C++11. | Lecture 2 - slide 23 : 29 Program 1 |
// Illustrate various simple uses of auto i C++11 #include <iostream> #include <vector> #include <cmath> // abs #include "point.h" // Illustration of alternative return type - best if return type depends on parameters. auto find_diagonal_points(std::vector<Point> points) -> std::vector<Point>{ std::vector<Point> res; for(auto p: points) if(std::abs(p.getx())==std::abs(p.gety())) res.push_back(p); return res; } void without_auto(){ int i{5}; std::vector<Point> points = {Point{1,1}, Point{1,2}, Point{-1,1}, Point{-2,2}}; std::vector<Point> diagonal_points = find_diagonal_points(points); for(Point p: diagonal_points) std::cout << p << std::endl; } void with_auto(){ auto i = 5; // initialize auto's with =, not {}. auto points = std::vector<Point>{{Point{1,1}, Point{1,2}, Point{-1,1}, Point{-2,2}}}; auto diagonal_points = find_diagonal_points(points); for(auto p: diagonal_points) std::cout << p << std::endl; } int main () { without_auto(); std::cout << std::endl; with_auto(); }