1

Suppose I have a vector in c++ as v = ('a','e','i','o','u'). I want to check whether a string is a vowel or not by simply checking if the character is in the vector v or not. I don't want any code for that as I myself know that , I am looking for a function or a keyword in c++ which is equivalent of below in python :

list = ['a', 'e', 'i', 'o', 'u']
if str in list:
    #do stuff

PS : Also let me know if nothing equivalent to this exists.

Sean
  • 60,939
  • 11
  • 97
  • 136
the_unknown_spirit
  • 2,518
  • 7
  • 34
  • 56

3 Answers3

1

Useful Link:

find Algorithm

Example is

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>

int main()
{
    int n1 = 3;
    int n2 = 5;

    std::vector<int> v{0, 1, 2, 3, 4};

    auto result1 = std::find(std::begin(v), std::end(v), n1);
    auto result2 = std::find(std::begin(v), std::end(v), n2);

    if (result1 != std::end(v)) {
        std::cout << "v contains: " << n1 << '\n';
    } else {
        std::cout << "v does not contain: " << n1 << '\n';
    }

    if (result2 != std::end(v)) {
        std::cout << "v contains: " << n2 << '\n';
    } else {
        std::cout << "v does not contain: " << n2 << '\n';
    }
}
Undefined Behaviour
  • 729
  • 2
  • 8
  • 27
1

I would suggest a best way of doing it as :-

std::unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u'};

for ( auto c : str )           // str is string you want to search
{
    if(vowels.find(c) != example.end()) {
        std::cout << "We have string with vowels\n";
    }
}
Elvis Dukaj
  • 7,142
  • 12
  • 43
  • 85
ravi
  • 10,994
  • 1
  • 18
  • 36
0

If you have a vector of items, see the question linked in the comments.

However, if you want to find a single character in a list of characters, it may be just as fast and simple to use an std::string and find or find_first_of:

std::string vowels = "aeiou";
char c = 'e';

bool isVowel = vowels.find_first_of(c) != std::string::npos;
Community
  • 1
  • 1
CompuChip
  • 9,143
  • 4
  • 24
  • 48