如何使用C++ 标准库?
作者:野牛程序员:2023-03-28 17:01:41 C++阅读 2640
要使用 C++ 标准库,需要在程序中包含相应的头文件,并调用相应的函数或使用相应的类、模板等。下面介绍一些常用的 C++ 标准库用法:
使用输入输出流
1 2 3 4 5 6 7 8 9 | #include <iostream> int main() { int x; std::cout << "Please enter an integer: " ; std::cin >> x; std::cout << "You entered: " << x << std::endl; return 0; } |
使用容器和算法
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <iostream> #include <vector> #include <algorithm> int main() { std::vector< int > vec = {1, 5, 3, 8, 2}; std::sort(vec.begin(), vec.end()); for ( auto x : vec) { std::cout << x << " " ; } std::cout << std::endl; return 0; } |
使用字符串
1 2 3 4 5 6 7 8 9 | #include <iostream> #include <string> int main() { std::string str = "hello world" ; std::cout << str.length() << std::endl; std::cout << str.substr(6, 5) << std::endl; return 0; } |
使用函数对象
1 2 3 4 5 6 7 8 | #include <iostream> #include <functional> int main() { std::function< int ( int )> add = []( int x) { return x + 1; }; std::cout << add(1) << std::endl; return 0; } |
使用时间库
1 2 3 4 5 6 7 8 9 10 | #include <iostream> #include <chrono> #include <ctime> int main() { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std:: time_t t = std::chrono::system_clock::to_time_t(now); std::cout << "Current time: " << std:: ctime (&t); return 0; } |
需要注意的是,在使用 C++ 标准库的时候,要根据需要包含相应的头文件,并使用正确的命名空间,避免出现命名冲突等问题。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:C++ 标准库是什么?里面包含了些什么内容?
- 下一篇:什么是C++中的命名空间?