views:

162

answers:

1

Hi All,

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.

+3  A: 

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.

aem
@aem how to implement w/o STL Search Algorithm
Rachel
+1 from me - a superior solution. It's been too long since I last wrote C++. Using STL is the way to go.
duffymo