在C++ 03中编程时,我们无法将未命名的临时文件T()传递给函数void foo(T&);.通常的解决方案是给临时名称,然后传递它:
T v;
foo(v);
Run Code Online (Sandbox Code Playgroud)
现在,沿着C++ 0x - 现在使用rvalue引用,定义为的函数void foo(T&&)将允许我传递临时值.这让我想到了一个问题:因为一个采用右值引用的函数可以同时使用右值引用(未命名的临时值)以及左值引用(命名为非const引用),是否有理由在函数参数中再使用左值引用?我们不应该总是使用rvalues作为函数参数吗?
当然,一个采用左值引用的函数会阻止调用者传递临时值,但我不确定这是否是一个有用的限制.
今天我想尝试将我的项目从visual c ++ 2010带到visual c ++ 2013.
我在visual c ++ 2013中遇到了这个错误,这是我在编译2010版时没有得到的.
//somewhere in the SimpleObject_list class
std::unordered_map<std::string, SimpleObject *> Object_list;
//method which is giving me the error
void SimpleObject_list::Add(const char *Object_name, SimpleObject * Object_pointer){
cout << "SimpleObject listed as: " << Object_name << endl;
Object_list.insert(std::make_pair<std::string,SimpleObject *>(Object_name, Object_pointer));
}
Run Code Online (Sandbox Code Playgroud)
错误是:
error C2664: 'std::pair<std::basic_string<char,std::char_traits<char>,std::allocator<char>>,SimpleObject *> std::make_pair<std::string,SimpleObject*>(_Ty1 &&,_Ty2 &&)' : cannot convert argument 2 from 'SimpleObject *' to 'SimpleObject *&&'
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?为什么我在vc ++ 2010中没有出现任何错误?
谢谢
GCC 和 Clang 都拒绝编译这个:
\n#include <string>\n#include <utility>\n\nusing namespace std;\n\nint main() {\n const string s = "12345";\n const string& r = s;\n\n auto p = std::make_pair<string, string>(r, r);\n}\nRun Code Online (Sandbox Code Playgroud)\n海湾合作委员会 说:
\nerror: cannot bind rvalue reference of type \xe2\x80\x98std::__cxx11::basic_string<char>&&\xe2\x80\x99 to lvalue of type \xe2\x80\x98const std::string\xe2\x80\x99 {aka \xe2\x80\x98const std::__cxx11::basic_string<char>\xe2\x80\x99}\nRun Code Online (Sandbox Code Playgroud)\n虽然 Clang 说:
\nerror: no matching function for call to 'make_pair'\nRun Code Online (Sandbox Code Playgroud)\n既然我给出了make_pair显式类型,为什么它不从中构造新字符串const string&?
这个编译:
\nauto p = std::make_pair<string, string>(string(r), string(r));\nRun Code Online (Sandbox Code Playgroud)\n 我有一个向量pairs。假设是这样的:
vector<pair<int,int>> vec = { {1,12}, {1,5}, {1,6}, {1,9}, {3,9}, {3,11}, {3,13}, {3,4}, {5,9}, {5,91}, {13,8}, {16,8}, {20,8}, {20,81} };
Run Code Online (Sandbox Code Playgroud)
在pairs由第一个元素进行排序。
给定a pair,我需要找到pair向量中最后一个元素的索引,该向量的第一个元素小于或等于给定对的第一个元素。如果对于最后一个pair,其他对以第一个元素的相同值位于其左侧,那么我需要所有这些对中的第一个:
<4,10> => 4 (vec[4] is <3,9>, the elements with the largest first value less than or equal to 4 are those with first element as 3, and there are 4 pairs with a 3 in the first element, at indices 4-7, so return the first of those pairs) …Run Code Online (Sandbox Code Playgroud)