在该行中temp.insert(it);
,我不断收到错误 No matching member function for call to insert,这意味着在我的代码中的某个时刻 temp 变成了向量以外的东西。有人有什么想法吗?
#include <iostream>
#include <vector>
using namespace std;
vector<int> removeDuplicates(vector<int> stuff)
{
vector<int> temp;
vector<int>::iterator it;
for(vector<int>::size_type i = 0; i < stuff.size(); i++){
//iterator to find stuff
it = find(stuff.begin(), stuff.end(), stuff);
//if it not in temp then add it
if (it == temp.end()) {
temp.insert(it); //No matching member function for call to insert
}
}
return temp;
}
int main(int argc, const char * argv[])
{
vector<int> values;
for(int i = 0; i < 5; i++){
values.push_back(i);
values.push_back(i+1);
}
removeDuplicates(values);
return 0;
}
好吧,答案对我帮助很大,但我决定重写代码,这就是我得到的,它似乎工作得很好
#include <iostream>
#include <vector>
using namespace std;
vector<int> removeDuplicates(vector<int> oldvector)
{
// newvector to hold non-duplicates
vector<int> newvector;
vector<int>::iterator it;
for(vector<int>::size_type i = 0; i < oldvector.size(); i ++){
//If it find a value then it returns the first element
it = find(newvector.begin(),newvector.end(), oldvector[i]);
if(it == newvector.end()){
newvector.push_back(oldvector[i]);
}
}
return newvector;
}
int main(int argc, const char * argv[])
{
vector<int> values;
vector<int> newvalues;
for(int i = 0; i < 5; i++){
values.push_back(i);
values.push_back(i+1);
}
newvalues = removeDuplicates(values);
//Print out the vector without duplicates
for(vector<int>::size_type i = 0; i < newvalues.size(); i ++){
cout << newvalues[i] << "\t";
}
return 0;
}
感谢您对原始问题的帮助,我学到了很多东西。