Thread: Problem in Map Count MEthod

  1. #1
    Registered User
    Join Date
    Jun 2010

    Problem in Map Count MEthod

    Hi All

    I am trying to insert values in map as <char*,int> .

    The key is combination of 2 numbers which is generated in code.

    The problem is when I am trying to get count of that key, it is giving me 0.

    Below is sample code.

    #include <iostream>
    #include <map>
    using namespace std;
    int main ()
      std::map<char*,int> mp;
      char key[10] = {0x00};
      char mapKey[10] = {0x00};
      int count = mp.count(mapKey); 
      if ( count > 0 )
    	  cout<<"\n Key Found";
    	  cout <<"\n Not found\n";
      std::map<char*,int>::iterator it;
    // This is printing correct values of map
      for (it=mp.begin(); it!=mp.end(); ++it)
        std::cout << it->first << " => " << it->second << '\n';
    OutPut: Not Found
    00=> 4
    So map has value but count() is failing.
    Can any body help me here.


  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Your key is compared as a pointer, not a string. Unless it's the same pointer used for count as was inserted, the lookup will fail. You could add a comparison delegate to make things work, but it would be better in general to stick with the std::string class instead of using C-style strings:
    #include <iostream>
    #include <map>
    #include <string>
    using namespace std;
    int main()
    	map<string, int> mp;
    	string key = to_string(0) + to_string(1);
    	mp[key] = 4;
    	cout << "Key" << (mp.count("01") != 0 ? " found" : "not found") << '\n';
    	for (auto it : mp)
    		cout << it.first << " => " << it.second << '\n';
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Count problem
    By Kecupochren in forum C Programming
    Replies: 9
    Last Post: 12-23-2012, 07:14 PM
  2. problem count \n, \t and \b
    By jmvbxx in forum C Programming
    Replies: 2
    Last Post: 12-20-2009, 10:12 AM
  3. c count problem
    By peter121 in forum C Programming
    Replies: 2
    Last Post: 03-27-2005, 06:14 AM
  4. Replies: 2
    Last Post: 05-05-2002, 01:38 PM

Tags for this Thread