【问题标题】:"in" list equivalent in c++ [duplicate]C ++中的“in”列表等效项[重复]
【发布时间】:2016-04-27 10:09:17
【问题描述】:

假设我在 C++ 中有一个向量 v = ('a','e','i','o','u')。我想通过简单地检查字符是否在向量 v 中来检查字符串是否为元音。我不想要任何代码,因为我自己知道,我正在寻找 C++ 中的函数或关键字,它相当于 python 中的以下内容:

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

PS:如果不存在与此等价的东西,也请告诉我。

【问题讨论】:

  • @SamiKuhmonen :对于这种特殊情况,std::setstd::vector 更适合
  • @vsz 对于这种特殊情况,我会使用std::string
  • @vsz 当然,它可能不是最好的数据结构,但问题谈到了向量。
  • std::find_first_of(str.begin(), str.end(), v.begin(), v.end()) != str.end()

标签: c++ algorithm vector


【解决方案1】:

有用的链接:

find Algorithm

例子是

#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';
    }
}

【讨论】:

    【解决方案2】:

    我建议最好的方法是:-

    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";
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果您有项目向量,请参阅comments 中链接的问题。

      但是,如果您想在字符列表中查找单个字符,使用std::stringfind or find_first_of 可能同样快速简单:

      std::string vowels = "aeiou";
      char c = 'e';
      
      bool isVowel = vowels.find_first_of(c) != std::string::npos;
      

      【讨论】:

        猜你喜欢
        • 2012-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-09
        • 2013-07-03
        • 1970-01-01
        • 2010-12-25
        • 1970-01-01
        相关资源
        最近更新 更多