简体   繁体   English

如何捕获由std :: map引起的异常?

[英]How do I catch an exception caused from std::map?

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. 我正在尝试将与设备ID相关的声音信息添加为地图中的键。 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++? 如何在C ++中捕获此异常?

Thanks in advance... 提前致谢...

std::map::operator[] returns a reference to the entry with the specified key; std::map::operator[]返回具有指定键的条目的引用; 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 ). 当分配内存失败( std::bad_alloc )时,它可能引发异常。

It sounds like you would probably find a good introductory C++ book useful. 听起来您可能会发现一本很好的C ++入门书籍很有用。

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. 将一个迭代器返回到同时包含键和值的对,或者如果键不存在,将返回map::end() iter->second will be your list<SoundInfo*> . iter->second将是您的list<SoundInfo*>

使用map :: find检查map是否已经具有与特定键相关联的任何值。

You might look up the value using m_soundListMap.find(x). 您可以使用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. 如果迭代器是m_soundListMap.end(),则找不到密钥,并且可以根据需要插入。 No exceptions are thrown. 没有异常被抛出。

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  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM