Vector container is one of the most common containers in STL (Standard Template Library), and it is often necessary to traverse vector container in design, this article introduces three kinds of commonly used vector traversal methods.
One, subscript index traversal
The bottom of a vector container is actually a wrapper for a dynamic array, so the [] operator is overloaded inside it.
The function prototypes are as follows:
The elements inside the vector can therefore be accessed in a similar manner to the array elements.
Example code:
Vector container Traversal method The subscript traversal of
void traversevector_1 (vector<int> v)
{for
(unsigned int i = 0; i < v.size (); ++i)
{
cout<<v[i]<< "";
}
cout<<endl;
}
Second, iterator traversal
Similar to how pointers to array elements are accessed, the second way to traverse vectors is to use iterators (one of the iterator smart pointers).
"The bottom of the iterator is the encapsulation of the native pointer"
Example code:
#include <iostream>
#include <vector>
using namespace std;
Vector container traversal mode 2--iterator traversal
void traversevector_2 (vector<int> v)
{
//NOTE: If the parameter is const vector<int> Need to use const_iterator
vector<int>::iterator it = V.begin ();
Vector<int>::const_iterator Iter=v.begin ();
for (; it! = V.end (); ++it)
{
cout<< (*it) << "";
}
cout<<endl;
}
Third, copy function traversal
The third way to traverse vectors is to use the copy function in the generic algorithm "inside is a template function"
Take a general look at its internal implementation:
The approximate format for calling the copy function is copy (begin, end, it);
The third parameter is an iterator that can use an output stream iterator when traversing a vector ostream_iterator
Example code:
#include <iostream>
#include <vector>
using namespace std;
Vector container Traversal mode 3--cpoy function traverses
void traversevector_3 (vector<int> v)
{
copy (V.begin (), V.end (), Ostream_iterator<int> (cout, ""));
cout<<endl;
}
Turn from:
Http://www.tuicool.com/articles/yUfQFnA
Thank you for that.