TGC Codebase Backup



Iterating through a vector and edit values via iterator by Dar13

17th Jul 2010 14:30
Summary

Shows how to go through a vector and change the value of a vector using an iterator.



Description

First, we declare and initialize our vector(testVector), by pushing 3 values onto the back.
Then we use a for loop to increment the iterator through the vector until the end is reached. As it goes through the vector, it increments the value the iterator is pointing to by 1(*itr+=1).
The for loop also prints the new values to the console.
Then the program waits for two return key presses to return to windows.



Code
                                    ` This code was downloaded from The Game Creators
                                    ` It is reproduced here with full permission
                                    ` http://www.thegamecreators.com
                                    
                                    #include <vector>
#include <iterator>
#include <iostream>

int main()
{
	std::vector<int> testVector;
	std::vector<int>::iterator itr;
	testVector.push_back(10);
	testVector.push_back(20);
	testVector.push_back(30);
	for(itr=testVector.begin();
		itr!=testVector.end();
		++itr)
	{
		*itr+=1;
		std::cout<<*itr<<std::endl;
	}
	std::cin.get();
	std::cin.get();
	return 0;
}