A little story about hash_map and map

Source: Internet
Author: User

Article Source: http://blog.sina.com.cn/s/blog_4d3a41f40100eoei.html

 

Shengming]: This English document is derived from the "conversation" column created by Herb Sutter. The translation works of the "C ++ translation team" are for learning, exchange, and reference purposes, it shall not be used for any commercial purposes. The translation team shall not be liable for any violation of the above terms without the consent of herb Suter and Jim hyslop; it hereby declares that.

Source: http://www.gotw.ca
Copyright: Herb Suter and Jim hyslop
Translated by: csdnfriend (csdn)

Dialog #23: Generate a real hash object

When we land, I feel a little dizzy, but free. After returning to Earth, after more than a month of detention, we were released and all the tension was eliminated. Control of alien technologies will be monitored by a new organization and protected by militia from all major factions around the world.

We are waiting for the elevator. "I am so sleepy. It seems that acceleration will never stop ."

"We used to get used to it. We will get used to it again ." It took me a long time to sit back in my chair. "How long will this damn thing come down ?"

"I think they made a mistake in optimizing the elevator plan to get the minimum average wait time ." Jenny also sat down and said, "Unfortunately, we have encountered the worst Waiting Time ."

"But I'm glad to be back home ."

We waited for a while. When we were waiting in the crowd, I recalled the tests of the past two years. I knew Jenny was thinking about them. "We did make a mess," she said. I smiled tired. "Oh," she smiled. "That reminds you of a story, right? Okay, keep on. Please do not drop my appetite ."

I started to tell the story. I can continue to tell other people who will come in the new year. During our new life...

The words elevator and "hash" remind me of that day, when I was engaged in my first programming job, many years ago.

-------------------------

"Oh, what do you hear Bob doing ?" Wendy smiled while talking, and his eyes were shining happily. "The new boss is very important to standards. so Bob thinks that time is getting better. In the latest code, he wants to be a kingfa boy who follows the standard."

"But is that a good thing ?" I asked, confused.

Wendy left with a smile. "Wait to see his code..." floated. When she turned to the corner and walked into her work room, I shrugged and went back to work.

The next day, the first outbreak started, and the sound seemed to come from Bob's compartment. I walked over and saw what happened. I found Bob glared at the monitor and gave a grin. There was a cup of forgotten coffee beside him. It was cold and it was on his elbow.

"Why ?" I am naive to ask. I put myself in a dangerous environment, but I think the potential humorous value deserves my adventure.

Bob continued to scold a few words, and I thought I heard several words "standard" and "stupid" and "slow ". "Williams doesn't know how to write efficient code at all," he complained. Now he heard more clearly.These."

I looked at Bob's shoulder and saw an email from the QA department. I quickly glanced at it and complained in the letter about the speed at which Bob handed in the Code the day before yesterday. "What do they complain about ?" I asked.

"Speed," Bob said, scratching himself. "Speed.The nitpicking test department does not care that my code works properly at all, but says it is not fast enough to meet the specifications ."

"What is the specification ?"

Oh, average regular search time. I told them that the stupid STL containers could not meet the requirements ." In another window, I see some code:

typedef map<string, Employee> SearchIndex; // ... SearchIndex::iterator result = ind.find( empname );

"How manyMap?" I asked.

"Oh, a lot," Bob said vaguely.

Pop!The sound of closing the book suddenly shocked us. Once again, Guru quietly appeared behind us and gave a stern look. She pointed to the cold coffee, and then Bob's room's internal device and asked, "How do you eat like this ?" Bob blushed and took a breath, but Guru continued to ask before Bob responded: "This performance issue is not a problem with the standard inventory. It is the error of the programmer who used the wrong container. Why are you usingMap?"

"Because that is the damn standard container used for searching !" Bob complained angrily, "Why do you want me to pull my hair out, sweetheart? Let those who design STL stay in the ivory tower know that they don't understand what we need in the real world at all. This kind of container with internal tree structure always uses logarithm search, which is too slow for us ."

"Moreover, in this case, as long as the average search time remains stable, what is the relationship between an occasional long search time ?" Guru asked sweetly. Her demeanor tells me that she already knows the answer.

Bob understands this too: "No, we only care about the stress testing benchmarks that can present thousands of queries. You should know that the specifications are formulated by you !"

"That is," she said. "I wrote it. The solution you need is to add five characters to your code and use the most standard-compliant containers. They are also part of the standard ." "

"Hmm ?" Bob said with me.

In response, Guru changed Bob's source code line:

typedef hash_map<string, Employee> SearchIndex;

"Now you have a constant time to search, on average," she says. "In product code, when you want to use the associative container, you almost always need a hash-based container instead of a tree-based container. note:Hash_mapNot standard, but it is available on all platforms we use [1]. Of course, you must change the name of the included header file. At the same time, you should also check whether the default hash function is suitable for your data. If not, you can customize one by yourself. Test and timing. If feasible, you can adopt them boldly ."

She opened the big book before we could ask her questions. I think it is a proper time to leave, so Bob left before going back.

Later that day, at the side of the chiller, I learned Bob made a change based on the suggestions and it did solve the problem. the QA Department is very happy, our manager Peter. williams is also very happy, Bob is not very happy, but he is like this, I think things should come to an end.

This is not the case.

The second outbreak started two days later. I rushed into Bob's small room and saw almost the same scene: a cup of cold coffee, a hot-headed Bob and an email from the QA Department. This time, I quickly glanced at it, QA complained about the execution speed of another piece of code that Bob wrote and added to version control last night.

"Hi Bob," I said naively. "What's the problem now ?"

"Speed," Bob said, scratching himself."Speed.What do they want from me? My code works! I even usedHash_mapTo meet their demanding coding requirements, the QA idiots complained that the execution speed of my code could not meet the specifications ."

"What is this code ?"

"Oh," Bob waved, "I think they used my program for real-time interrupt processing or something else ." I took a look at his code:

typedef hash_map<Descriptor, Resource> Lookup; // ... Lookup::iterator result = res.find( d );

"How manyMap?" I asked again.

"Oh, too many ." Bob waved his hand carelessly.

Pop!She came again. Although I had long suspected that guru was nearby, I was surprised. So did Bob. "'One size fits everyone ', right ?" She calmly asked, "Why are you using it here?Hash_map?"

Bob's face turned red. I took a few steps back and felt Bob was so angry today that he was very discouraged. "Because," he said cautiously, "two days ago, you told me that we should always use non-standard hash-based containers !"

Guru shook his head sadly, "I didn't say that ." Bob almost blew up his lungs, but she continued: "Hey, you said, did you say he should always use it in the hash container ." She turned her head and asked me.

What I do not want most is to be involved in a dispute between them. "Er, right ?" I try to be vague.

We were in silence for a while, and then: "Have you ever heard of my child?" he asked anxiously, "was someone drowned by a three-foot-deep river ?"

I have a flash in my mind. "Ah," I nodded. "Some people waited for 15 minutes by an average elevator with only one minute. Generally, containers are based on trees, and their search speed is usually logarithm-level, whether it is the best or the worst case. If the appropriate hash function is selected, the average search time based on the hash container is shorter ." My answers were sharp and fast, winning guru's smile and opening the door. "But in the worst case, it may be worse than a tree-based container, isn't it ?"

"Yes, my child," she stressed. "Never confuse the average and the worst ." Guru re-opened her big book and turned to another page. "Here," she pointed to it and said, "Listen, first know musser." She looked at me through the book edge, looked at Bob again, and then concentrated her eyes on the book, reading, "the worst execution efficiency of 'hash table operations may be very poor, which may be linear n. In some cases, this will happen. However, containers based on the balanced binary tree are always maintained at O (logn ). '"[2]

"Yes," I said quickly, eager to show that my understanding is better than Bob. "the essence of the problem two days ago was the total time of thousands of searches, so it doesn't matter if you're a little slow, only the average condition is the most important. But for a service program... "I stopped.

"... You have a strict ceiling on the time that may be spent," she confirms. "The worst case is an important criterion for use ."

Bob just looked at this one of us and looked at it again, as if he was watching a tennis match. "Enough !" He shouted, and quickly stood up, so that the Chair almost turned over, and then angrily walked towards the coffee supply point.

"Indeed," guru continued, and turned around to prepare for it. "hash provides a constant average time advantage for insertion and search, tree-based search provides reliable performance. Select what you need, as I said, "She smiled for a while," 'in the finished code, when you need to associate the container, you almost always choose the hash table-based container... '"

-------------------------

A few months later, our wedding was held, a peaceful family event, and a new beginning. Some political struggles continue throughout the world, and countries continue to cheat each other for the status and advantages of alien technology, but this has nothing to do with me. It has nothing to do with us. We are insulated from them.

On a sunny afternoon several weeks after the wedding, Jenny sat in our new house and flipped through a book.

"What is that ?" I asked her to show me the name of the book and the Section she was reading. "Oh," I said, "Of course. Okay. Will we keep on going? Do you think about it ?"

"'From below the door, '" she agreed and smiled. "And I think the first volume of our book has ended ." 'The Happiness of their lives will be fulfilled in the following days. 'For details, see Volume 2.

I smiled, and we all laughed. This is true. This is the end of some of my life stories. It is how Jenny and I met and arrived at Jupiter. There were some wonderful discoveries and terrible adventures, and then returned safely. But our happy life is still going on, and you can believe that in our future life, we will often think of things in our young age, much earlier than we knew each other, I will tell Jenni many stories that are more interesting, touching, dangerous, and memorable when she is with Wendy, Bob, and guru.

[References]

[1] The typical hash-based container isHash_set,Hash_multiset,Hash_map, AndHash_multimap. You can find them in some popular C ++ compiler toolbox, including comeau (which uses sgi stl or dinkuware standard library Revision) metrowerks (which implements its own version, initially based on Modena, but has been thoroughly redesigned and rewritten) and Microsoft (which uses the dinkumware standard library ). They are also included in some popular third-party standard library implementation solutions. You may be able to use them using your existing compiler, including dinkumware, sgi stl and stlport (based on sgi stl ). Some implementations are slightly different. Please refer to the document of your library.

[2] D. musser et al.STL tutorial and Reference Guide, Second Edition(Addison-Wesley, 2001 ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.