The advance and distance methods in stl are used to add and subtract iterator. Before traversing the vector, the addition and subtraction between iterator is often used to obtain the index of the element in the container.
Today, when performing addition and subtraction of list iterator, we found that the list cannot be compiled. The list is a non-linear container and cannot be added or subtracted.
I checked the information and found that stl provides two methods for addition and subtraction of iterator: advance and distance.
Advance is to move the iterator, while distance is to calculate the direct distance between the two iterator.
Template <typename _ InputIterator>
Inline typename
Iterator_traits <_ InputIterator >:: difference_type
Distance (_ InputIterator _ first, _ InputIterator _ last)
{
// Concept requirements -- taken care of in _ distance
Return std: :__ distance (_ first, _ last,
Std: :__ iterator_category (_ first ));
}
The first parameter is "first" and the second parameter is "last ".
The returned result is based on n in first + n = last
That is, based on the fact that last can be reached through n after first. Note that n may be negative.
The first time I used this operation, I reversed the order of the two parameters and returned negative n, which is the Index subscript corresponding to a number. As a result, the corresponding index element cannot be found.
The sample code is as follows:
std::vector<STableInfor>::iterator iter_begin = m_tableInfoList.begin(); std::vector<STableInfor>::iterator iter_end = m_tableInfoList.end(); int index = distance(iter_begin,iter_end);