错误推回对常量向量元素的引用

Error push back reference to elements of const vector

本文关键字:元素 引用 向量 常量 错误      更新时间:2023-10-16

请考虑以下几点:

// from main file
// first arguement gets enc_array
Rock rock (voice.getEncArray());
// getEncArray() gets a vector of vectors:
// std::vector<std::vector<unsigned int> > enc_array;
// in rock.hpp file, consider members
Rock( const std::vector<std::vector<unsigned int> > &);
std::vector<std::vector<unsigned int> * > remaining;
const std::vector<std::vector<unsigned int> > * population;
// in rock.cpp
Rock::Rock ( const vector<vector<unsigned int> > & v) :
  population (&v),
  ....
// in one of the class member functions
for ( vector<vector<unsigned int> >::const_iterator ci = population->begin(); ci != population->end(); ++ci ) {
    // for some indexes...
    remaining.push_back (& (*ci));      // <------  PROBLEM
}

海湾合作委员会报告:

error: no matching function for call to 'std::vector<std::vector<unsigned int>*>::push_back(const std::vector<unsigned int>*)'
note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::vector<unsigned int>*; _Alloc = std::allocator<std::vector<unsigned int>*>; std::vector<_Tp, _Alloc>::value_type = std::vector<unsigned int>*] <near match>
note:   no known conversion for argument 1 from 'const std::vector<unsigned int>*' to 'std::vector<unsigned int>* const&'

我知道我正在尝试将被认为const vector<int>的地址推送到非常量vectorremaining填满后,没有其他方法会更改其数据,因此实际上应该const。但我不能将remaining声明为const vector,因为它会给出错误。

error: no matching function for call to 'std::vector<std::vector<unsigned int>*>::push_back(const std::vector<unsigned int>*) const'
note: candidate is:
note: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::vector<unsigned int>*; _Alloc = std::allocator<std::vector<unsigned int>*>; std::vector<_Tp, _Alloc>::value_type = std::vector<unsigned int>*] <near match>
note:   no known conversion for argument 1 from 'const std::vector<unsigned int>*' to 'std::vector<unsigned int>* const&'

我真的需要将元素从population复制到remaining吗?或者我还能做些什么来避免这种开销?

您正在获取 population 元素的地址,以后可以更改它。这很糟糕,因为您指定了要const population

如果要更改 population 的元素,则应从population定义中删除 const 关键字,然后使用 iterator 而不是 const_iterator

尝试

std::vector<const std::vector<unsigned int> *> remaining;