-4

I get different results iterating through the same vector using two different methods. Why?

When I iterate through a vector using what I understand to be the preferred method I get back junk. If use a different method it works fine. Why am I getting inconsistent results depending on the method I choose?

for(vector <NgramOutput*>::iterator sausage = (*sausageCarton)->getSausageBox().begin(); sausage != (*sausageCarton)->getSausageBox().end(); ++sausage){
  dosomething(*sausage);
}

for (int i=0; i < sausage.size(); i++) {
  dosomething(sausage[i]);
}

As far as I know both should do basically the same thing (although there may be differences in speed?) but for me the first one produces junk such as invalid or null pointers scattered throughout. The second method gives the expected results.

Derek Seabrooke
  • 123
  • 1
  • 2
  • 5
    Does `getSausageBox()` return the vector by value? If so your start and end iterators are associated with two different vectors. That's UB. – G.M. Feb 09 '19 at 14:32
  • 3
    Hard to say. The code provided does not compile. Do you have a [mcve]? – Eljay Feb 09 '19 at 14:35
  • G.M. please post as answer. – Derek Seabrooke Feb 09 '19 at 14:48
  • What is `sausageCarton` and `getSausageBox`? Also, your 2 `sausage` variables are not of the same type? **If you want help, then at least put some effort in your question**. As written, many information are missing or misleading and the code **does not even compile** – Phil1970 Feb 09 '19 at 14:48
  • This is probably a dupe of ["comparing iterators from different containers"](https://stackoverflow.com/questions/4657513/comparing-iterators-from-different-containers). – G.M. Feb 09 '19 at 14:50

1 Answers1

0

In your case * operator returns to you the item referenced by the iterator, which is a pointer NgramOutput* (from your declaration).

In order to use the object you need to dereferentiate that pointer (**sausage)

bogdan tudose
  • 1,064
  • 1
  • 9
  • 21
  • Not if `dosomething` takes an `NgramOutput*` pointer argument. (Which might be questioned from a design perspective, but is certainly technically valid.) – aschepler Feb 09 '19 at 15:43