Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- bitcoin
- go언어
- FOR
- C
- Python
- channel
- API
- c++
- 영화
- GO 언어
- write
- tcp
- mutex
- http
- range
- Close
- go
- window
- Linux
- install
- 리뷰
- Sync
- 책
- Callback
- windows
- json
- JavaScript
- Golang
- File
- package
Archives
- Today
- Total
Code Habit
[c++] Modern C++ 주요 문법 정리 본문
Modern C++은 C++ 11 이 후의 버전을 가리키며 더 효율적으로 코드를 작성하고 안정성 및 최적화를 위해 등장했다.
1. auto 키워드
- auto 키워드를 이용하여 변수형을 자동으로 추론할 수 있다.
auto n = 10; // int형으로 추론
auto str = "coding"; // char* 형식으로 추론
2. 범위 기반 루프 ( for 문 )
- 범위 기반 루프를 사용하여 컨테이너의 모든 요소를 간편하게 순회할 수 있다.
std::map<int, std::string> data;
data[0] = "first";
data[1] = "second";
data[2] = "third";
for (auto& fit : data) {
auto& idx = fit.first;
auto& value = fit.second; // 참조로 접근 : 값을 수정하면 원본 데이터도 변경됨
printf("idx [%d], value [%s]\n", idx, value);
}
3. 스마트 포인터
- std::shared_ptr, std::unique_ptr, std::weak_ptr과 같은 스마트 포인터를 사용하여 메모리 관리를 효율적으로 할 수 있다.
std::shared_ptr<int> ptr1 = std::make_shared<int>(21);
std::unique_ptr<int> ptr2 = std::make_unique<int>(42);
4. 람다 표현식
- 간단한 익명 함수를 정의하여 함수 객체를 생성하고 사용할 수 있다.
auto add = [](int a, int b){ return a + b; };
int result = add(2, 5); // 결과는 7
int x = 5;
auto multiply = [x](int a){ return a * x; }; // x를 외부변수 캡처하여 전달
result = multiply(2); // 결과는 10
5. 스레드와 병렬 프로그래밍
- std::thread를 사용하여 멀티스레드 프로그래밍을 할 수 있다.
#include <thread>
void work() {
return "done";
}
int main() {
std::thread th1(work); // 스레드 생성과 실행
th1.join() // 스레드 종료될때까지 대기
return 0;
}
6. chrono 라이브러리
- chrono 라이브러리를 사용하여 시간측정, 지연 등의 기능을 손쉽게 구현할 수 있다.
#include <iostream>
#include <chrono>
int main() {
// get start time
auto start_time = std::chrono::high_resolution_clock::now();
// wait 2 second
std::this_thread::sleep_for(std::chrono::seconds(2));
// get end time
auto end_tiem = std::chrono::high_resolution_clock::now();
// get duration
std::chrono::duration<double> elapsed_time = end_time - start_time;
// print output
std::cout<< "경과 시간 :" << elapsed_time.count() << "초" << std::endl;
return 0;
}