Question

/** * Performs an index-based linear search on an indexable object for a given value, by...

/**
* Performs an index-based linear search on an indexable object for a given value, by using
* operator[].
*
* @param haystack the object to search. Must support operator[] and size(), e.g. a std::vector.
* @param needle the value for which to search
* @return the first index found via linear search at which the object contains the value, or -1 if
* the object does not contain the value.
*/
template <typename IndexedContainer, typename Value>
int LinearSearch(const IndexedContainer &haystack, const Value &needle)

0 0
Add a comment Improve this question Transcribed image text
Answer #1
#include <iostream>
#include <vector>

using namespace std;

/**
* Performs an index-based linear search on an indexable object for a given value, by using
* operator[].
*
* @param haystack the object to search. Must support operator[] and size(), e.g. a std::vector.
* @param needle the value for which to search
* @return the first index found via linear search at which the object contains the value, or -1 if
* the object does not contain the value.
*/
template <typename IndexedContainer, typename Value>
int LinearSearch(const IndexedContainer &haystack, const Value &needle) {
    for(int i = 0; i < haystack.size(); ++i) {
        if(haystack[i] == needle) {
            return i;
        }
    }
    return -1;
}

int main() {
    vector<int> vec;
    vec.push_back(4);
    vec.push_back(2);
    vec.push_back(7);
    vec.push_back(9);
    cout << LinearSearch(vec, 2) << endl;   // prints 1
    cout << LinearSearch(vec, 5) << endl;   // prints -1
    return 0;
}
Add a comment
Know the answer?
Add Answer to:
/** * Performs an index-based linear search on an indexable object for a given value, by...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please show me how to overload the operators << and >> #ifndef LINK_LIST #define LINK_LIST #include...

    Please show me how to overload the operators << and >> #ifndef LINK_LIST #define LINK_LIST #include <iostream> using namespace std; template <typename T> struct Int_Node {    T value;    Int_Node<T> *pre, *next; }; template <typename T> class Link_List {    template <typename U>    friend ostream &operator<<(ostream &, const Link_List<U> &);// print all integers in the list    template <typename U>    friend istream &operator>>(istream &, Link_List<U> &);// input a value at the back of the list, like insert_node(val);...

  • / Animal.hpp #ifndef ANIMAL_H_ #define ANIMAL_H_ #include <string> class Animal { public: Animal(); Animal(std::string, bool domestic=false,...

    / Animal.hpp #ifndef ANIMAL_H_ #define ANIMAL_H_ #include <string> class Animal { public: Animal(); Animal(std::string, bool domestic=false, bool predator=false); std::string getName() const; bool isDomestic() const; bool isPredator() const; void setName(std::string); void setDomestic(); void setPredator(); protected: // protected so that derived class can directly access them std::string name_; bool domestic_; bool predator_; }; #endif /* ANIMAL_H_ */ //end of Animal.h // /////////////////////////////////////////////////////////////////Animal.cpp #include "Animal.h" Animal::Animal(): name_(""),domestic_(false), predator_(false){ } Animal::Animal(std::string name, bool domestic, bool predator): name_(name),domestic_(domestic), predator_(predator) { } std::string Animal::getName() const{ return...

  • In this assignment, you will implement a sort method on singly-linked and doubly-linked lists. Implement the...

    In this assignment, you will implement a sort method on singly-linked and doubly-linked lists. Implement the following sort member function on a singly-linked list: void sort(bool(*comp)(const T &, const T &) = defaultCompare); Implement the following sort member function on a doubly-linked list: void sort(bool(*comp)(const T &, const T &) = defaultCompare); The sort(…) methods take as a parameter a comparator function, having a default assignment of defaultCompare, a static function defined as follows: template <typename T> static bool defaultCompare(const...

  • You will be reading in 3 files in the program. One will contain a list of...

    You will be reading in 3 files in the program. One will contain a list of 1000 words in unsorted order. The second file will contain 1000 words in sorted order. The final file will contain 20 words to be searched for. The main program has been written for you. You will be implementing three functions: bool readWords(string array[], int size, string fileName); int linearSearch(string wordToFind, const string words[], int size); int binarySearch(string wordToFind, const string words[], int size); The...

  • The following program contains the definition of a class called List, a class called Date and...

    The following program contains the definition of a class called List, a class called Date and a main program. Create a template out of the List class so that it can contain not just integers which is how it is now, but any data type, including user defined data types, such as objects of Date class. The main program is given so that you will know what to test your template with. It first creates a List of integers and...

  • 7. Code a linear search. Given are two input iterators and a key to be located. Use only operators that are permit- ted on input iterators. For comparing keys, use only operatorReturn the iterator po...

    7. Code a linear search. Given are two input iterators and a key to be located. Use only operators that are permit- ted on input iterators. For comparing keys, use only operatorReturn the iterator pointing at the key found or the end iterator. If the key occurs more than once, return the first one found. [2v] template <typename itor, typename item> itor linear search (itor begin, itor end, const items key) l 7. Code a linear search. Given are two...

  • (C++) (VISUAL STUDIO) Circular Queue is a linear data structure in which the operations are performed...

    (C++) (VISUAL STUDIO) Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. In a normal Queue, we can insert elements until queue becomes full. But once queue becomes full, we cannot insert the next element even if there is a space in front of queue. Efficiently implement a queue class using a circular...

  • A library maintains a collection of books. Books can be added to and deleted from and...

    A library maintains a collection of books. Books can be added to and deleted from and checked out and checked in to this collection. Title and author name identify a book. Each book object maintains a count of the number of copies available and the number of copies checked out. The number of copies must always be greater than or equal to zero. If the number of copies for a book goes to zero, it must be deleted from the...

  • vector.h: #ifndef VECTOR_H #define VECTOR_H #include <algorithm> #include <iostream> #include <cassert> template <typename T> class Vector...

    vector.h: #ifndef VECTOR_H #define VECTOR_H #include <algorithm> #include <iostream> #include <cassert> template <typename T> class Vector {     public:         Vector( int initsize = 0 )         : theSize( initsize ),          theCapacity( initsize + SPARE_CAPACITY )         { objects = new T[ theCapacity ]; }         Vector( const Vector & rhs )         : theSize( rhs.theSize),          theCapacity( rhs.theCapacity ), objects( 0 )         {             objects = new T[ theCapacity ];             for( int k = 0; k < theSize; ++k)                 objects[ k ] = rhs.objects[ k...

  • C programming (you don't need to write program) Problem 1 [Linear Search with Early Stop] Below...

    C programming (you don't need to write program) Problem 1 [Linear Search with Early Stop] Below you will find a linear search function with early stop. A linear search is just a naive search - you go through each of the elements of a list one by one. Early stop works only on sorted list. Early stop means, instead of going through whole list, we will stop when your number to search can no longer be possibly found in the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT