range-based for in c++11(c++11中基于范围的for)
问题描述
在 C++ 11 中,如果我们有一个 set;我们可以说:
in c++ 11 if we have a set<int> S; we could say:
for (auto i: S)
cout << i << endl;
但是我们可以强制 i 成为迭代器吗,我的意思是写一段代码,相当于:
but can we force i to be a iterator, I mean write a code that is equivalent to:
for (auto i = S.begin(); i != S.end(); i++)
cout << (i != s.begin()) ? " " : "" << *i;
或者我们可以做一些我们可以理解i在集合(或向量)中的索引的事情吗?
or could we do something that we can understand the index of i in the set(or vector)?
另一个问题是我们怎么能说不对 S 中的所有元素都这样做,而是对它们的前半部分或除第一个之外的所有元素都这样做.
and another question is how could we say that don't do this for all elements in S but for first half of them or all of them except the first one.
或者当我们有一个 vector,想打印它的第一个n值怎么办?我知道我们可以创建一个新的向量,但是将一个向量复制到一个新的向量需要时间.
or when we have a vector<int> V, and want to print its first n values what should we do? I know we can create a new vector but it takes time to copy a vector to a new vector.
推荐答案
没有,很不幸.看看标准怎么说:
No, unluckily. See what the standard says:
基于范围的for语句for ( for-range-declaration : expression ) 语句相当于
The range-based for statement for ( for-range-declaration : expression ) statement is equivalent to
{
auto && __range = ( expression );
for ( auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin ) {
for-range-declaration = *__begin;
statement
}
}
其中 __range、__begin 和 __end 是仅为说明而定义的变量
where __range, __begin, and __end are variables defined for exposition only
换句话说,它已经从 begin 迭代到 end 并且已经解引用了迭代器,这是你永远看不到的.
In other words, it already iterates from begin to end and already dereferences the iterator, which you never get to see.
这篇关于c++11中基于范围的for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c++11中基于范围的for
基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
