【问题标题】:Dereferencing a reference not working取消引用引用不起作用
【发布时间】:2017-03-26 20:22:03
【问题描述】:

我有一个返回向量中位数的函数:

unsigned int Class::Median() const {    
    sort(m_Transactions.begin(), m_Transactions.end(), cmpInt);

    if (m_Transactions.size() != 0) {
        if ( m_Transactions.size()%2 == 0 ) {
            return *m_Transactions[ m_Transactions.size()/2 + 1 ];
        } else {
            return *m_Transactions[ m_Transactions.size()/2 ];
        }
    }

    return 0;
}

向量是vector<unsigned int> m_Transactions。据我了解,[] 运算符返回对数组中元素的引用。我不想返回引用,而是返回元素。所以我取消引用*。编译器错误状态:invalid type argument of unary '*'...

但是,如果我删除“*”:

if ( m_Transactions.size()%2 == 0 ) {
    return m_Transactions[ m_Transactions.size()/2 + 1 ];
} else {
    return m_Transactions[ m_Transactions.size()/2 ];
}

由于assignment of read-only location...,构建失败

其余代码HERE

我该如何解决这个问题?为什么取消引用不起作用?

【问题讨论】:

  • 您不能取消引用引用,除非它是对指针的引用。只需使用 [] 运算符返回的内容,就好像它是一个值一样。并阅读一本好的 C++ 教科书。
  • 你第一次返回可能会报错:if size == 2, size / 2 + 1 = 2
  • 从函数中删除const,看看是否有效......
  • 删除const 解决了这个问题,非常感谢。但是,由于分配,const 必须在那里。
  • 那么,您必须将m_transactions 复制到一个新变量中,然后对该变量进行排序并从中获取中位数,因为排序会修改它所排序的内容。

标签: c++ pointers vector reference


【解决方案1】:

您确实需要取消引用使用*operator[] 索引已经为您取消引用 std::vector 中的值。

见下文:

更新

std::vector<unsigned int> ret = m_Transactions; // Use auxiliary ret vector to return while maintaining the const in your function signature.
std::sort(ret.begin(), ret.end(), cmpInt);
if (ret.size() != 0) {
    if (ret.size()%2 == 0 ) {
        return ret[ ret.size()/2 + 1 ]; // remove the * dereference operator
    } else {
        return ret[ ret.size()/2 ];  // remove the * dereference operator
    }
}

【讨论】:

  • 如果我这样做,构建会由于assignment of read-only location...而失败
  • @HichigayaHachiman 您提供的代码没有分配(var a = x)。错误必须来自其他地方
  • 删除函数签名末尾的 const
  • 这行得通,不幸的是,任务不允许我删除它。任何解决方法?我还编辑了其余代码。
  • 立即尝试...这是 const 函数的解决方法。
猜你喜欢
  • 2021-11-18
  • 1970-01-01
  • 2019-09-02
  • 2016-11-18
  • 2016-02-16
  • 2018-10-24
  • 2015-07-03
  • 2012-06-24
  • 2014-10-12
相关资源
最近更新 更多