C++ examples for STL:vector
Binary search to find an integer from a vector
#include <vector> #include <algorithm> #include <cstdlib> #include <ctime> #include <iostream> class BinarySearch { public:/* www. jav a 2 s . c o m*/ BinarySearch(int); // constructor initializes vector int binarySearch(int) const; // perform a binary search on vector void displayElements() const; // display vector elements private: int size; std::vector<int> data; void displaySubElements(int, int) const; // display range of values }; BinarySearch::BinarySearch(int vectorSize) { size = (vectorSize > 0 ? vectorSize : 10); // validate vectorSize srand(time(0)); // fill vector with random ints in range 10-99 for (int i = 0; i < size; ++i) data.push_back(10 + rand() % 90); // 10-99 std::sort(data.begin(), data.end()); } int BinarySearch::binarySearch(int searchElement) const { int low = 0; int high = size - 1; int middle = (low + high + 1) / 2; int location = -1; do { // print remaining elements of vector to be searched displaySubElements(low, high); // output spaces for alignment for (int i = 0; i < middle; ++i) std::cout << " "; std::cout << " * " << std::endl; // indicate current middle // if the element is found at the middle if (searchElement == data[middle]) location = middle; else if (searchElement < data[middle]) high = middle - 1; else low = middle + 1; middle = (low + high + 1) / 2; // recalculate the middle } while ((low <= high) && (location == -1)); return location; } void BinarySearch::displayElements() const { displaySubElements(0, size - 1); } void BinarySearch::displaySubElements(int low, int high) const { // output alignment spaces for (int i = 0; i < low; ++i) std::cout << " "; // output elements left in vector for (int i = low; i <= high; ++i) std::cout << data[i] << " "; std::cout << std::endl; } int main(int argc, const char* argv[]) { int searchInt; int position; // create vector and output it BinarySearch searchVector(15); searchVector.displayElements(); // get input from user std::cout << "\nPlease enter an integer value (-1 to quit): "; std::cin >> searchInt; std::cout << std::endl; // repeatedly input an integer: -1 terminates the program while (searchInt != -1) { // use binary search to try to find integer position = searchVector.binarySearch(searchInt); // return value of -1 indicates integer was not found if (position == -1) std::cout << "The integer " << searchInt << " was not found.\n"; else std::cout << "The integer " << searchInt << " was found in position " << position << ".\n"; // get input from user std::cout << "\n\nPlease enter an integer value (-1 to quit): "; std::cin >> searchInt; std::cout << std::endl; } return 0; }