Searching for an int in a vector
Hi,
I am needing to take a vector and search it for a certain integer.
The goal:
To search a vector and confirm or deny if a certain integer is there.
The problem:
I am having problems searching the vector. Here is what I have been trying to use to search the "bag" of numbers.
Code:
search (bag.begin(), bag.end(), match1);
I have this part of my code below commented out so that the code will compile and run.
So could somebody show me how to use this command for a vector? Or is this even the right command to be using or should I go about it a different way?
Code:
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
class Bag
{
protected:
vector<int> bag;
public:
Bag() {};
bool isEmpty()
{
if (bag.empty())
{
cout << "Bag D is empty" << endl;
}
else
{
cout << "Fail" << endl;
}
return 0;
};
bool isElement(int x)
{
cout << "Enter a number to see if it's in the bag." << endl;
cin >> x;
vector<int>::iterator it;
//int match1 = x;
//it = search (bag.begin(), bag.end(), match1);
if (it!=bag.end())
{
cout << "match1 found at position " << int(it-bag.begin()) << endl;
}
else
{
cout << "match1 not found" << endl;
}
return 0;
};
void add(int x)
{
int y;
cout << "How many items would you like to put in the bag?" << endl;
cin >> y;
bag.resize(y);
cout << "Enter in " << y << " intergers." << endl;
for (int i=0; i<y; i++)
cin >> bag[i];
};
void list()
{
cout << "Here's what's in the bag:" << endl;
for (int i=0; i< bag.size(); i++)
cout << bag[i] << endl;
};
void remove()
{
};
};
int main()
{
int x;
Bag D;
D.isEmpty();
D.add(x);
D.list();
return 0;
}