关于 C++ Primer 中 Iterator Arithmatic(迭代器)的思考

关于 iter1 - iter2

在C++ Primer(English Version Page 111)的Table 3.7有:

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.

对于这句话可能有些难以理解。但首先,产出的是个数字。而这个数字即位置差((signed) location distance)(如此方便记忆)(当然是signed的了),而非像 iter - n 这样输出那个位置上的vector中存储的值。在做Exercise 3.24(b)时将概念混淆,下面通过test来试验,如下图:
test程序界面

关于 - - ivec.end()

书在107页的note上说不能被incremented或dereferenced的。注意:不要想当然,不能被incremented而被subtracted是可以的。
以下程序(Exercise 3.24(b))可以运行。

#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;
}

类似地,在P119的note中说"We may not dereference or increment an off-the-end pointer.”也就是pointer指向end(/* */)时不可以间接访问或++。

以下为试验程序:

#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 的导航页

猜你喜欢

转载自blog.csdn.net/weixin_50012998/article/details/108123835