#include <utility>
#include <vector>
using namespace std;
std::pair<std::size_t, std::size_t> func(const std::vector<int>& numbers, int target) {
for(std::size_t i =0; i < numbers.size(); i++)
{
for(std::size_t j = i; j < numbers.size(); j++)
{
if(numbers[i] + numbers[j] == target)
return std::make_pair<std::size_t, std::size_t>(i,j);
}
}
return std::make_pair<std::size_t, std::size_t>(0,0);
}
错误:
test.cpp: In function ‘std::pair<long unsigned int, long unsigned int> func(const std::vector<int>&, int)’:
test.cpp:12:62: error: no matching function for call to ‘make_pair<std::size_t, std::size_t>(std::size_t&, std::size_t&)’
return std::make_pair<std::size_t, std::size_t>(i,j);
^
In file included from /usr/include/c++/7/utility:70:0,
from test.cpp:1:
/usr/include/c++/7/bits/stl_pair.h:524:5: note: candidate: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
make_pair(_T1&& __x, _T2&& __y)
^~~~~~~~~
/usr/include/c++/7/bits/stl_pair.h:524:5: note: template argument deduction/substitution failed:
test.cpp:12:62: note: cannot convert ‘i’ (type ‘std::size_t {aka long unsigned int}’) to type ‘long unsigned int&&’
return std::make_pair<std::size_t, std::size_t>(i,j);
^
当我们明确提到模板化 pair
中的类型以及 i
的数据类型时,为什么它尝试用 unsigned long int
替换和j
?
最佳答案
当你指定模板参数为std::size_t
时,std::make_pair
的函数参数类型变为std::size_t&&
,即右值引用; i
和 j
是左值,不能绑定(bind)到右值引用。
只需让 std::make_pair
进行模板参数推导,如 std::make_pair(i,j)
(模板参数为 std::size_t&
,函数参数是 std::size_t&
) 就可以了。 std::make_pair
需要 forwarding references ,它应该接受左值和右值(对于 std::make_pair(0,0)
,模板参数是 std::size_t
,函数参数是 std::size_t&&
)。
关于c++ - std::pair 替换因 std::size_t 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68235631/