如何从函数返回pair

how to return pair from a function?

本文关键字:返回 pair 函数      更新时间:2023-10-16

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

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/../../../../包括/c++/4.4.7/位/stl_algobase.h: 66年,从/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../包括/c++/4.4.7/位/char_traits.h: 41岁从/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../包括/c++/4.4.7/ios: 41岁从/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../包括/c++/4.4.7/上ostream: 40岁从/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../包括/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>, 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:错误:非静态const成员' const std::basic_string, std::allocator> std::pair, std::allocator>, const double>::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>, const double>::second ',不能使用默认赋值操作符test8。在函数"pr getvalue(std::string)"中:test8。Cxx:14:注释:合成方法' std::pair, std::allocator>, const double>&Std::pair, Std::allocator>, const double>::operator=(const Std::pair, Std::allocator>, const double>&) '这里首先需要

请帮帮我。

类型pr定义为对的两个成员都是const。变量pValue一旦声明,就不能在赋值pValue = (*iter).second中更改,因为它的所有成员实际上都是const。

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

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