简体   繁体   English

我如何处理迭代的最后一个元素

[英]how can I work with the last element of iterations

for(int t(0); t < 10;++t) { cout<<t<<endl;}

I'm just biginer in C++, and want to know how can I take the last elemnt of my "cout...."; 我只是C ++中的佼佼者,想知道我该如何接受“ cout ....”的最后一个要素。 in this case my laste element is 9 在这种情况下,我的laste元素是9

thx for help ;) 寻求帮助;)

You can extract int t from the for loop : 您可以从for循环中提取int t

int t;  
for (t = 0; t < 10; ++t)  
{
    cout << t << endl;
}
int c = 0;
for(int t = 0; t<10; t++)
{
  c = t;
}
cout<<c;

This might be what you are looking for I am not sure I understand your question properly though.The variable c should hold the last element of t when the loop ends. 这可能就是您要查找的内容,但是我不确定我是否正确理解您的问题。循环结束时,变量c应该包含t的最后一个元素。

int t = 9;
cout << t << endl;

Now you have the last element, #9. 现在,您有了最后一个元素#9。

ghagha,C ++中的范围从0到n-1运行时,在例如,你必须<10因此0到9的范围为0,因此你的最后一个元素是9.但正如我说可以做任何范围最后一个元素为-1 ,前提是它遵循常规约定(如果这种方式编码,则范围可能在1到n之间

It is not clear what you want but in any case your loop contains a bug. 目前尚不清楚您想要什么,但是无论如何您的循环都包含一个错误。 Instead of 代替

for(int t(0); t < 10;  t) { cout<<t<<endl;}

should be 应该

for(int t(0); t < 10;  t++) { cout<<t<<endl;} 

that is variable t has to be incremented. 变量t必须增加。

One simple way - 一种简单的方法-

int t = 0;
for (; t < 10; ++t)
   cout << t << ;

Tough the correct way to do it will be (one variable should not have two meanings, ie 1. last element, 2. iterator context) - 正确的方法很严格(一个变量不应具有两种含义,即1.最后一个元素,2。迭代器上下文)-

int last_element;
for (int t = 0; t < 10; ++t;
{
    cout << t << ;
    last_element = t;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM