#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <tuple>
using namespace std;
// nullptr
void F(int a) {
cout << "F(int a):" << a << endl;
}
void F(int *p) {
cout << "F(int *p):" << p << endl;
}
void main() {
// auto
cout << "auto---------------------\n";
{
auto a = "test auto\n";
cout << a;
vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
for (auto itr = v.begin(); itr != v.end(); ++itr) {
cout << *itr << endl;
}
// template <class Product, class Creator>
// void processProduct(const Creator &creator) {
// Product *val = creator.makeObject();
// }
//
// template <class Creator>
// void processProduct(const Creator &creator) {
// auto val = creator.makeObject();
// }
}
// decltype
cout << "decltype---------------------\n";
{
int x = 3;
decltype(x) y = 3;
// template <class Creator>
// auto processProduct(const Creator &creator) -> decltype(creator.makeObject()) {
// auto val = creator.makeObject();
// }
}
// nullptr
cout << "nullptr---------------------\n";
{
int *p = nullptr;
int *q = NULL;
cout << "p equals q: " << (p == q) << endl;
//int a = nullptr; // error
F(0);
F(nullptr);
}
// for
cout << "for---------------------\n";
{
//map<string, int> m {{"a", 1}, {"b", 2}, {"c", 3}};
map<string, int> m; m["a"] = 1; m["b"] = 2; m["c"] = 3;
for (auto p : m) {
cout << p.first << ":" << p.second << endl;
}
}
// lambda
// [Func Object Param](Func Param)->ReturnType {Func Body}
cout << "lambda---------------------\n";
{
//vector<int> v {5, 4, 3, 2, 1};
vector<int> v; v.push_back(5); v.push_back(4); v.push_back(3); v.push_back(2); v.push_back(1);
int a = 2, b = 1;
// can visit global var 'b'
for_each(v.begin(), v.end(), [b](int &x){ cout << (x + b) << endl;});
// [=] means can visit all outer var (by value)
for_each(v.begin(), v.end(), [=](int &x){ x *= (a + b);});
for_each(v.begin(), v.end(), [=](int &x)->int{ return x * (a + b);});
}
// var params length template
cout << "var param len template---------------------\n";
{
auto t1 = make_tuple(1, 2.0, "c++ 11");
//auto t2 = make_tuple(1, 2.0, "c++ 11", {1, 0, 2});
// template <typename head, typename... tail>
// void Print(Head head, typename... tail) {
// cout << head << endl;
// Print(tail...);
// }
}
// init method
cout << "init method---------------------\n";
{
int arr[3] = {1, 2, 3};
vector<int> v(arr, arr + 3);
// int arr1[3] {1, 2, 3};
// vector<int> v1 {1, 2, 3};
// map<int, string> {{1, "a"}, {2, "b"}};
// string str{"Hello World"};
}
getchar();
}
C++11——1.小练手
最新推荐文章于 2021-12-24 17:26:35 发布