✔ std namespace
max, min 함수
→ c++ 표준이 제공하는 함수
→ <algorithm> 헤더
→ 모든 C++ 표준 함수는 "std" namespace 안에 있다.
① 기본 사용
- 가장 권장하는 방법
// qualified name
#include <stdio.h>
#include <algorithm>
int main()
{
int n1 = std::max(10, 20);
int n2 = std::min(10, 20);
printf("%d, %d\n", n1, n2);
}
② using 사용
// qualified name
#include <stdio.h>
#include <algorithm>
using std::max;
using std::min;
int main()
{
int n1 = max(10, 20);
int n2 = min(10, 20);
printf("%d, %d\n", n1, n2);
}
③ std의 모든 함수 선언
// qualified name
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
int n1 = max(10, 20);
int n2 = min(10, 20);
printf("%d, %d\n", n1, n2);
}
- 업무에는 사용하지 않는 것 권장
- 이유 : std::count라는 함수가 있다. 👉이름 충돌 발생
// qualified name
#include <stdio.h>
#include <algorithm>
using namespace std;
int count = 10;
int main()
{
int n1 = max(10, 20);
int n2 = min(10, 20);
printf("%d, %d\n", n1, n2);
printf("%d\n", count);
}
✔ nested namespace
- std : 대부분의 C++ 표준 라이브러리
- std::filesystem: 파일 관련 표준라이브러리 (c++17)
- std::chrono: 날씨/시간 관련 표준 라이브러리 (c++11)
- std::this_thread: 스레드 관련 표준 라이브러리 (c++11)
namespace Video
{
void init()
{
}
//namespace는 중첩될 수 있다.
namespace Render
{
void start()
{
}
}
}
int main()
{
Video::init();
Video::Render::start();
using namespace Video;
init();
Render::start();
}
✔ header file
→ C++ 표준 헤더 파일 이름에는 .h가 붙어있지 않다.
ex) <algorithm>
→ 사용자가 만드는 헤더는 .h 붙어도 됨
→ C언어에서 사용하던 헤더는 C++ 버전이 별도로 제공된다
→ 서로 다른 header에서 같은 namespace를 사용하는 것은 문제가 되지 않는다.
- stdio.h : printf 등의 함수가 global namespace에 제공
- cstdio : prinft 등의 함수가 global namespace와 std namespace 안에 모두 제공
C언어용 헤더 | C++에서 제공하는 헤더 |
<stdio.h> <stdlib.h> <string.h> <xxxxx.h> |
<cstdio> <cstdlib> <cstring> <cxxxxxx> |
#include <algorithm>
//#include <stdio.h>
#include <cstdio>
int main()
{
int n = std::max(10, 20);
printf("%d\n", n);
std::printf("%d\n", n);
}
✔ namespace alias
#include <filesystem> // C++17
namespace fs = std::filesystem; //namespace alias
int main()
{
std::filesystem::create_directory("C:/Test");
if ( ! std::filesystem::exists("C:/Test/calc.exe") )
{
std::filesystem::copy_file("C:/Windows/system32/calc.exe", "C:/Test/calc.exe");
}
// namespace fs = std::filesystem; 안쪽에도 사용 가능
// namespace fs 사용시 코드
fs::create_directory("C:/Test");
if ( ! fs::exists("C:/Test/calc.exe") )
{
fs::copy_file("C:/Windows/system32/calc.exe", "C:/Test/calc.exe");
}
}
반응형
'프로그래밍 > C ++' 카테고리의 다른 글
[C++] 함수 (0) | 2024.12.03 |
---|---|
[C++] 자료형 (묵시적형변환) (0) | 2024.12.03 |
[c++] C++ 변수의 특징 (0) | 2024.07.08 |
[C++] iosteam 표준 입출력 (0) | 2024.07.08 |
[C++] namespace (0) | 2024.06.24 |