如何从函数返回对?

时间:2014-07-03 09:21:29

标签: c++ map

我正在尝试编写一个函数,它将从函数返回对,但我在编译期间遇到错误。

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");

}

错误讯息:

在/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_algobase.h中包含的文件中: 66,                  来自/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/char_traits.h:41,                  来自/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ios:41,                  来自/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/ostream:40,                  来自/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/iostream:40,                  来自test8.cxx:1: /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h:在成员函数'std :: pair,std :: allocator&gt;,const double&gt;&amp; std :: pair,std :: allocator&gt;,const double&gt; :: operator =(const std :: pair,std :: allocator&gt;,const double&gt;&amp;)': /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h:68:错误:非静态const成员'const std :: basic_string,std :: allocator&gt; std :: pair,std :: allocator&gt;,const double&gt; :: first',不能使用默认赋值运算符 /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_pair.h:68:错误:非静态const成员'const double std :: pair,std :: allocator&gt;,const double&gt; :: second',不能使用默认赋值运算符 test8.cxx:在函数'pr getvalue(std :: string)'中: test8.cxx:14:注意:合成方法'std :: pair,std :: allocator&gt;,const double&gt;&amp; std :: pair,std :: allocator&gt;,const double&gt; :: operator =(const std :: pair,std :: allocator&gt;,const double&gt;&amp;)'这里首先需要

请帮帮我。

1 个答案:

答案 0 :(得分:1)

类型pr的定义是该对的成员都是const。声明后,变量pValue无法在作业pValue = (*iter).second中更改,因为它的所有成员都是有效的。

代码可以修改为(应编译);

pr getvalue(const string s)
{
    mpr::iterator iter = mymap.find(s);
    if(iter not_eq mymap.end())
    {
        return (*iter).second;
    }
    return pr();
}