![](/img/trans.png)
[英]Is std::vector<int, std::allocator<char> > valid?
[英]fatal error: no member named 'find' in 'std::vector<int, std::allocator<int> >'
有人可以告訴我為什么會收到此錯誤
fatal error: no member named 'find' in 'std::vector<int, std::allocator<int> >' if(people.find(people.begin(),people.end(),x)!=people.end())
#include<iostream>
#include<vector>
#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;
REP(i,0,n){
cin >> cost_of_person[i];
people.push_back(i+1);
}
REP(i,0,m){
int x,y;
cin >> x >> y;
if(people.find(people.begin(),people.end(),x)!=people.end()) // error here
people.erase(x);
if(people.find(people.begin(),people.end(),y)!=people.end())
people.erase(y);
bool inserted = false;
REP(j,0,friends.size())
.
.
.
.
return 0;
}
std::vector
沒有find()
成員方法。 您需要改用std::find()
算法:
#include <algorithm>
if (std::find(people.begin(), people.end(), x) != people.end())
people.erase(x);
if (std::find(people.begin(), people.end(), y) != people.end())
people.erase(y);
但是,您將收到一個新錯誤,因為std::vector::erase()
不將元素值作為輸入,而是使用迭代器。 所以你也需要解決這個問題:
vector<int>::iterator iter = std::find(people.begin(), people.end(), x);
if (iter != people.end())
people.erase(iter);
iter = std::find(people.begin(), people.end(), y);
if (iter != people.end())
people.erase(iter);
我在您的代碼中看到的另一個問題是您沒有正確地將元素添加到您的cost_of_person
向量中,從而破壞了 memory。 你有兩個選擇來解決這個問題:
在進入循環之前調整cost_of_person
的大小:
vector<int> cost_of_person(n); REP(i,0,n){... }
或者
vector<int> cost_of_person; cost_of_person.resize(n); REP(i,0,n){... }
在循環內使用cost_of_person.push_back()
:
vector<int> cost_of_person; REP(i,0,n){ int cost; cin >> cost; cost_of_person.push_back(cost); people.push_back(i+1); }
問題在這里:
if(people.find(people.begin(),people.end(),x).=people.end())
您正在使用名為find
的 object people
的成員 function 。 然而,事實證明, people
被定義為:
vector<int> people;
它是一個向量。 並且該類型沒有名為find
的成員 function 。 因為你調用了一個不存在的成員 function,所以程序是非良構的。 因此,您會從編譯器收到一條診斷消息:
致命錯誤:“std::vector >”中沒有名為“find”的成員
要修復它,請不要調用不存在的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.