Use the advance and distance methods in stl to add and subtract iterator

Source: Internet
Author: User
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);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.