You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用反向迭代器按顺序显示C++ vector?

使用反向迭代器显示vector元素时丢失最后一个元素的解决方法

问题描述

我有一个存储姓名的vector:

vector <string> names;
names.push_back("William");
names.push_back("Maria");
names.push_back("Petterson");
names.push_back("McCarthy");
names.push_back("Jose");
names.push_back("Pedro");
names.push_back("Hang");

需要使用反向迭代器(reverse_iterator)按原顺序显示这个vector。尝试了以下代码:

//Define a reverse iterator for the vector object
vector<string>::reverse_iterator itR = names.rend();

itR = itR - 1;

//Use the reverse iterator to display each element in the vector
cout << "	Names:\n";
while (itR != names.rbegin())
{
    cout << *itR << endl;
    itR--;
}

这段代码能按正确顺序显示部分姓名,但会截断最后一个元素“Hang”,求解决建议。


问题原因

你的循环条件itR != names.rbegin()导致了这个问题:当迭代器itR移动到names.rbegin()时,循环直接终止,而names.rbegin()恰好指向原vector的最后一个元素“Hang”,所以它没被输出。

解决方法

方法一:改用do-while循环

先执行输出操作,再判断循环条件,确保rbegin()指向的元素能被正常输出:

vector<string>::reverse_iterator itR = names.rend();
cout << "	Names:\n";
do {
    --itR;
    cout << *itR << endl;
} while (itR != names.rbegin());

方法二:补充最后一个元素的输出

在原循环结束后,单独输出names.rbegin()指向的元素,补上被漏掉的“Hang”:

vector<string>::reverse_iterator itR = names.rend();

itR = itR - 1;

cout << "	Names:\n";
while (itR != names.rbegin())
{
    cout << *itR << endl;
    itR--;
}
// 输出最后一个元素
cout << *names.rbegin() << endl;

推荐使用第一种方法,逻辑更连贯,不需要额外的收尾代码。


内容的提问来源于stack exchange,提问作者smirand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 02:30:52