错误推回对常量向量元素的引用
Error push back reference to elements of const vector
请考虑以下几点:
// 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>
的地址推送到非常量vector
。remaining
填满后,没有其他方法会更改其数据,因此实际上应该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;
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 设计将引用元素移动到开头的数据结构.C++
- 为什么通过 vector<reference_wrapper> 的元素删除引用的值<T>不会使向量无效?
- 将新元素添加到列表中,并返回对该元素的引用?
- 如何告诉自动推断向量<bool>元素的非引用类型
- 通过引用访问矢量元素是否会降低C++的空间复杂性?
- 通过引用传递时访问std::vector的元素
- 如何取消引用和打印指针数组的每个元素?
- 如何从模板获取常量矢量元素的引用
- 调整大小后保持对矢量元素的引用有效
- 取消引用C++中的指针元素
- 在这种情况下,如何返回对数组中元素的引用?
- C++ - 返回对矢量元素的引用
- 引用保留向量中的第一个元素
- C++ 当容器在使用前被破坏/修改时发出警告(通过引用元素或迭代器使用)
- 如何通过引用对用户定义对象的类型集 (STL) 的数组元素进行增强迭代?
- 如何理解取消引用指向数组的指针会获取指向元素的指针
- 如何将一个向量的元素引用复制到另一个向量?
- 通过[]运算符返回矢量元素引用