【问题标题】:STL std::find() C++STL std::find() C++
【发布时间】:2020-05-26 09:58:46
【问题描述】:

在下面的代码中,我将一个向量声明为{1,2,3,4,5}

使用STL std::find(),我试图在从arr.begin()arr.end()-1arr.begin()arr.begin()+4 的向量中找到5,这与从1 到@987654330 的范围相同@。

但在这里,迭代器返回指向5。为什么会这样,因为范围仅从 14

#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
using namespace std;

int main () {
    vector<int> arr {1,2,3,4,5};
    // TEST
    for_each(arr.begin(), arr.begin()+4, [](const int &x) { cerr << x << " "; }); cerr << endl;
    for_each(arr.begin(), arr.end()-1, [](const int &x) { cerr << x << " "; }); cerr << endl;

    auto it1 {std::find(arr.begin(), arr.begin()+4, 5)};
    auto it2 {std::find(arr.begin(), arr.end()-1, 5)};

    if (it1 != arr.end())
        cout << *it1 << " Found!" << endl;
    else
        cout << "NOT Found!" << endl;

    if (it2 != arr.end())
        cout << *it2 << " Found!" << endl;
    else
        cout << "NOT Found!" << endl;
    return 0;
}

输出:

1 2 3 4 
1 2 3 4 
5 Found!
5 Found!

【问题讨论】:

标签: c++ algorithm stl find containers


【解决方案1】:

std::find 仅返回未找到元素时作为第二个参数传递的迭代器。因此,它会在您的代码中将迭代器返回为 arr.begin()+4arr.end()-1

您不应将其与std::end 进行比较,例如

if (it1 != arr.begin()+4)
    cout << *it1 << " Found!" << endl;
else
    cout << "NOT Found!" << endl;

if (it2 != arr.end()-1)
    cout << *it2 << " Found!" << endl;
else
    cout << "NOT Found!" << endl;

【讨论】:

    【解决方案2】:

    这是因为如果std:find 没有找到请求的值(因为它出现在这里),它会返回你给它的结束迭代器(不是完整向量的结束迭代器),在这种情况下指向您正在寻找的元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2016-06-13
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多