2

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
  • 2
    I think you forgot the homework tag Commented Aug 29, 2009 at 2:50
  • I am pretty sure that it is not related tag. Thank you for input though. Commented Aug 29, 2009 at 3:03
  • Perhaps you could edit the question to mention that you don't want to use STL. If this is not homework, I'd also be very curious to know the reasons as well. Commented Aug 29, 2009 at 5:53

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.