相关疑难解决方法(0)

当std :: map :: at去out_of_range时要返回什么?

在游戏中,我想搜索项目地图并返回位于棋盘特定方块上的项目.但如果广场是空的怎么办?(这些项目没有存储在董事会结构中.对于这个问题,我没关系.)我有下面的代码,但是我应该怎样做才能返回"空"参考?

map<pair<int, int>, Item*> _items;

Item& itemAt(int row, int col) const {
    try {  
        return *_items.at(make_pair(row, col));
    } catch(out_of_range& e) {
        return // what goes here?            
    } 
}
Run Code Online (Sandbox Code Playgroud)

或者这是错误的方法,我应该使用find()

c++ exception c++11

8
推荐指数
2
解决办法
600
查看次数

返回数组元素时,非const引用的初始化无效

我正在编写一个包装动态分配数组的类,我正在尝试编写operator []函数.目前我有:

bool& solution::operator[](unsigned int pos)
{
  if(pos < _size)
  {
    return this->_data[pos];
  }
  else
  {
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我从g ++中得到以下错误:

error: invalid initialization of non-const reference of type ‘bool&’ from an rvalue of type ‘bool’

我该怎么做?我需要[]运算符才能修改元素.

c++

0
推荐指数
1
解决办法
2680
查看次数

标签 统计

c++ ×2

c++11 ×1

exception ×1