0

I have the following Code in my project:

std::cout << "Without iterator:\n";

std::vector<RectangleCluster*> rc = p->getInnerRegionPolygons().at(0)->getClusters();

for (int i = 0; i < rc.size(); i++)
     std::cout << "Cluster " << rc.at(i)->getId() << ": start = " << rc.at(i)->getOverlapAtStart() << ", end = " << rc.at(i)->getOverlapAtEnd() << std::endl;

std::cout << "\n\nWith iterator:\n";

for (std::vector<RectangleCluster*>::iterator ci = p->getInnerRegionPolygons().at(0)->getClusters().begin(); ci != p->getInnerRegionPolygons().at(0)->getClusters().end(); ++ci)
    std::cout << "Cluster " << (*ci)->getId() << ": start = " << (*ci)->getOverlapAtStart() << ", end = " << (*ci)->getOverlapAtEnd() << std::endl;

The console output looks like this:

Without iterator:
Cluster 0: start = 65.4238, end = 64.9811
Cluster 1: start = 64.9811, end = 17.9983
Cluster 2: start = 17.9983, end = 17.9983...

With iterator:
Cluster 34026352: start = 1.68113e-316, end = 1.68113e-316
Cluster 1: start = 64.9811, end = 17.9983
Cluster 2: start = 17.9983, end = 17.9983...

The output after "..." is also equal. Why does the code without iterator give me "Cluster 0: start = 65.4238, end = 64.9811" and the code with the iterator "Cluster 34026352: start = 1.68113e-316, end = 1.68113e-316"?

Best regards Gernot

  • 2
    There's not really enough information here to say with any certainty. (In general a *minimal* complete example makes questions a lot easier to answer). Does `p->getInnerRegionPolygons().at(0)->getClusters()` return by value or by reference? I'd bet the former – Flexo Feb 12 '12 at 10:04
  • If this is by value, your iterator is initialized with one vector copy and the checking is done against another the iterator end of another copy !! Not sure what is the effect in this case. Can you try by initializing the array to a single variable and taking the iterator OR expose an interface of p->getInnerRegionPolygons().at(0) to provide the iterator out? – PermanentGuest Feb 12 '12 at 10:32

1 Answers1

3

Please rewrite your code with iterators like:

for (std::vector<RectangleCluster*>::iterator ci = rc.begin(); ci != rc.end(); ++ci)
    std::cout << "Cluster " << (*ci)->getId() << ": start = " << (*ci)->getOverlapAtStart() << ", end = " << (*ci)->getOverlapAtEnd() << std::endl;

I agree with awoodland's comment. Most likely p->getInnerRegionPolygons().at(0)->getClusters() returns new vector every call. And it is incorrect to compare iterators from different containers inside for( ... ) operator.

alexander
  • 2,703
  • 18
  • 16