收到有关_Vector_const_iterator不可转换为_Vector_iterator的错误

Getting an error about a _Vector_const_iterator not being convertible to a _Vector_iterator

本文关键字:Vector iterator 可转换 错误 const      更新时间:2023-10-16

我目前是C++编程新手,我正在尝试制作一个数独求解器。但是,我在返回单元格候选列表(单元格可能是的可能值列表(的方法时遇到问题。候选列表是一个向量。这就是我目前尝试这样做的方式,但是它出现了一个错误:

 int Cell::getCandidateList(void) const
{
int i;
for (vector<int>::iterator j = m_candidateList.begin(); j <       m_candidateList.end(); j++)
{
    i = *j;
}
  return i;
 }

这就是它在头文件中的声明方式:

 int getCandidateList(void) const; //create method to get candidate list

错误似乎在 m_candidateList.begin 上,错误显示:

严重性代码说明项目文件行抑制状态错误(活动(不存在从"std::_Vector_const_iterator>>"到"std::_Vector_iterator>>"的合适用户定义转换

好吧,首先,您不会从此函数返回向量,您只是重复重新分配一个整数值... :-(

但至于你得到的错误:你试图强迫你的迭代器成为一个非常量向量迭代器,通过它可以修改元素 - 这不是你想要的。尝试:

for (vector<int>::const_iterator j = m_candidateList.begin(); j < m_candidateList.end(); j++)

或:

for (auto j = m_candidateList.begin(); j < m_candidateList.end(); j++)

或者更好的是,使用 C++11 语法:

for (const auto& e : m_candidateList) { }

。在这种情况下,在每次迭代中,e 是对向量中连续整数的常量引用。