Searching in a vectors
Sample Code:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
void createVect(vector<int> &vect)
{
srand(time(NULL));
for(int i = 0; i < 100; i++)
{
vect.push_back(rand()%100 + 1);
}
}
int searchVect(vector<int> vect, int searchValue)
{
int found = -1;
//Manual Search
for(int i=0;i<vect.size();i++)
{
if (vect[i] == searchValue)
return i;
}
//Using Vector function
found = vect.at(searchValue);
return found;
}
int main()
{
vector<int> int_vect;
int num, found;
createVect(int_vect);
cout << "Enter the number to be searched"<< endl;
cin >> num;
found = searchVect(int_vect, num);
if (found == -1)
cout << num << " is not found" << endl;
else
cout << num << " is found at " << found << "Location"<< endl;
return 0;
}
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
void createVect(vector<int> &vect)
{
srand(time(NULL));
for(int i = 0; i < 100; i++)
{
vect.push_back(rand()%100 + 1);
}
}
int searchVect(vector<int> vect, int searchValue)
{
int found = -1;
//Manual Search
for(int i=0;i<vect.size();i++)
{
if (vect[i] == searchValue)
return i;
}
//Using Vector function
found = vect.at(searchValue);
return found;
}
int main()
{
vector<int> int_vect;
int num, found;
createVect(int_vect);
cout << "Enter the number to be searched"<< endl;
cin >> num;
found = searchVect(int_vect, num);
if (found == -1)
cout << num << " is not found" << endl;
else
cout << num << " is found at " << found << "Location"<< endl;
return 0;
}
Comments
Post a Comment