gpt4 book ai didi

c++ - 将 `std::swap` 应用于这些对象时会做什么?

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:29 25 4
gpt4 key购买 nike

代码

using namespace std;

class A
{
private:
vector<int> a;
public:
A(vector<int> x):a(x){}
string toString()
{
string s;
for (auto& element : a)
{
s += to_string(element) + " ";
}
return s;
}
};

int main()
{
A a1({1,2,3});
A a2({11,12,13});

cout << "a1 = " << a1.toString() << "\n";
cout << "a2 = " << a2.toString() << "\n";

swap(a1,a2);

cout << "a1 = " << a1.toString() << "\n";
cout << "a2 = " << a2.toString() << "\n";

return 0;
}

按预期输出

a1 = 1 2 3                                                                                                            
a2 = 11 12 13
a1 = 11 12 13
a2 = 1 2 3

来自 cplusplus.com > std::swap复杂性

Non-array: Constant: Performs exactly one construction and two assignments (although notice that each of these operations works on its own complexity).

Array: Linear in N: performs a swap operation per element.

这是否意味着 std::swap 在应用于 a1a2 时仅交换指向数组的指针 [1 ,2,3][11,12,13] 但不复制任何 int 或其他任何内容?

std::swap 应用于 A 类的两个对象时究竟做了什么?

假设 std::swap 复制数组的所有元素,我是否应该使用 vector::swap< 编写一个 static A::swap 函数 其时间复杂度是常量(来自 cplusplus.com > vector::swap )意味着它只交换指针?


[..] want to add a note that the semantics of std::swap is changed in C++17. So it might be a good idea to mention compiler, version of it and what standard you target.

我希望一个看起来简单的问题不会带来有关 C++ 标准和编译器版本的复杂性。我通常在 C++11 中编译我的代码。为了完整起见,这里是我笔记本电脑上的 gcc 版本。

$ gcc --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.13.sdk/usr/include/c++/4.2.1
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.3.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

最佳答案

要求 std::swap 模板的类型参数是 MoveConstructible 和 MoveAssignable。这表明 swap 可以粗略地写成(省略几位)

void swap(T &a, T &b) {
T tmp{std::move(a)};
a = std::move(b);
b = std::move(tmp);
}

对于您的示例类,它将调用默认的移动构造函数/移动赋值运算符(编辑:A)几次,然后它们将依次调用 std::vector 。IOW,您可以期望您的程序按原样相当高效。

或者,您可以在与 A 相同的命名空间中定义一个非成员 swap 函数,并使用 vector 显式调用 std::swap参数。或者直接调用std::vector::swap

关于c++ - 将 `std::swap` 应用于这些对象时会做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48861311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com