Thread: finding element in std::map

  1. #16
    Registered User
    Join Date
    Sep 2009
    Posts
    6
    Thank you all very much for help !

    To sum up: according to what has been said this version is correct:

    Code:
    #include <cstdio>
    #include <map>
    #include <algorithm>
    using namespace std;
    
    typedef map<int,int>::iterator iter;
    iter find(map<int,int> &s, int x) {
      iter it=s.lower_bound(x);
      return it==s.begin() ? s.end() : --it;
    }
    
    int main() {
      map<int,int> t;
      int x=0;
      for(int i=4;i<=8;i+=2) t[i]=++x;
      for(int i=2;i<=9;++i) {
        iter it=find(t,i);
        printf("find(%d):", i);
        if(it==t.end()) printf(" NONE\n");
        else printf("(%d,%d)\n",it->first,it->second);
      }
      return 0;
    }
    Why ? If map is empty, then lower_bound(x)==s.end()==s.begin() and result is s.end(), and if map is not empty and is the lower_bound(x) is s.begin(), then result is s.end(), and if the lower_bound(x)!=s.begin() then --lower_bound(x) is the answer (even if lower_bound(x) is s.end(), since performing --s.end() is correct in this case).
    Last edited by booleanx; 09-20-2009 at 11:54 AM.

  2. #17
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    What exactly are you asking with "Why?" The only tricky part would seem to be what to do in the case that the result is s.begin(), i.e., the first number is larger so there are no smaller numbers. Usually, s.end() is returned (since it's the most obvious not-a-real-answer object we have) in that case.

  3. #18
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> What exactly are you asking with "Why?"
    I think that was just setting up the answer that came after it. I don't think it was an actual question for anybody to answer.

  4. #19
    Registered User
    Join Date
    Sep 2009
    Posts
    6
    Yup, fortunately sb understands me, thx Daved : )

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 06-14-2009, 01:39 PM
  2. Replies: 4
    Last Post: 01-05-2008, 11:30 PM
  3. finding the element number in an array
    By tommy69 in forum C Programming
    Replies: 7
    Last Post: 04-02-2004, 04:26 AM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Finding numbers higher than the first element in array
    By sonict in forum C++ Programming
    Replies: 2
    Last Post: 12-02-2002, 10:00 AM