2

if I have:

const string food[] = {"Burgers", "3", "Fries", "Milkshake"}
string word;
cin >> word;

How can I compare word with the correct food? or rather, if the user inputs "Fries", how can I compare that with the string array?

4
  • That's correct. If the user enters "Fries" I am trying to figure out how I can compare food[] with word Commented Sep 11, 2013 at 13:33
  • 2
    An array seems like the wrong structure. I would store the data in a std::map to take advantage of the look-up functionality. Commented Sep 11, 2013 at 13:35
  • 3
    @andre: A std::set seems more appropriate. Commented Sep 11, 2013 at 13:38
  • Curious if this question is going to bring all the boys to the yard... Commented Sep 11, 2013 at 14:31

2 Answers 2

7

With find:

#include <algorithm>
#include <iterator>

auto it = std::find(std::begin(food), std::end(food), word);

if (it != std::end(food))
{
    // found *it
}
else
{
    // not found
}
Sign up to request clarification or add additional context in comments.

Comments

3

With the find algorithm from <algorithm>:

auto found = std::find(std::begin(food), std::end(food), word);
if (found == std::end(food)) {
    // not found
} else {
    // found points to the array element
}

or with a loop:

for (const auto &item : food) {
    if (item == word) {
        // found it
    }
}

although, if you need to do this a lot, it might be better to store the items in a data structure designed for quick searches: std::set or std::unordered_set.

Comments

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.