-4

why this code works with the function argument?

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';
}

with class property not work

void GameBoard::showField() const {
    for (std::vector<int>::iterator it = this->board.begin(); it < this->board.end(); it++) {
        std::cout << ' ' << *it;
    }
    std::cout << '\n';
}
mch
  • 9,424
  • 2
  • 28
  • 42
Johnny K.
  • 41
  • 1
  • 4
  • `this->board` is `const` in the function, so you need a `const_iterator`. – mch Sep 10 '18 at 13:32
  • Define what you mean by "_works_", and "_doesn't work_" I suspect that the code doesn't compile due to you needing to use `const_iterator`. – Algirdas Preidžius Sep 10 '18 at 13:32
  • Is the compiler error a secret? A mystery? Where is your [MCVE]? – Lightness Races in Orbit Sep 10 '18 at 13:32
  • @mch Answers go in the answer section please and thank you – Lightness Races in Orbit Sep 10 '18 at 13:33
  • 1
    Possible duplicate of [what is the difference between const\_iterator and iterator?](https://stackoverflow.com/questions/5346890/what-is-the-difference-between-const-iterator-and-iterator) – mch Sep 10 '18 at 13:33
  • Please read [the help pages](http://stackoverflow.com/help), especially ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask) and [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). Lastly learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Sep 10 '18 at 13:34

1 Answers1

1

Your function argument is a std::vector<int>. As such, .begin() gives you a nice std::vector<int>::iterator. This matches the usage in your loop.

However, your member, when accessed via a const member function like showField, is also const. It is now a const std::vector<int> in that context. As such, .begin() gives you a std::vector<int>::const_iterator instead.

You wrote out std::vector<int>::iterator explicitly though and the two don't match.

You don't modify the values so just stick with std::vector<int>::const_iterator or, y'know, auto.

I mean, really what you want is this:

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

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

Ideally take the stream as an argument too:

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

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

Now we're talking.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055