我正在编写代码,其中 1 个更多的可变长度对象存储为所有单位的 vector ,即假设每个字母都是一个单位,并且相同的字母是相同的高级对象。 该 vector 可能包含如下内容:aaaabbcccdeeffff...
这个 vector 是一个类的内部私有(private)变量,它有一个 operator[] 定义为上面的 vector
- obj[0] returns an const_iterator to the first "a"
- obj[1] to the first "b"
- obj[2] to the first "c" etc.
const AI::GeneArray::const_iterator& AI::Chromosome::operator[](int index) const {
GeneArray::const_iterator pGene;
int cIndex;
for (cIndex=0,pGene = this->vGenes.cbegin();pGene != this->vGenes.cend();pGene++, cIndex++) {
if (index == cIndex) { break; }
(*pGene)->EndOfBlock(pGene); }
return pGene; }
然后在另一个函数中我有以下内容
AI::GeneArray::const_iterator function = vChromosome[0];
这会导致访问冲突错误。
我的函数上面的调用栈如下
AI.exe!std::_Vector_const_iterator<std::_Vector_val<AI::Gene *,std::allocator<AI::Gene *> > >::_Vector_const_iterator<std::_Vector_val<AI::Gene *,std::allocator<AI::Gene *> > >(const std::_Vector_const_iterator<std::_Vector_val<AI::Gene *,std::allocator<AI::Gene *> > > & __that) + 0x2f byte
AI.exe!std::_Iterator012<std::random_access_iterator_tag,AI::Gene *,int,AI::Gene * const *,AI::Gene * const &,std::_Iterator_base12>::_Iterator012<std::random_access_iterator_tag,AI::Gene *,int,AI::Gene * const *,AI::Gene * const &,std::_Iterator_base12>(const std::_Iterator012<std::random_access_iterator_tag,AI::Gene *,int,AI::Gene * const *,AI::Gene * const &,std::_Iterator_base12> & __that) + 0x2f bytes
AI.exe!std::_Iterator_base12::_Iterator_base12(const std::_Iterator_base12 & _Right) Line 118
AI.exe!std::_Iterator_base12::operator=(const std::_Iterator_base12 & _Right) Line 123 + 0x5 bytes
最后的电话是
_Iterator_base12& operator=(const _Iterator_base12& _Right)
{ // assign an iterator
if (_Myproxy != _Right._Myproxy)
_Adopt(_Right._Myproxy->_Mycont);<- This line
return (*this);
}
根据我的调试器(Visual C++ 2010 Express)
_Right._Myproxy->
_Mycont = CXX0030: Error: expression cannot be evaluated
_Myfirstiter = CXX0030: Error: expression cannot be evaluated
在我项目的其他地方,我有类似的代码使用 std::list,而不是正确工作的 vector
parents = new ChromosomeList::const_iterator[C];
*(parents) = --(this->vChromosomes.cend());
for (int i=1;i<C;i++) {
*(parents+i) = ChromosomeList::const_iterator((*(parents+i-1)));
(*(parents+i))--; }
我检查了返回的值
v染色体[0]
这个值是正确的类型,
const AI::GeneArray::const_iterator &
我在谷歌上搜索了类似的问题,我所能找到的都是与使用迭代器循环 vector 相关的问题
即
for (AI::GeneArray::const_iterator pGene = Genes.cbegin();pGene != Genes.cend();pGene++)
我项目中的此类代码运行正常。
最佳答案
AI::GeneArray::const_iterator function = vChromosome[0];
不应编译。 function
是一个迭代器,但您试图将它设置为某个值的内容的值。您确定不想用 vChromosome.begin()
代替吗?
假设这只是一个拼写错误,您的错误不会出现在分配发生的地方,您的错误会出现在之前的某个地方。例如,vChromosome
可能为空,在这种情况下尝试访问 operator[](0)
会导致未定义的行为。 (先看看 vector 是否有效!)
(旁注,
parents = new ChromosomeList::const_iterator[C];
为什么要手动管理这样的阵列?这不是 vector
的用途吗? :)
)
关于c++ - std vector const_iterator 赋值访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6566785/