我有这个名字向量:
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");
我需要使用反向迭代器按顺序显示这个向量。
这是我的尝试:
//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 << "tNames:n";
while (itR != names.rbegin())
{
cout << *itR << endl;
itR--;
}
这将以正确的顺序显示所有名称,但它会切断"Hang"最后,有什么建议吗?
如果从范围的末尾到开始,应该先检查相等性,然后在循环体内递减。否则,要么不对最后一个元素进行迭代,要么迭代器从末尾开始递减,导致未定义的行为。您可以使用以下循环:
// print elements in original (= non-reversed) order
for (auto pos = names.rend(); pos != names.rbegin();)
{
--pos;
std::cout << *pos << std::endl;
}
while语句的条件
while (itR != names.rbegin())
禁止输出迭代器names.rbegin()
所指向的vector对象的元素。
itR = itR - 1;
迭代器itR
将等于names.rbegin()
,循环将被跳过。
也不清楚为什么你开始使用反向迭代器从迭代器names.rend() - 1
开始输出向量。
可以使用原始迭代器,或者如果您想以相反的顺序输出向量,则写入
//Use the reverse iterator to display each element in the vector
cout << "tNames:n";
for ( auto first = names.rbegin(), last = names.rend(); first != last; ++first )
{
cout << *first << endl;
}
否则至少更改代码,如
//Define a reverse iterator for the vector object
vector<string>::reverse_iterator itR = names.rend();
//Use the reverse iterator to display each element in the vector
cout << "tNames:n";
while (itR != names.rbegin())
{
cout << *--itR << endl;
}