C++ — `algorithm` 库和命名空间 `std`

标签 c++ namespaces

我发现可以使用 algorithm 的许多(也许所有)功能。带或不带命名空间的库 std :例如当algorithm是进口的:

#include <algorithm>
std::uniqueunique似乎是等价的。这是一个例子:
#include <iostream>
#include <vector>
#include <algorithm>


int main () {
    std::vector<int> v = {10,20,20,20,30,30,20,20,10};
    std::vector<int>::iterator it;

    it = std::unique (v.begin(), v.end());
    for (it=v.begin(); it!=v.end(); ++it)
        std::cout << ' ' << *it;
        std::cout << '\n';

    it = unique (v.begin(), v.end());
    for (it=v.begin(); it!=v.end(); ++it)
        std::cout << ' ' << *it;
        std::cout << '\n';
}

输出:
10 20 30 20 10 30 20 20 10
10 20 30 20 10 30 20 20 10

1)它们的功能相同吗?

2)不管使用std,使用这些功能的机制是什么?命名空间?我查了一下源代码:
https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/bits/stl_algo.h



https://github.com/gcc-mirror/gcc/blob/d9375e490072d1aae73a93949aa158fcd2a27018/libstdc%2B%2B-v3/include/std/algorithm

但我仍然不知道它是如何工作的。

先感谢您。

最佳答案

正如评论中提到的unique没有 std::由于依赖于参数的查找而工作。
v.begin()v.end()返回 std::vector<int>::iterator这是 std::vector<int> 的一些迭代器.这可以是满足迭代器要求的任何类型。它可以是指向 int 的简单指针或更可能是带有重载运算符的类。

如果迭代器是类类型,则依赖于参数的查找将搜索 unique在该类和封闭命名空间范围的类中。如果封闭的命名空间范围恰好是 ::std ,然后 ::std::unique会被发现并使用。

不能保证这有效。它是否会取决于标准库实现。

例如 std::array而不是 std::vector它适用于 MSVC,但不适用于 Clang(使用 libc++)或 GCC(使用 libstdc++),因为后两者只使用 int*作为迭代器,参见 https://godbolt.org/z/Ysu2-d .

您应该始终引用 std::unique用它的限定名称。

关于C++ — `algorithm` 库和命名空间 `std`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60028356/

相关文章:

c++ - Google Test 中的 RAII 内存损坏

php - C++ 在 PHP 中使用命名空间?

python - 同时使用相同端口、相同 IP 地址的应用程序/协议(protocol)

c++ - 命名空间中的主要内容

Spring GCP 数据存储接口(interface) : setting the namespace?

c++ - AT命令响应解析器

c++ - 确保正确释放 C++ 对象

c++ - 全局指针是否初始化为零?

c++ - 使用 CRTP 时在基类中使用非模板派生类的 typedef

html - 将节点的内容克隆到不同的命名空间