string - find_if 在字符串数组上

标签 string foreach c++

我根据第一个字母从数组中查找所有字符串:

#include<iostream>
#include<algorithm>
#include<string>

int main(){

const std::string strArray[] =  {"an","blau","Bo","Boot","bos","da","Fee","fern","Fest","fort","je","jemand","mir","Mix",
                      "Mixer","Name","neu","od","Ort","so","Tor","Torf","Wasser"};

std::string value = "JNQ";
for_each(value.begin(), value.end(), [strArray](char c){
                  std::string const * iterator = find_if(strArray, strArray+23, [c](std::string str){
                                                    return toupper(str[0]) == c;
                                                 });
                  std::cout<<*iterator<<'\n';
          });

 return 0;
}

我得到这个输出:

je
Name
an

为什么显示'an'? 我在 Ubuntu 上使用 g++ 4.5。

最佳答案

你的代码的问题是你没有检查 iterator 对数组的 end,在此行之前:

std::cout<<*iterator<<'\n';

实际上应该是这样的:

if (iterator != (strArray+23))  //print only if iterator != end
     std::cout<<*iterator<<'\n';

看到这个。它现在可以工作了。

它不再打印"an"。 :-)

关于string - find_if 在字符串数组上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6506948/

相关文章:

c++ - 在 C++ 中将 int 转换为字符串的最简单方法

string - 如何找到字符串的不同子序列的数量?

javascript - 我的 forEach 在 javascript 字典中以相反的顺序循环,为什么?

php - laravel 使用数字键迭代 @foreach

C++ 协程 : call a coroutine function without co_await

C++ - 取消引用作为数组元素的指针?

matlab - 如何在Matlab中将空字符串连接到字符串的开头

java - 如何处理 Iterable.forEach 中的 IOException?

c++ - 如何访问 C++ 中其他文件中的静态链接变量?

string - 通过控制台运行脚本进行 Dart 字符串插值