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
  • 29,128
  • 5
  • 77
  • 94
user800799
  • 2,883
  • 7
  • 31
  • 36
  • 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
  • 348,265
  • 75
  • 913
  • 977
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
  • 129,499
  • 52
  • 291
  • 397
1

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

Alok Save
  • 202,538
  • 53
  • 430
  • 533
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,168
  • 1
  • 24
  • 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,245
  • 4
  • 29
  • 53
Manoj R
  • 3,197
  • 1
  • 21
  • 36
  • 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