Thinking about Iterator Arithmatic in C++ Primer

About iter1-iter2

Table 3.7 in C++ Primer (English Version Page 111) has:

Subtracting two iterators yields the number that when added to the right-hand iterator yields the left-hand iterator. The iterators must denote elements in, or one past the end of, the same container.

It may be difficult to understand this sentence. But first, the output is a number. And this number is the location difference ((signed) location distance) (so easy to remember) (of course it is signed), instead of outputting the value stored in the vector at that location like iter-n. When doing Exercise 3.24(b), the concept was confused. The following is a test through test, as shown in the figure below:
test program interface

About--ivec.end()

The book says in the note on page 107 that it cannot be incremented or dereferenced. Note: Don’t take it for granted, it’s okay not to be incremented but subtracted .
The following program (Exercise 3.24(b)) can be run.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    
    
	vector<int> ivec;
	int i;
	while (cin >> i)
		ivec.push_back(i);
	for (auto it = ivec.begin(), IT=--ivec.end(); it != ivec.begin() + ivec.size() / 2; ++it, --IT)
		cout << *it + *IT << " ";
	if (ivec.size() % 2 == 0) cout << endl;
	else cout << *(ivec.begin() + ivec.size() / 2 )<< endl;
	return 0;
}

Similarly, in the P119 note, it says " We may not dereference or increment an off-the-end pointer ." That is, when the pointer points to end (/* */), it cannot be accessed indirectly or ++.

The following is the test procedure:

#include <iostream>
#include <iterator>
using namespace std;

int main()
{
    
    
	int a[] = {
    
     0,1,2,3,4 };
	int* p = end(a);
	cout << *p << endl;
	--p;
	cout << *p << endl;
	return 0;
}

Result:

-858993460
4


See also

Teddy van Jerry's navigation page

Guess you like

Origin blog.csdn.net/weixin_50012998/article/details/108123835