2

I have a function and I am passing an iterator and a string to check whether the iterator is pointing to the first element or not. However, I am getting unexpected results.

int main()
{
 std::string str="abc";
 std::string::iterator strit = str.begin();
 iteratorProperty(strit, str);
}

void iteratorProperty(std::string::iterator it, std::string str) {
//std::next(it);
int count = 0;
for(auto i = it; i <str.end();i++) {

    count++;
}
std::cout<<count<<std::endl;
}

This cout statement is returning me a value of 51. Could anyone please help me understand this?

Thank You.

goodfellas95
  • 35
  • 1
  • 6
  • 5
    `str` is a copy. your begin and end iterators are incompatible, they belong to different strings. – tkausl Mar 01 '19 at 20:08
  • Thank you. I fixed it. I am so Stupid. This was a dumb question. – goodfellas95 Mar 01 '19 at 20:10
  • @goodfellas95 No, the question is a valid one. Maybe just remove the confusing main() line, since you neither open nor close the function body. And tell the expected value ;-) – Christophe Mar 01 '19 at 20:14

1 Answers1

1

I was passing a shallow copy instead of a deep copy.

That's why I was getting undefined values.

Correct signature:

void iteratorProperty(std::string::iterator it, std::string& str) {
goodfellas95
  • 35
  • 1
  • 6
  • 1
    When you pass by reference there is no copying at all. You are literally using the object from the call site in the function. – NathanOliver Mar 01 '19 at 20:14
  • 2
    Another change that you should consider is to avoid `<` with iterators and prefer `!=` (see here why: https://stackoverflow.com/q/38121032/3723423) – Christophe Mar 01 '19 at 20:17