Use the advance and distance methods in STL to carry out iterator addition and subtraction

Source: Internet
Author: User
use the advance and distance methods in STL to carry out iterator addition and subtractionIn the past, when traversing vectors, the addition and subtraction of iterator were often used to obtain the index of elements in the container.
Today in the list of iterator addition and subtraction, found that can not compile through, the back of the list is a non-linear container, can not be added and reduced.
Check the data, found that STL has provided two iterator Plus and minus methods: advance and distance
Advance is the iterator move, and distance is the calculation of two iterator direct distances.

Template<typename _inputiterator>

Inline typename Iterator_traits<_inputiterator>::d Ifference_type

Distance (_inputiterator __first, _inputiterator __last)

{

Concept requirements--taken care of in __distance

Return Std::__distance (__first, __last,

Std::__iterator_category (__first));

}


First argument, second argument last

Returns based on the N in the top + n = Last, in


That is, the last is reachable from the top through N, and note that n can be negative.

The first time I use this is to reverse the order of two parameters, and return the negative n, and I am the index subscript for a number, which results in the corresponding index element not found.

The example 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.