我根据第一个字母从数组中查找所有字符串:
#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/