C++ 11관련해서 외울 필요가 있는 몇가지 정리
1. 신규 타입
auto 타입 : auto i = 7;
decltype(expr) 타입 : decltype(i) j = 8; // i의 타입을 따라 j타입 지정
2. auto를 사용해서 for 루프 간편하게
int arr[] = {1,2,3,4}; // 다른 컨테이너도 사용가능
for(auto& i : arr) {
i += 2;
}
3. 고정 배열의 경우 std의 array사용
std::array<int, 3> arr = {9,8,7};
for (auto i : arr)
cout << i << endl;
4. stl vector 컨테이너 추가시에 아래 방식으로 복제 없이 이동 시맨틱으로 동작하도록 개선
vec.push_back({12, "twelve"});
vec.emplace_back(12, "twelve");
5. std의 여러 탐색 알고리즘 활용
auto end = myVector.end();
auto it = find_if(myVector.begin(), end, [](int i){ return i >= 100; });
if (it == end) {
cout << "No Perfect Scores" << endl;
} else {
count << "Found Perfect Score of << *it << endl;
}
6. 람다 표현식 사용 및 캡쳐블록 정리
[]{cout << "Hello world" << endl;}();
function<void> multiplyBy2Lamda(int x)
{
return [=]{return 2*x;};
}
auto fn = multiplyBy2Lamda(5);
cout << fn() << endl;
[=] 모든 변수 값으로 복제하여 캡쳐
[&] 모든 변수 참조로서 캡쳐
[&x] 변수 x만을 참조로 캡쳐
[x] 변수 x만을 값으로 캡쳐
7. 연산자 오버로딩 활용
friend const TempClass operator+(const TempClass& lhs, const TempClass& rhs);
..
const TempClass operator+(const TempClass& lhs, const TempClass& rhs)
{
TempClass newTemp;
newTemp.set(lhs.mValue + rhs.mValue);
return newTemp;
}
8. 정규표현식 활용
regex r("^test");
if (regex_match(str, r))
{
cout << "Valid Str" << endl;
}
9. uniform한 난수 생성 예제
mt19937 eng(static_cast<unsigned long>(time(nullptr)));
uniform_int_distribution<int> dist(1,99);
auto gen = std::bind(dist, eng);
vector<int> vec(10);
generate(vec.begin(), vec.end(), gen);
for (auto i : vec)
cout << i << endl;
[출처] 전문가를 위한 C++ 책을 읽고 몇 가지 정리|작성자 밤비
[출처] 전문가를 위한 C++ 책을 읽고 몇 가지 정리|작성자 밤비
http://blog.naver.com/vambii/220570762830
'개발' 카테고리의 다른 글
Improved Type Inference in C++11: auto, decltype, and the new function declaration syntax (0) | 2016.02.15 |
---|---|
Modern C++ auto에 관해서 (0) | 2016.02.15 |
Modern C++ 스마트 포인터 (0) | 2016.02.15 |
Full Stack Engineer에 대하여 (0) | 2015.11.30 |
Mysql Join 해부(Left, Right, Outer, Inner Join) (0) | 2015.11.30 |