【问题标题】:how to return pair from a function?如何从函数返回对?
【发布时间】:2014-07-03 09:21:28
【问题描述】:

我正在尝试编写一个函数,该函数将从函数返回对,但在编译过程中出现错误。

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::对,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 member '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 member 'const double std::pair, std::allocator >, const double>::second',不能使用默认赋值运算符 test8.cxx:在函数‘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>&)' 这里首先需要

请帮帮我。

【问题讨论】:

  • @LuchianGrigore 添加错误
  • 请避免修复您的问题,因为答案试图修复它,因为您使它们无效......
  • pr 的元素是不可变的,但您正在尝试分配给它们。
  • 除了SirDarius的评论,你更新了你的代码,但没有更新错误。
  • @all 我的问题很简单:如何从函数返回对,我无法弄清楚为什么我在这里问...但我不知道为什么这个问题有这么多的消极情绪,我没有问编译,我只是问编译的原因。谢谢

标签: c++ map


【解决方案1】:

类型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();
}

【讨论】:

  • 如果你只使用一个返回,代码会更清晰:return iter == myMap.end() ? pr() : iter-&gt;second;iter-&gt;second的使用也比(*iter).second更惯用。)
  • 当然,您通常会将参数作为对 const 的引用传递。
  • @JamesKanze 我同意。我认为代码存在一些问题,问题最初是围绕编译错误,包含等。我在这里只关注const
猜你喜欢
  • 2015-12-15
  • 1970-01-01
  • 2019-10-13
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 2021-07-20
相关资源
最近更新 更多