- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我很难理解为什么在下面的代码中直接调用 std::swap()
会导致编译错误,而使用 std::iter_swap
编译却没有任何错误.
来自 iter_swap()
versus swap()
-- what's the difference? , iter_swap
最终调用了 std::swap
但它们的行为仍然不同。
#include <iostream>
#include <vector>
class IntVector {
std::vector<int> v;
IntVector& operator=(IntVector); // not assignable
public:
void swap(IntVector& other) {
v.swap(other.v);
}
};
void swap(IntVector& v1, IntVector& v2) {
v1.swap(v2);
}
int main()
{
IntVector v1, v2;
// std::swap(v1, v2); // compiler error! std::swap requires MoveAssignable
std::iter_swap(&v1, &v2); // OK: library calls unqualified swap()
}
最佳答案
iter_swap
中调用的 swap
是不完全合格的,即不作为 std::swap
调用,而只是作为 交换
。因此,在名称查找和 ADL
期间,编译器会找到多个与 swap
调用相匹配的函数。但是,重载解决方案
会选择您提供的交换
,因为它最匹配。
如果您在主代码中使用 swap
,那么它可以正常编译,因为它不会找到 std::swap
。即使您 using namespace std;
关于c++ - std::iter_swap 需要 ValueSwappable args vs std::swap 需要 Move Assignable args,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38291489/
如果我有一个容器 std::vector items ,我可以创建一个 IndirectIterator包装 std::vector::iterator并允许遍历 T的而不是 T*的。 我可以专攻it
我只是想知道,为什么有人会写这个: std::iter_swap(i, k); 而不是这个? std::swap(*i, *k); // saved a few keystrokes! 然后我研究
MSDN says : swap should be used in preference to iter_swap, which was included in the C++ Standard f
实现基本的冒泡排序以按名称对 Student 结构的 vector 进行排序。 #include #include void sortStudents(std::vector& students)
我有一个“简单”的问题:我正在尝试交换 map 中的对以更改顺序。此代码无法编译。 #include #include #include #include int main() { std
我将一个包含 20 个项目的 vector 传递给下面的函数。我的目标是更改 vector 中项目的顺序。如果列表包含项目 1 2 3 4,我希望最终结果为 4 3 2 1。基本上将第一项与最后一项切
我正在尝试概括一个函数,该函数用于将两个迭代器带入特定数据结构的 vector ,并使用 std::iter_swap 以特定方式重新排列元素(就像 std::sort 那样)。 由于这个函数实际上只
从 David Abrahams 和 Aleksey Gurtovoy 的书“C++ 模板元编程”中,我了解到 iter_swap (见下文)会比 std::swap 慢得多有时。虽然这本书有一些解释
查看std::iter_swap reference我的结论是: struct A {}; std::experimental::optional x{A{}}, y{A{}}; std::iter_
为什么/什么时候我们应该更喜欢 using std::swap; swap(a, b); over std::iter_swap(&a, &b)? 最佳答案 因为它们完全不同,所以你的问题是错误的二分
我很难理解为什么在下面的代码中直接调用 std::swap() 会导致编译错误,而使用 std::iter_swap 编译却没有任何错误. 来自 iter_swap() versus swap() -
我是一名优秀的程序员,十分优秀!