-1

I have a loop that iterates through each of the each key and then each of the values for those keys. I create a RoadSegment for each point and want to use the values to set the coordinates of the RoadSegment. To do this I need the current vec3 that the iteration is on as well as the next in the sequence.

Is there a way to store the next iteration in the sequence so that I can reference the value (*next).second I have tried creating another std::multimap::iterator next and then setting next = mapIt++ but that seems to manipulate the mapIt value for the following loop so next on the previous is not the same as mapIt on the following loop

Many thanks in advance for your help.

    for(int i = 0; i < m_genRoads->getKeyValueData().size(); i++)
{
    int numberDesired = m_genRoads->getMultimapData().count(i) - 1;

    std::multimap<int, glm::vec3>::iterator mapIt;
    std::multimap<int, glm::vec3>::iterator next;
    std::pair<std::multimap<int, glm::vec3>::iterator, std::multimap<int, glm::vec3>::iterator> it;

    it = m_genRoads->getMultimapData().equal_range(i);

    for(mapIt = it.first; mapIt != it.second; mapIt++)
    {
        next = mapIt++;

        int distance = std::distance(it.first, mapIt);

        if(distance != numberDesired)
        {
            std::cout<<"MAKE ROAD SEGMENT"<<std::endl;
            RoadSegement* roadSegmentPointer = new RoadSegement();
            **roadSegmentPointer->setYcoord((*mapIt), (*next));
            roadSegmentPointer->setXcoord((*mapIt));**
            m_segmentArray.push_back(roadSegmentPointer);
        }

        else
        {
            std::cout<<"..................."<<std::endl;
            continue;
        }
willgosling
  • 23
  • 2
  • 6

1 Answers1

0

Read about how the preincrement and postincrement operators work. In particular, the postincrement (mapIt++) will set next to the current value of mapIt and then increment mapIt. In practice, it's as if you've swapped the two so that next points to the current object and mapIt points to the next object. Also, when the loop continues, the mapIt++ there will cause you to skip the next object! I'd bet you didn't intend for that.

for ( mapIt = it.first; mapIt != it.second; mapIt++ )
{
    next = mapIt;
    ++next; // note that preincrement is generally faster for iterators
    if ( next == it.second ) {
        // Uh oh, next is pointing to your end object, so there is no next object! Now what??
    }
    /* do work */
}
inetknght
  • 4,300
  • 1
  • 26
  • 52