C++ 学习与 CLion 使用:(二)using namespace std 语句详解,以及 std 空间的标识符罗列

发布于:2025-08-13 ⋅ 阅读:(20) ⋅ 点赞:(0)

using namespace std

1)作用

在 C++ 中,using namespace std; 的作用是引入标准命名空间 std 中的所有标识符,使得在代码中可以直接使用 std 中的名称(如 coutvectorstring 等,类似 python 中的关键字),而无需显式添加 std:: 前缀。

  • 如果不使用 using namespace std;,每次调用标准库功能时都必须显式加上 std:: 前缀:

    #include <iostream>
     
    int main() {
        std::cout << "Hello, World!" << std::endl;  // 必须写 std::
        std::string s = "C++";
        return 0;
    }
    
  • 而使用 using namespace std; 后,可以省略 std::

    #include <iostream>
    using namespace std;  // 引入 std 命名空间
     
    int main() {
        cout << "Hello, World!" << endl;  // 直接使用
        string s = "C++";
        return 0;
    }
    

注意:虽然这样可以省事,但是如果自定义的标识符(如变量、函数)与 std 中的名称相同,会导致冲突。也会降低代码可读性。

注意:在头文件中绝对不要使用 using namespace std;

2)用法

  • 局部使用(推荐)

    仅在函数内部或 .cpp 文件中局部引入,避免在头文件中使用:

    #include <iostream>
     
    void printHello() {
        using namespace std;  // 仅在此作用域内有效
        cout << "Hello!" << endl;
    }
    
  • 显式引入特定名称

    只引入需要的名称,而非整个 std

    #include <iostream>
    using std::cout;  // 仅引入 cout
    using std::endl;  // 仅引入 endl
     
    int main() {
        cout << "Hello!" << endl;  // 可以直接使用
        // string s = "C++";       // 错误!未引入 std::string
        return 0;
    }
    
  • 完全避免(最安全)

    直接使用 std:: 前缀,明确来源:

    #include <iostream>
     
    int main() {
        std::cout << "Hello!" << std::endl;  // 始终显式指定
        std::string s = "C++";
        return 0;
    }
    

3)std 命名空间核心内容表格

分类 子分类 关键成员
输入/输出 (I/O) 标准流 cin, cout, cerr, clog
文件流 ifstream, ofstream, fstream
字符串处理 字符串类 string, wstring, u16string, u32string
字符串操作 getline, stoi, to_string, stod
容器 顺序容器 vector, list, deque, array, forward_list
关联容器(有序) set, map, multiset, multimap
无序关联容器(哈希表) unordered_set, unordered_map, unordered_multiset, unordered_multimap
算法 排序与搜索 sort, find, binary_search, lower_bound, upper_bound
修改操作 copy, reverse, unique, fill, transform
数值计算 accumulate, inner_product, iota, partial_sum
迭代器 通用工具 begin, end, next, prev, distance, advance
实用工具 时间处理 chrono::seconds, chrono::milliseconds, system_clock
随机数生成 mt19937, uniform_int_distribution, shuffle
智能指针 unique_ptr, shared_ptr, weak_ptr, make_shared, make_unique
类型特性与转换 move, forward, is_integer, enable_if, conditional
异常处理 异常类 exception, runtime_error, logic_error, invalid_argument
多线程 线程管理 thread, mutex, lock_guard, unique_lock, condition_variable
函数式编程 函数对象 plus, minus, less, equal_to, greater
绑定与可调用对象 bind, function, mem_fn, not_fn
数学函数 通用数学 abs, sqrt, sin, cos, floor, ceil, pow, log
C 兼容性 C 标准库封装 printf, scanf, fopen, malloc, free(通过 <cstdio> 等头文件提供)


网站公告

今日签到

点亮在社区的每一天
去签到