Why can't I make a vector of references?

前端 未结 9 742
梦如初夏
梦如初夏 2020-11-22 03:32

When I do this:

std::vector hello;

Everything works great. However, when I make it a vector of references instead:



        
9条回答
  •  死守一世寂寞
    2020-11-22 04:14

    As the other comments suggest, you are confined to using pointers. But if it helps, here is one technique to avoid facing directly with pointers.

    You can do something like the following:

    vector iarray;
    int default_item = 0; // for handling out-of-range exception
    
    int& get_item_as_ref(unsigned int idx) {
       // handling out-of-range exception
       if(idx >= iarray.size()) 
          return default_item;
       return reinterpret_cast(*iarray[idx]);
    }
    

提交回复
热议问题