Iterators


Tip
An iterator can be used to navigate from the beginning to end of the container. An asterisk is places before an iterator to access the object in the container as shown in the problem below.
Un iterador puede ser usado para navegar desde el principio al final de un contenedor. Un asterisco se coloca antes de un iterador para tener acceso al objeto en el contenedor como se muestra en el problema de abajo.

Problem 1
Create project called Sumador as shown below to compute the summation of the elements of an array. Use the template vector and iterators.
Cree un proyecto llamado Sumado como se muestra debajo para calcular la suma de los elementos de un arreglo. Use la plantilla vector y los iteradores.

Program.cpp

void Program::SomeFunction()
{
     vector<double> input;
     input.push_back(10.4);
     input.push_back(-2.45);
     double sum = 0.0;

     for(vector<double>::iterator p = input.begin(); p != input.end(); p++)
     {
          sum += *p;
     }
}


Tip
The following code illustrates how to use reverse iterators to iterate a STL container backwards.
El siguiente código ilustra cómo usar los iteradores de reversa para iterar un contenedor de la STL al revés.

Program.cpp

void Program::SomeFunction()
{
     vector<double> input;
     input.push_back(10.4);
     input.push_back(-2.45);
     double sum = 0.0;

     for(vector<double>::reverse_iterator p = input.rbegin(); p != input.rend(); p++)
     {
          sum += *p;
     }
}


const_iterator and const_reverse_iterator

Use const_iterator instead of iterator when it is necessary to iterate a STL container without altering the content of the container. In first program, we use an iterator because the content of the vector is being altered. In the second program, we use a const_iterator because the content of the vector is not being altered during the execution of the for loop.
Use const_iterator en lugar de iterator cuando se necesario iterar un contenedor de la STL sin alterar el contenido del contenedor. En el primer programa, se usa un iterador porque el contenido del vector se altera. En el segundo programa, se usa un cons_iterator porque el contenido del vector no se altera durante la ejecución del for.

Program.cpp

void Program::SomeFunction()
{
     vector<double> input;
     input.resize(4);
     for(vector<double>::iterator p = input.begin(); p != input.end(); p++)
     {
          *p = 10.0;
     }
}


Program.cpp

void Program::SomeFunction()
{
     vector<double> input;
     double sum = 0.0;
     for(vector<double>::const_iterator p = input.begin(); p != input.end(); p++)
     {
          sum += *p;
     }
}

© Copyright 2000-2021 Wintempla selo. All Rights Reserved. Jul 22 2021. Home