【问题标题】:check if value exists in all indexes of array检查值是否存在于数组的所有索引中
【发布时间】:2014-01-02 15:39:06
【问题描述】:

所以我有一个字符数组(大小为 5),每个索引包含一个字符,并且我正在获取要在数组中搜索的字符的用户输入。但我不确定如何检查数组的所有索引中是否存在char cInput

char cLetters[5] = {'b', 'b', 'b', 'b', 'b'};
char cInput;
cout << "Enter a character to search for: ";
cin >> cInput;

我不应该这样做吗?

if(cInput == cLetters[0] && cInput == cLetters[1] && cInput == cLetters[2] 
&& cInput == cLetters[3] && cInput == cLetters[4])
          return true;

特别是如果数组的大小是 200,我不会把这个条件写 200 次。

有什么想法吗?

【问题讨论】:

  • 您的问题被标记为 for-loop。怎么样?
  • 我整天都在放屁。我的道歉

标签: c++ arrays loops for-loop


【解决方案1】:

我正在寻找一种方法来使用 bools 并想出了这个:

auto is_true = std::bind(std::equal_to<bool>(), std::placeholders::_1, true);
return std::all_of(v.begin(), v.end(), is_true)

使用 const char 看起来像这样:

auto is_b = std::bind(std::equal_to<char>(), std::placeholders::_1, 'b');
return std::all_of(v.begin(), v.end(), is_b)

【讨论】:

    【解决方案2】:

    另一种可能性是使用 C++11 基于范围的 for 循环来稍微简化代码:

    for (auto ch : cLetters)
        if (ch != cInput)
            return false;
    return true;
    

    【讨论】:

      【解决方案3】:

      如果输入字符在任何一个索引中都不存在,则它不会出现在所有索引中。循环遍历数组来查看

      for (int i=0; i<5; ++i){
          if (cInput != cLetters[i])
              return 0;
      }
      return 1;
      

      【讨论】:

        【解决方案4】:

        &lt;algorithm&gt;std::all_of中使用C++11算法。

        示例代码:

        #include <algorithm>
        #include <iostream>
        
        int main() {
            char x[] = { 'b', 'b', 'b', 'b', 'b' };
            if(std::all_of(std::begin(x), std::end(x), [](char c) { return c == 'b'; })) {
                std::cout << "all are b!";
            }
        }
        

        【讨论】:

        • @Cheersandhth.-Alf,实际上令人难以置信的是,有多少有用的算法和实用程序被添加到 C++11 中,而这些算法和实用程序似乎并不为人所知。 std::to_stringstd::stoi 花了我很多时间。
        猜你喜欢
        • 1970-01-01
        • 2010-09-20
        • 1970-01-01
        • 2016-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        相关资源
        最近更新 更多