You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:为何std::vector<int>调用find方法报‘无find成员’错误

解答:fatal error: no member named 'find' in 'std::vector<int>'

嘿,这个错误的核心原因其实挺直白的——std::vector 根本就没有自带的 find 成员函数!你想实现的查找功能,得用标准库算法里的全局 std::find,但你不仅用错了调用方式,还漏了必要的头文件。

我给你拆解一下问题,顺便把代码里的其他小坑也指出来:

1. 为什么找不到find?

STL里只有部分容器(比如std::set、std::map、std::string)自带find成员方法,因为它们的内部结构(比如红黑树、哈希表)适合高效的内置查找。而std::vector是连续存储的数组,没有内置的find,必须用<algorithm>头文件里的全局std::find算法。

2. 正确的调用方式

你写的people.find(people.begin(), people.end(), x)是成员函数的调用语法,但std::find是全局函数,正确写法是把容器的迭代器作为参数传进去:

std::find(people.begin(), people.end(), x)

而且一定要记得包含头文件:#include <algorithm>

3. 额外的坑:erase用法错误

就算你找到了元素,people.erase(x)也是错的——vector::erase要求传入的是迭代器,不是元素的值。你得把std::find返回的迭代器传给erase才行。

4. 代码里的另一个小问题

你初始化cost_of_person的时候,直接用cin >> cost_of_person[i]会导致越界,因为这个vector一开始是空的,没有分配空间。你可以先调用cost_of_person.resize(n)来分配足够的空间,或者用push_back来添加元素。

修正后的代码片段

#include<iostream>
#include<vector>
#include<algorithm> // 必须包含这个头文件!
#define REP(i,a,b) for(int i=a ; i<b ; i++)
using namespace std;

int main(){
    int n,m;
    cin >> n >> m;
    vector<vector<int>> friends;
    vector<int> people;
    vector<int> cost_of_person;
    cost_of_person.resize(n); // 先分配空间,避免越界
    REP(i,0,n){
        cin >> cost_of_person[i];
        people.push_back(i+1);
    }
    REP(i,0,m){
        int x,y;
        cin >> x >> y;
        // 正确查找并删除x
        auto it_x = find(people.begin(), people.end(), x);
        if(it_x != people.end()){
            people.erase(it_x);
        }
        // 正确查找并删除y
        auto it_y = find(people.begin(), people.end(), y);
        if(it_y != people.end()){
            people.erase(it_y);
        }
        bool inserted = false;
        REP(j,0,friends.size())
            // 你的后续逻辑代码
        ;
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者Abhishek Shinde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:27:50