每个人我都是C ++的新手并且刚刚离开C.在研究向量时我遇到了这个:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> g1;
vector <int> :: iterator i;
vector <int> :: reverse_iterator ir;
for (int i = 1; i <= 5; i++)
g1.push_back(i);
cout << "Output of begin and end\t:\t";
for (i = g1.begin(); i != g1.end(); ++i)
cout << *i << '\t';
cout << endl << endl;
cout << "Output of rbegin and rend\t:\t";
for (ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << '\t' << *ir;
return 0;
}
我的问题是为什么vector <int> :: iterator i;
vector <int> :: iterator i;
与int i
之间存在差异?
答案 0 :(得分:0)
为什么在这里
vector <int> :: iterator i;
创建vector <int> :: iterator i;
是为了遍历向量vector <int> g1;
(实际上它可以遍历任何vector<int>
,但在这种情况下,g1
为vector <int> :: iterator i
)
int i
之间有区别吗?和vector <int> :: iterator i;
?
main
的范围是main
函数。在for (int i = 1; i <= 5; i++)
g1.push_back(i);
内,创建了一个新范围:
i
在该范围内,int
是循环开始时定义的i
,但它在循环结束时消失,之后vector <int> :: iterator i
&#34;返回为& #34; int main()
{
vector <int> g1;
vector <int> :: iterator i; // i is the iterator
vector <int> :: reverse_iterator ir;
for (int i = 1; i <= 5; i++) // here i the int
g1.push_back(i); // also here
// from here the int i is dead, and i is back to being an iterator
cout << "Output of begin and end\t:\t";
for (i = g1.begin(); i != g1.end(); ++i)
cout << *i << '\t';
cout << endl << endl;
cout << "Output of rbegin and rend\t:\t";
for (ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << '\t' << *ir;
return 0;
}
{{1}}
答案 1 :(得分:0)
vanilla C和现代C ++之间存在差异,因为for()中声明的变量的范围和生命长度为for()循环体。它们被允许屏蔽具有相同名称的变量,在向上范围内声明。
这个例子几乎同样有效:
int main()
{
int i = 5, j;
for(int i = 5; i< 10; i++)
j = i;
std::cout << i << " " << j;
return 0;
}
// Output: 5 9
你问题中的代码不够优雅,并且包含不良做法。
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
using namespace std; // never do this in global scope
vector <int> g1(5); // allocating vector of 5 elements
// nothing is wrong with for() but you can do this too, for more complex cases.
generate(g1.begin(), g1.end(), [](){ static int i = 1; return i++; });
cout << "Output of begin and end\t:\t";
// so called range-based for
for (auto value : g1 )
cout << value << '\t';
cout << endl << endl;
cout << "Output of rbegin and rend\t:\t";
// type of ir is deduced. It's not same as C99's auto keyword
for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir)
cout << '\t' << *ir;
return 0;
}
在第一个for()
循环中,auto
关键字被推断为容器的元素类型。使用此关键字可以避免编写长嵌套类型名称,并且在模板代码中非常有用,还有typedecl