简体   繁体   中英

segmentation fault in iterator

I have created a multimap for my road points. The key refers to the road number and the values are vec3 points that make up the road.

I am trying to iterate through the values of each key point and create a road segment at each point on the road (except the last), adjust the values to be on the road points and then store them in a std::vector.

The RoadSegment constructor creates 6 vec3 points and pushes them onto a std::vector.

I have a segmentation fault in the line marked in bold [for(mapIt = it.first; mapIt != it.second; ++mapIt)]

When i take out the lines creating the new objects and pushing them onto the std::vector it works fine.

Can anyone tell me what the problem is / a solution to the problem??

Many thanks in advance

std::vector<glm::vec3>::iterator SegIt;

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::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)
    {

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

        if(distance != numberDesired)
        {
            RoadSegement* roadSegmentPointer = new RoadSegement();

            // FUNCTIONS TO ADJUST COORD VALUES TO MATCH THE ROAD POINTS


            m_segmentArray.push_back(roadSegmentPointer);

        }

        else
        {
            continue;
        }

         ///SOME BUFFER BINDING STUFF 

The issue seems to be that you're using iterators that do not exist, all due to returning a temporary object.

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

Since getMultiMapData() returns a copy of the multimap, that multimap is gone after the line is executed, thus rendering any iterators invalid.

One solution is to return a reference to the multimap, not a new copy of the multimap.

std::multimap<int, glm::vec3>& GenerateRoads::getMultimapData() { return m_roadsMultimap; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM