473,803 Members | 3,022 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[STL] hash_map problem

Hello

I have a big problem with hash_map in stl.

I'm trying to create hash_map<const char *, char *> map
to keep key => val pairs as 4 byte C "strings".

Everything is ok when i do let's say
my_hash["abc"] = "efg";
my_hash["aa"] = "bb";
and then
for (it = my_hash.begin() ; it != my_hash.end(); ++it)
printf("%s %s\n", it->first, it->second);
it will print 2 entries
The problem starts when i try to push values to my_hash that
i read from a file. Here's a bit of code:
for (i = 0; i < N2; i++)
{
fread_unlocked( mro1, sizeof(char), 4, stdin);
fread_unlocked( mro2, sizeof(char), 4, stdin);

m_hash[mro1] = (char *) malloc(4*sizeof (char));
memcpy(m_hash[mro1], mro2, 4);
/*
or like this:

m_hash[mro1] = mro2

*/
}

mro1 and mro2 are 4*sizeof(char) bytes malloced vectors
for (it = my_hash.begin() ; it != my_hash.end(); ++it)
printf("%s %s\n", it->first, it->second);

will print only one, last entry i read from file. I figured out that it no
longer keeps "strings" as keys but pointers. Can someone tell me how to make
it work like my_hash["dljfj"] = "dlkfjkjdf" ; ?

gibffe
Jul 22 '05 #1
2 2066
"gibffe" <gi****@o2.pl > wrote in message
news:cl******** **@achot.icm.ed u.pl...
I'm trying to create hash_map<const char *, char *> map
to keep key => val pairs as 4 byte C "strings".
You are not taking advantage of std::string and struggling with C-style
strings.
Everything is ok when i do let's say
my_hash["abc"] = "efg";
my_hash["aa"] = "bb";
and then
for (it = my_hash.begin() ; it != my_hash.end(); ++it)
printf("%s %s\n", it->first, it->second);
it will print 2 entries
The problem starts when i try to push values to my_hash that
i read from a file. Here's a bit of code:
for (i = 0; i < N2; i++)
{
fread_unlocked( mro1, sizeof(char), 4, stdin);
fread_unlocked( mro2, sizeof(char), 4, stdin);

m_hash[mro1] = (char *) malloc(4*sizeof (char));
So you are using the same key (the value of mro1, which is a memory address)
for everything you read. You are overwriting the old value each time you do
this.

Since you don't free the previously malloced 4 bytes, you also leak memory
here.
memcpy(m_hash[mro1], mro2, 4);
/*
or like this:

m_hash[mro1] = mro2
If you did that, you would not leak memory, but still keep one key/value
pair (mro1/mro2) in the container.

*/
}

mro1 and mro2 are 4*sizeof(char) bytes malloced vectors
Since you don't malloc mro1 per key, your key is the same for everything you
read.


for (it = my_hash.begin() ; it != my_hash.end(); ++it)
printf("%s %s\n", it->first, it->second);

will print only one, last entry i read from file. I figured out that it no
longer keeps "strings" as keys but pointers. Can someone tell me how to make it work like my_hash["dljfj"] = "dlkfjkjdf" ; ?


Use std::string, not 'char *':

#include <string>
/* ... */
typedef hash_map<std::s tring, std::string> MyMap;

MyMap m_hash;
m_hash["dljfj"] = "dlkfjkjdf" ;

Ali

Jul 22 '05 #2

Use std::string, not 'char *':

#include <string>
/* ... */
typedef hash_map<std::s tring, std::string> MyMap;

MyMap m_hash;
m_hash["dljfj"] = "dlkfjkjdf" ;


Obviously this is the correct advice. But the thing to add is that some
implementations of hash_map do not have a hash function defined for
std::string. Therefore the OP might need to do add that themselves. Since
hash_map is non-standard the way to do that will vary, consult your
documentation. The other option would be to switch to std::map (and use
std::string of course).

john
Jul 22 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
19961
by: Daniel Heiserer | last post by:
Hello, I used a unique associative container such as: //--------------- map<vector<int>,double> X; //--------------- In general I fill X with millions of entries. Sorting plays no role for me. All I need is uniqueness
3
4177
by: Murali | last post by:
I have a requirement where I have to use two unsigned ints as a key in a STL hash map. A couple of ways to do this is 1. create a struct with two unsigned ints and use that as key (write my own HashFcn and EqualKey template args) or, 2. convert the two unsigned ints to char*s, concatenate them and use that as Key. For method 1, the difficulty I am having is in writing the HashFcn. HashFcn requires the following method
34
14489
by: pembed2003 | last post by:
Hi All, Does C++/STL have hashtable where I can do stuff like: Hashtable h<int>; h.store("one",1); h.store("two",2); and then later retrieve them like:
4
2816
by: Generic Usenet Account | last post by:
Consider two entities A and B such that there is a 1:n association between them. I mean that associated with each instance of A there are up to n instances of B. Currently in our software we are using an STL map in which instances of A are the key and each value is a set (STL set) of instances of B. There is some thought now that we should instead have a "transpose" of this data structure. By this I mean that the key should be an...
1
2975
by: anjangoswami06 | last post by:
Hi, I am interested to know how it is possible to update the data type with "insert" with stl hash_map. Suppose we have, hash_map<const char *, MyDataType, hash_compare<const char*, some_compare_func_obj>> x; //I want to insert a new instance of MyDataType if a new key is encountered but if it is a key //which already exists I want to update
1
9404
by: jayesah | last post by:
Hi All, I am developing my code with Apache stdcxx. I am bound to use STL of Apache only. Now today I need hash_map in code but as I learned, it is not available in Apache since it is not standard c++. Though it is available with GNU STL. The code module where I use hash_map will generate separate object file during compilation. This code module is also using STL string.
18
2956
by: Hunk | last post by:
Would like some advice on the fillowing I have a sorted list of items on which i require to search and retrieve the said item and also modify an item based on its identity. I think an Map stl container would be most suited. Am i correct in my assumptions Problem Reocrds are already stored with a unique identity in a binary format.The structure is roughly ----------------------
2
4284
by: Amit Bhatia | last post by:
Hi, I am trying to use hash maps from STL on gcc 3.3 as follows: #ifndef NODE_H #define NODE_H #include <ext/hash_map> #include "node_hasher.h" class Node; typedef hash_map<pair<int,int>, Node, Node_HasherLoc_Tree;
1
4476
by: mono12 | last post by:
Hi! I have written code using STL hash_map in c++ and am running into memory issues. I have two kinds of hash_maps: A <int,int> which stores ~5million key-value pairs, and needs to be accessed often to store in memory, its not updated during the program. B <int,hash_map<int,float>> which is also ~5m key-value pairs, but I can read this in parts from the disk. The inner hash_map has about 20 elements. In my program, I read in A and...
0
9564
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10546
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10292
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10068
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.