如何使用迭代的最后一个元素
how can I work with the last element of iterations
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;
}
相关文章:
- lower_bound()返回最后一个元素
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 仅显示链表的最后一个元素
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- std::矢量保存 只推送最后一个元素
- 反转后不返回最后一个元素
- 如何在新数组较小时创建新数组并将旧数组的最后一个元素复制到新数组中?
- 在 QListView 中显示最后一个元素
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 遍历列表包含排除最后一个元素的内容
- 如何打印第一个和最后一个元素的和,然后打印第二个和倒数第二个元素的总和,依此类推
- C++链表最后一个元素的迭代器?
- 这种获取模板参数包中最后一个元素的方法是否有隐藏的开销?
- 使用 STL 交换堆栈 C++ 中的第一个和最后一个元素
- 数组:如何在指定索引之前显示数组的第一个和最后一个元素以及数组元素的差异?
- 你能pop_back一个向量,并且仍然使用迭代器到最后一个元素吗?
- 如何使用第一个、中间和最后一个元素的中位数正确分区?