开发者

find_if on a string array

开发者 https://www.devze.com 2023-03-15 18:16 出处:网络
I am finding all strings from an array depending on the first letter: #include<iostream> #include<algorithm>

I am finding all strings from an array depending on the first letter:

#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(), [st开发者_如何学PythonrArray](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;
}

I get this output:

je
Name
an

Why is 'an' displayed? I am using g++ 4.5 on Ubuntu.


The problem with your code is that you're NOT checking iterator against the end of the array, before this line:

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

which should actually be this:

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

See this. Its working now.

  • http://www.ideone.com/vyqlR

It doesn't print "an" anymore. :-)


iterator is not valid in 3rd case.

In this case iterator = strArray + 23 and point to element placed after array.

Look the fixed code.


Others have already told you the iterator is invalid, so I won't repeat that. However, here is a quick type-up of a solution that should work for you. As a side-note, don't use "magic numbers" to represent your array sizes. This is error-prone because if the size of the array changes (i.e. you add another element to it later) then it is easy to forget to update the 23 to 24. Consider this solution:

static unsigned const length = sizeof( strArray );
std::string const* end = strArray+length;
std::string const * iterator = find_if(strArray, end, [c](std::string str){
                                  return toupper(str[0]) == c;
                               });
if( iterator != end ) {
    std::cout<<*iterator<<'\n';
}

Note I couldn't compile this, as I do not have a C++0x compiler, so consider this pseudo-code if nothing else.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号