C++ 在一组整数值中,添加一些整数值,检查该值是否存在,如果不存在,则插入是否发生 #包括 #包括 #包括 使用名称空间std; set setofnumbers(set&myset){//用于我的随机输入的函数 int-s; cout>s; 而(s!=-1){ myset.insert(s); cin>>s; } }

C++ 在一组整数值中,添加一些整数值,检查该值是否存在,如果不存在,则插入是否发生 #包括 #包括 #包括 使用名称空间std; set setofnumbers(set&myset){//用于我的随机输入的函数 int-s; cout>s; 而(s!=-1){ myset.insert(s); cin>>s; } },c++,C++,我在这些部分的问题是,我必须使用.find来检查数字,我以前用作函数的setofnumbers中有错误,但我需要在这里使用该setofnumbers #include<iostream> #include<set> #include<cstdlib> using namespace std; set<int> setofnumbers(set<int>& myset) { //function for my ran

我在这些部分的问题是,我必须使用.find来检查数字,我以前用作函数的setofnumbers中有错误,但我需要在这里使用该setofnumbers

#include<iostream>    
#include<set>
#include<cstdlib>
using namespace std;

set<int> setofnumbers(set<int>& myset) {   //function for my random input
int s;
cout << "Enter the set of numbers(-1 to exit): ";
cin >> s;
while(s != -1){
    myset.insert(s);
    cin >> s;
    }
}
void checkandinsert(int num){//插入函数检查整数是否存在
set::iterator it=setofnumbers.find(num);
if(it!=setofnumbers.end())

你可以简单地使用它。你需要捕获
insert
的返回,看看它是否真的插入了。是的,我在setofnumbers函数中的插入是随机的,但我在第二个函数中的问题是:checkandinsert,我必须比较和检查…任何类型的帮助都非常感谢checkandinsert从不尝试插入,因此在此之前,它不会做它所说的事情。而且它完全没有意义,因为std::set已经有了这个函数。请阅读第一条注释中链接的文档。
void checkandinsert(int num){  //insert function to check integer present or not

set<int>::iterator it = setofnumbers.find(num); 
if( it != setofnumbers.end())
    cout << "NUmber " << num <<" inserted sucessfully";
else cout << "Number " << num << " was already present in the set";
}

int main(){    //main function
int x;
checkandinsert(2);
checkandinsert(4);
checkandinsert(6);
checkandinsert(76);
int size = setofnumbers(x)
cout << "Size of the set: " << size << endl;
for(set<int>::iterator i=size.begin(); i!=size.end(); i++)
    cout << *i << " ";
cout << endl;
return 0;
}

"my output suppose to look like"
Enter the set of numbers(-1 to exit): 1 2 3 4 5 6 11 -1
2 was already present in the set.
4 was already present in the set.
6 was already present in the set.
76 inserted successfully.
Size of the set: 8
1 2 3 4 5 6 11 76