C++ — `algorithm` 库和命名空间 `std`
C++ — `algorithm` library and namespace `std`
我发现可以使用 algorithm
库的许多(也许是所有)功能,无论是否带有命名空间 std
:例如导入 algorithm
时:
#include <algorithm>
std::unique
和 unique
似乎是等价的。这是一个例子:
#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
和
但我仍然不知道它是如何工作的。
提前致谢。
如评论中所述,unique
没有 std::
是因为依赖于参数的查找。
v.begin()
和 v.end()
return std::vector<int>::iterator
是 std::vector<int>
的一些迭代器。这可以是满足迭代器要求的任何类型。它可能是指向 int
的简单指针,或者更可能是带有重载运算符的 class。
如果迭代器是 class 类型,则依赖于参数的查找将在该 class 和 classes 封闭命名空间范围内搜索 unique
。如果封闭的命名空间范围恰好是 ::std
,那么将找到并使用 ::std::unique
。
不能保证这有效。这取决于标准库实现是否会。
例如,使用 std::array
而不是 std::vector
它适用于 MSVC,但不适用于 Clang(使用 libc++)或 GCC(使用 libstdc++),因为后两者只使用 int*
作为迭代器,参见 https://godbolt.org/z/Ysu2-d.
您应该始终使用其限定名称引用 std::unique
。
我发现可以使用 algorithm
库的许多(也许是所有)功能,无论是否带有命名空间 std
:例如导入 algorithm
时:
#include <algorithm>
std::unique
和 unique
似乎是等价的。这是一个例子:
#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
和
但我仍然不知道它是如何工作的。
提前致谢。
如评论中所述,unique
没有 std::
是因为依赖于参数的查找。
v.begin()
和 v.end()
return std::vector<int>::iterator
是 std::vector<int>
的一些迭代器。这可以是满足迭代器要求的任何类型。它可能是指向 int
的简单指针,或者更可能是带有重载运算符的 class。
如果迭代器是 class 类型,则依赖于参数的查找将在该 class 和 classes 封闭命名空间范围内搜索 unique
。如果封闭的命名空间范围恰好是 ::std
,那么将找到并使用 ::std::unique
。
不能保证这有效。这取决于标准库实现是否会。
例如,使用 std::array
而不是 std::vector
它适用于 MSVC,但不适用于 Clang(使用 libc++)或 GCC(使用 libstdc++),因为后两者只使用 int*
作为迭代器,参见 https://godbolt.org/z/Ysu2-d.
您应该始终使用其限定名称引用 std::unique
。