gpt4 book ai didi

c++ - Push_back 方法在此代码中的工作方式不同。为什么?

转载 作者:行者123 更新时间:2023-11-28 05:33:11 27 4
gpt4 key购买 nike

#include<bits/stdc++.h>
#define MAX 20
using namespace std;
int main()
{
//Creating a vector
vector <int> v;
std::vector<int>::iterator vIterator;
int i;

for(i=1;i<MAX;i++)
{
v.push_back(i);
}

cout<<"Numbers:"<<endl;
for(vIterator = v.end();vIterator>v.begin();vIterator--)
{

cout<<*vIterator<<endl;
}

int el_count = v.size();
cout<<"Size="<<el_count;

return 0;
}

这是代码的输出:

数字:01918171615141312111098个76个5个4个3个2个尺寸=19

为什么我一开始就得到这个“0”?为什么我的列表以 2 开头?

最佳答案

这是因为 vector 的索引范围是从v.begin()v.end()-1。您改为从 v.begin()+1v.end() 使用它。

循环中的语句应该是,

for(vIterator = v.end()-1; vIterator>=v.begin(); --vIterator)

访问 v.end() 将是未定义的行为,此处给出 0,显然您正在跳过第一个元素。

编辑:(感谢@Revolver_Ocelot)

从注释可以看出,在上一次迭代中,当vIterator=v.begin(),然后调用vIterator--时,指向的位置迭代器将导致未定义的行为。这是因为当 vIteratorv.begin() 以下递减时,vIterator>=v.begin() 可能为真也可能不为真。另一种可能是,

for(vIterator = v.end()-1; vIterator>v.begin(); --vIterator)
{
cout<<*vIterator<<endl;
}
cout<<*vIterator<<endl;

另一种方法是使用反向迭代器,

std::vector<int>::reverse_iterator vIterator;
for(vIterator = v.rbegin(); vIterator!=v.rend(); ++vIterator)

关于c++ - Push_back 方法在此代码中的工作方式不同。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935903/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com