如何使用迭代的最后一个元素

how can I work with the last element of iterations

本文关键字:最后一个 元素 迭代 何使用      更新时间:2023-10-16
for(int t(0); t < 10;++t) { cout<<t<<endl;}

我只是在C++中比大,想知道我怎样才能拿走我的"cout..."的最后一句话。在这种情况下,我的 laste 元素是 9

感谢帮助;)

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

这可能是您正在寻找的,但我不确定我是否正确理解了您的问题。当循环结束时,变量 c 应保存 t 的最后一个元素。

您可以从

for循环中提取int t

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

现在你有最后一个元素,#9。

ghagha,C++范围从 0 到 n-1,在您的示例中,您的范围为 0 到 <10,因此 0 到 9,因此您的最后一个元素是 9。 但正如我所说,你可以为最后一个元素做任何范围作为 n-1,前提是它遵循正常的约定(如果你这样编码,范围可以从 1 到 n

目前尚不清楚您想要什么,但无论如何您的循环都包含一个错误。而不是

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

应该是

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

也就是说,变量 t 必须递增。

一个简单的方法 -

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

很难正确的方法是(一个变量不应该有两个含义,即 1. 最后一个元素,2. 迭代器上下文) -

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