C++ — "算法"库和命名空间"std"

C++ — `algorithm` library and namespace `std`

本文关键字:quot 命名空间 std C++ 算法      更新时间:2023-10-16

我发现可以使用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

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

提前谢谢你。

如注释中所述,由于依赖于参数的查找,没有std::工作unique

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