为什么需要取消引用迭代器? [英] Why do I need to dereference iterators?

查看:73
本文介绍了为什么需要取消引用迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我需要取消对迭代器的引用?例如在以下程序中

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

为什么必须使用isupper(*it);而不是仅仅使用isupper(it);?

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

推荐答案

迭代器是通用指针.它指向.如果您有一个需要某些东西(在这种情况下为char或int)而不是指针"本身的函数,则需要取消引用迭代器.

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.

例如,标准的advance函数将迭代器作为其参数.因此,您可以在不取消引用迭代器的情况下传递迭代器,如

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);

但是,如果您有一个指向int的迭代器,并且想要将该整数增加4,则需要

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

(*it) += 4;

我建议您阅读关于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);

这篇关于为什么需要取消引用迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆