添加项目后C find()函数不起作用

C++ find() function does not work after adding items

本文关键字:函数 不起作用 find 项目 添加      更新时间:2023-10-16

我想知道为什么" a.push_back(4)"会导致运行时错误。没有" A.push_back(4)"没有运行时错误。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void main()
{
    vector<int> a(5);
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);
    vector<int>::iterator begIt = begin(a);
    vector<int>::iterator endIt = end(a);
    a.push_back(4); // Once it is removed, this program will work well.
    auto begIt2 = begin(a);
    auto endIt2 = end(a);
    auto findIt = find(begIt, endIt, 4);
    if (findIt == endIt)
        cout << "not found";
    else
        cout << *findIt;
}

push_back(4)使您的迭代器无效。这就是为什么此代码产生错误的原因。