Reputation: 11
I want to print cardinality of a set using array or vector and membership of an element.
I am able to find cardinality but but can't find membership in same program.
Here is my code..
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int> v;
int ch;
int j;
for(int i=1; cin>>j; i++){
v.push_back(j);
}
cout << v.size();
cout << " enter element you want to find whether it is a memebr or not: ";
cin >> ch;
for(int i=0; i < v.size(); i++){
if(v[i] == ch){
cout << "element found";
break;
}
}
return 0;
}
Upvotes: 1
Views: 44
Reputation: 716
Try this:
#include <iostream>
using namespace std;
#include<vector>
#include<stdlib.h>
int main(){
vector<int> v;
int ch;
int j;
cout<<"Enter the size of set:"<<endl;
int n;
cin>>n;
for(int i=0; i<n ; i++){
cin>>j;
v.push_back(j);
}
cout << v.size()<<endl;
cout << " enter element you want to find whether it is a memebr or not: ";
cin >> ch;
for(int i=0; i < v.size(); i++){
if(v[i] == ch){
cout <<endl<< "element found";
exit(0);
}
}
cout<<endl<<"Element not found.";
return 0;
}
Upvotes: 0
Reputation: 1082
See what you did is taking an input during runtime inside a loop that too at condition validation place.Since to terminate this you gave a char. It throws an exception for that.So your program is not working as expected. Dont ever do that. Always ask for the size and then iterate the loop for that many number of times. Here is the code which is working :
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int> v;
int ch;
int j,temp;
int size;
cin>>size;
for(int i=1; i<=size; i++){
cin>>temp;
v.push_back(temp);
}
cout << " enter element you want to find whether it is a memebr or not: ";
cin >> ch;
for(int i=0; i < v.size(); i++){
if(v[i] == ch){
cout << "element found";
break;
}
}
cout<<v.size();
return 0;
}
Hope this would help you :)
Upvotes: 1