Rachel
Rachel

Reputation: 103447

In C++ how to return index of an array if user entered matches entered array?

I wanted to know how can we get the index of the array if the user entered array matches the input array ?

For example:

Input Array = [1,2,3,4] and user entered Array = [2,3] than I should get output as index where both array matches is 1.

Guidance would be highly appreciated.

Upvotes: 2

Views: 750

Answers (1)

aem
aem

Reputation: 3916

Use the STL search algorithm, which does just what you want: "The search() algorithm looks for the elements [start2,end2) in the range [start1,end1)." You'll need to supply it pointers to the start and end of the two arrays; you get the end pointer for an array by adding its length to its start pointer.

Better, use the STL vector to store your data instead of an array, and then you can just call vec.begin() and vec.end() to get the iterators you want.

Edit: To do it without std::search, follow the example on the link I provided, which shows how search can be done. If you're doing it C-style, you'll use pointers (like int*) rather than ForwardIterator. The only tricky bit there is the part outside the loop, where they figure out what limit should be set to - this will turn into some pointer arithmetic.

Upvotes: 4

Related Questions