0

I have declared a map like this

map<long long, list<SoundInfo *> > m_soundListMap;

and I also have this function

void addSoundInfo(long long deviceId, SoundInfo * info)

I am trying to add sound info associate with the device id as the key into the map. In this function, I assumed that a key and value pair has been added to the map. So I can retrieve the list of the sound info and add incoming sound info to the back of the list.

I want to catch an exception for the case that the map doesn't have the key then I can create the key and value pair and insert into the map.

How do I catch this exception in C++?

Thanks in advance...

Chris Schmich
  • 28,454
  • 5
  • 73
  • 94
user800799
  • 2,733
  • 7
  • 26
  • 34
  • 1
    Ehm.. what exactly are you doing in `addSoundInfo`? `std::map` doesn't throw any exceptions on insertion. – Xeo Jun 23 '11 at 05:49
  • What is going to happen if I try to get the list and the map doesn't have the key? is it just returning null or something? – user800799 Jun 23 '11 at 05:50

5 Answers5

4

std::map::operator[] returns a reference to the entry with the specified key; if no such entry exists a new entry is inserted (with the specified key and a default-constructed value) and a reference to that entry is returned. It can throw an exception when allocating memory fails (std::bad_alloc).

It sounds like you would probably find a good introductory C++ book useful.

Community
  • 1
  • 1
James McNellis
  • 338,529
  • 73
  • 897
  • 968
2

What is going to happen if I try to get the list and the map doesn't have the key?

Depends on how you try to get the item.

list<SoundInfo*>& info_list = m_soundListMap[55];

Will create an empty list, insert it into the map and return that when the key doesn't exist yet.

typedef map<long long, list<SoundInfo *> >::iterator iterator;
iterator iter = m_soundListMap.find(55);

Will return an iterator to the pair that holds both the key and the value, or will be map::end() if the key doesn't exist. iter->second will be your list<SoundInfo*>.

Xeo
  • 126,658
  • 49
  • 285
  • 389
1

Use map::find to check if map already has any value associated to a particular key.

Alok Save
  • 196,531
  • 48
  • 417
  • 525
1

You might look up the value using m_soundListMap.find(x). This returns an iterator. If the iterator is m_soundListMap.end() then the key wasn't found and you can insert if needed. No exceptions are thrown.

seand
  • 5,132
  • 1
  • 23
  • 37
1

I think you need this.

if(m_soundListMap.find(SomeLongVar) != m_soundListMap.end())
{  
  //Element found, take a decision if you want to update the value  
}  
else   
{  
  //Element not found, insert  
}
Chris
  • 3,055
  • 4
  • 25
  • 49
Manoj R
  • 3,157
  • 1
  • 20
  • 34
  • you are right. there is no exception, actually a new entry is created if the kety does not exist! the mystery of C++ :) – Mia Shani Nov 06 '20 at 02:09