willgosling
willgosling

Reputation: 23

How to check if what an iterator points to exists

I have a loop that iterates through a vector of classes. It finds a std::vector within the class and find a glm::vec3 at a particular element. Within the loop I have a iterator that points to the next class.

I use this data to calculate some vectors.

How do I check that (*nextSegIt) actually exists? When segIt reaches the last element it will point somewhere random I guess.

I have tried an if statement to check if it is NULL or if it is the end of the vector array but neither will compile.

Does anyone have any advice?

Thanks in advance.

std::vector<RoadSegement*>::iterator segIt;
std::vector<RoadSegement*>::iterator nextSegIt;

for (segIt = nextSegIt = m_segmentArray.begin(); segIt != m_segmentArray.end(); segIt++)
{
    nextSegIt++;
    (*segIt)->calculateVectors((*segIt)->getRoadSegmentCoords().at(3), (*segIt)->getRoadSegmentCoords().at(2), (*nextSegIt)->getRoadSegmentCoords().at(3));
}

RoadSegment constructor

RoadSegement::RoadSegement()
{
    m_roadSegment.push_back(glm::vec3(-1, +1, 0));
    m_roadSegment.push_back(glm::vec3(-1, -1, 0));
    m_roadSegment.push_back(glm::vec3( 0, +1, 0));
    m_roadSegment.push_back(glm::vec3( 0, -1, 0));
    m_roadSegment.push_back(glm::vec3(+1, +1, 0));
    m_roadSegment.push_back(glm::vec3(+1, -1, 0));

    m_roadWidth = 0.5;
    scale(m_roadWidth);
}

calculateVectors() function:

void RoadSegement::calculateVectors(glm::vec3 _point, glm::vec3 _nextPoint, glm::vec3 _nextNextPoint)
{
    glm::vec3 vector0 = glm::vec3(m_roadSegment.at(2) - _point);
    glm::vec3 vector1 = glm::vec3(m_roadSegment.at(1) - _point);
    glm::vec3 vector2 = glm::vec3(m_roadSegment.at(5) - _point);
    glm::vec3 vector3 = glm::vec3(_nextNextPoint - _nextPoint);
    glm::vec3 vector4 = glm::vec3(m_roadSegment.at(0) - _nextPoint);
    glm::vec3 vector5 = glm::vec3(m_roadSegment.at(4) - _nextPoint);

    m_segmentVectors.push_back(vector0);
    m_segmentVectors.push_back(vector1);
    m_segmentVectors.push_back(vector2);
    m_segmentVectors.push_back(vector3);
    m_segmentVectors.push_back(vector4);
    m_segmentVectors.push_back(vector5);
} 

Upvotes: 0

Views: 357

Answers (1)

Mooing Duck
Mooing Duck

Reputation: 66922

Simple enough: check if nextSegIt == m_segmentArray.end(). If so, the element doesn't exist.

If there is no NextNextPoint, you'll have to call a different function obviously. You could pass a dummy value, but that's not recommended.

Upvotes: 2

Related Questions