繁体   English   中英

向量 <int> :: iterator设置为begin时在向量的末尾开始

[英]vector<int>::iterator starts at end of vector when set with begin

因此,我正在尝试进行此小练习以解决c ++的问题,问题是,每当我对包含结果的向量使用迭代器时,它总是从向量的末尾开始然后崩溃。

cin >> mTestCases;
int i = 0;

while (mCycles.size() < mTestCases) {
    int x;
    cin >> x;
    mCycles.push_back(x);
}


//Cycling through said values
vector<int>::iterator iterator;

i = 0;
for(iterator = mCycles.begin(); iterator != mCycles.end(); ++iterator) {
    int j = 0;
    int height = 1;
    while (j < *iterator) {
        if (j%2)
            height++;
        else
            height*=2;
        j++;
    }
    mResults.push_back(height);
}

vector<int>::iterator resultsIterator;


for (resultsIterator = mResults.begin(); resultsIterator != mResults.end(); ++resultsIterator) {
    cout<<mResults.at(*resultsIterator)<<endl;
}

此处讨论的turd代码是此文本上方的for循环。 由于某种原因,如果我输入3个测试用例,我会将3个结果放入向量中,因此resultsIterator从最后一个值开始,将其打印出来,然后由于当机试图访问向量之外而崩溃。 。

我认为您想要的是:

cout << *resultsIterator << endl;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM