【问题标题】:C++ iterator for vector of struct Compiler Error Askstruct 向量的 C++ 迭代器编译器错误
【发布时间】:2019-02-14 22:55:46
【问题描述】:

为什么这段代码适用于函数参数?

void GameBoard::showField(std::vector<int> newBoard) const {
    for (std::vector<int>::iterator it = newBoard.begin(); it < newBoard.end(); it++) {
        std::cout << ' ' << *it;
    }
    std::cout << '\n';
}

类属性不起作用

void GameBoard::showField() const {
    for (std::vector<int>::iterator it = this->board.begin(); it < this->board.end(); it++) {
        std::cout << ' ' << *it;
    }
    std::cout << '\n';
}

【问题讨论】:

标签: c++ stdvector


【解决方案1】:

您的函数参数是std::vector&lt;int&gt;。因此,.begin() 给了你一个很好的std::vector&lt;int&gt;::iterator。这与您的循环中的用法相匹配。

但是,当通过 const 成员函数(如 showField)访问时,您的成员也是 const。在这种情况下,它现在是 const std::vector&lt;int&gt;。因此,.begin() 会为您提供 std::vector&lt;int&gt;::const_iterator

您明确写出了std::vector&lt;int&gt;::iterator,但两者不匹配。

您无需修改​​这些值,因此只需坚持使用 std::vector&lt;int&gt;::const_iterator 或您知道的 auto

我的意思是,你真正想要的是这样的:

void GameBoard::showField() const
{
   for (const auto& el : board)
      std::cout << ' ' << el;

   std::cout << '\n';
}

理想情况下也将流作为参数:

std::ostream& GameBoard::showField(std::ostream& os) const
{
   for (const auto& el : board)
      os << ' ' << el;

   os << '\n';
   return os;
}

现在我们正在讨论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多