[英]Need some help about "swap" function in c++
I am new to C++ programming.我是 C++ 编程的新手。 I am trying to compile another person's program, and the software reported a bug that I don't know how to solve (the software I use is Visual Studio 2019).我在尝试编译别人的程序,软件报了一个不知道怎么解决的bug(我用的软件是Visual Studio 2019)。
The line of code with bug is:有错误的代码行是:
swap(allBeamPoints, unordered_map<int, vector<LidarPoint>>());
The definition for variable allBeamPoints
is:变量allBeamPoints
的定义是:
unordered_map<int, vector<LidarPoint>>allBeamPoints
The error information is:错误信息是:
Error C2665 'std::swap': none of the 2 overloads could convert all the argument types
and和
Error (active) E0304 no instance of overloaded function "swap" matches the argument list
However, if I type the following codes, no bug will be reported:但是,如果我输入以下代码,则不会报告错误:
unordered_map<int, vector<LidarPoint>> allBeamPoints_new;
swap(allBeamPoints, allBeamPoints_new);
Does anyone know what the problem is?有谁知道问题是什么? Did I fail to link some of the required libraries?我是否未能链接某些必需的库? How should I check those libraries?我应该如何检查这些库?
Try this way.试试这个方法。 ( Here ) ( 这里)
// unordered_map::swap
#include <iostream>
#include <string>
#include <unordered_map>
int main ()
{
std::unordered_map<std::string,std::string>
first = {{"Star Wars","G. Lucas"},{"Alien","R. Scott"},{"Terminator","J. Cameron"}},
second = {{"Inception","C. Nolan"},{"Donnie Darko","R. Kelly"}};
first.swap(second);
std::cout << "first: ";
for (auto& x: first) std::cout << x.first << " (" << x.second << "), ";
std::cout << std::endl;
std::cout << "second: ";
for (auto& x: second) std::cout << x.first << " (" << x.second << "), ";
std::cout << std::endl;
return 0;
}
The older MSVC compilers allowed the binding of an anonymous temporary to a non- const
reference function parameter.较旧的 MSVC 编译器允许将匿名临时对象绑定到非const
引用函数参数。 That's not standard C++.这不是标准的 C++。
So所以
swap(allBeamPoints, unordered_map<int, vector<LidarPoint>>());
which had the effect of clearing allBeamPoints
was reasonably idiomatic in code that only targeted Microsoft platforms.清除allBeamPoints
的效果在仅针对 Microsoft 平台的代码中是相当惯用的。
It's wrong and not portable as you now observe.正如您现在观察到的那样,这是错误的并且不可移植。 Use用
allBeamPoints.clear();
instead to clear the map.而是清除地图。 Your second snippet compiles since allBeamPoints_new
is not an anonymous temporary.您的第二个代码段可以编译,因为allBeamPoints_new
不是匿名临时文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.