how to return pair from a function?
I am trying to write a function which will return pair from function but I am getting error during compilation.
This is the whole file:
#include <iostream>
#include <map>
#include <utility>
using namespace std;
typedef pair<const string, const double> pr;
typedef map<const string,pr > mpr;
mpr mymap;
pr getvalue(const string s)
{
pr pValue;
mpr::iterator iter = mymap.find(s);
if(iter not_eq mymap.end())
{
pValue = (*iter).second;
}
return pValue;
}
int main( )
{
getvalue("test");
}
Error Message:
In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_algobase.h:66, from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/char_traits.h:41, from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ios:41, from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ostream:40, from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/iostream:40, from test8.cxx:1: /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h: In member function 'std::pair, std::allocator >, const double>& std::pair, std::allocator >, const double>::operator=(const std::pair, std::allocator >, const double>&)': /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h:68: error: non-static const member 'const std::basic_string, std::allocator > std::pair, std::allocator >, const double>::first', can't use default assignment operator /usr/ lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h:68: error: non-static const member 'const double std::pair, std::allocator >, const double>::second', can't use default assignment operator test8.cxx: In function 'pr getvalue(std::string)': test8.cxx:14: note: synthesized method 'std::pair, std::allocator >, const double>& std::pair, std::allocator >, const double>::operator=(const std::pair, std::allocator >, const double>&)' first required here
Please help me out.
The type pr
is defined with both members of the pair being const
. Once declared, the variable pValue
cannot be changed in the assignment pValue = (*iter).second
, because all it's members are effectively const.
The code can be modified to (which should compile);
pr getvalue(const string s)
{
mpr::iterator iter = mymap.find(s);
if(iter not_eq mymap.end())
{
return (*iter).second;
}
return pr();
}
链接地址: http://www.djcxy.com/p/66744.html
上一篇: 排序矢量中的值时,会使用排序方法生成错误
下一篇: 如何从函数返回对?