Why do I need to dereference iterators?

假如想象 提交于 2021-02-05 12:22:33

问题


Why do I need to dereference iterators? For example in the following program

#include <iostream>
#include <string>
#include <vector>

int main()
{
    using namespace std;
    string s("some string");

    for(auto it = s.begin(); it != s.end(); && !isspace(*it); ++it)
        *it = isupper(*it);
    cout<<s;
}

Why is it necessary to use isupper(*it); instead of just isupper(it);?


回答1:


Iterator is a generalized pointer. It points to something. If you have a function that needs that something(char or int, in this case), not the "pointer" itself, you need to dereference the iterator.

For example, the standard advance function takes an iterator as its argument. Therefore you pass the iterator without dereferencing it, as in

std::advance(it, n);

But if you have an iterator that points to an int and you want to increment that integer by 4, you need

(*it) += 4;

I suggest that you should read a good book on C++.

By the way, your entire loop can be replaced by a single call to transform

 std::transform(s.begin(), s.end(), s.begin(), toupper);



回答2:


You need to be able to perform operations on the iterator itself e.g. your code does it != s.end() and ++it

And sometimes you need to be able to perform operations on the object the iterator points to, e.g. isupper(*it)

There has to be some operation to indicate you want to refer to the thing it refers to not the iterator itself, otherwise if you test if (it == another_it) how would the compiler know if you were trying to compare the iterators or the things they point to? The same applies to the ++it operation, which wants to modify the iterator, not the thing it points to.

Iterators could have a get() member to return the thing they refer to, so you'd do isupper(it.get()) but instead they support the dereference operator, which is less typing and is consistent with pointers and allows pointers to be used in any code that expects iterators.




回答3:


In order to distinguish operations on pointer-to-T and operations on the subject T it is necessary to have a dereferencing operator.

For example:

int* x = ...;

x++;

Do you mean you want to increment the pointer so it is pointing to the next int in memory? Or do you want to increment the int pointed to by x?

Without the deferenencing operator this would be ambiguous.

Iterators are simply a generalization of the pointer interface.

Contrast with references:

int& x = ...;

x++;

References have the alternative semantic, and do not require dereferencing. An operation on reference-to-T applies to the subject T. The downside is that you can't modify the reference itself.



来源:https://stackoverflow.com/questions/17295720/why-do-i-need-to-dereference-iterators

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!