• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: C++ function to check whether value exists in tuple

Resolved: C++ function to check whether value exists in tuple

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I’m a total beginner to C++, and I am trying to code a program that checks user input to make sure it is a valid option.
Here’s my code so far:
#include <iostream>
#include <string>
#include <tuple>

int UserInputCheck() {
    int x;
    cout << "Options: 1,2,3 or q. \n \n Choose an option:";
    cin >> x;
    tuple<int,int,int,string> valid_options{ 1, 2, 3, "q"};
    do {
        cout << "\nInvalid input. Please try again.";
        cin >> x;
    }
    while (x is not in valid_options); // This is psuedo-code, I'm looking for a function that does this
    
    cout << x << "\n";
    return 0;
{
So is there a C++ function that would check if x is in valid_options?
If not, how can I write one?

Answer:

static inline bool isValid(int input) {
        static const std::vector<int> valids = {1, 2, 3};

        return std::any_of(valids.begin(), valids.end(),
                                 [&input](const auto &s) { return input == s; });
    }
This function can do the coffee
EDIT: String version
static inline bool isValid(const std::string &input) {
static const std::vector<std::string> valids = {"1", "2", "3", "q"};

        return std::any_of(valids.begin(), valids.end(),
                                 [&input](const auto &s) { return input.find(s) != std::string::npos; });
}

If you have better answer, please add a comment about this, thank you!

c++
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: Reshape tensors of unknown shape with tf.function

26/03/2023

Resolved: Use Svelte Component as Slot

26/03/2023

Resolved: Vaadin 14.9 – Redirect on Session Destroy Event

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.