如何将值从NSMutableDictionary复制到Map
How do I copy values from NSMutableDictionary to a Map?
我需要接受字符串的键值对的NSMutableDictionary,我需要复制到stl映射。有简单的方法吗?我试过了,但是行不通。
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:@"10" forKey:@"6"];
[dictionary setObject:@"10" forKey:@"7"];
[dictionary setObject:@"10" forKey:@"8"];
NSEnumerator *enumerator = [dictionary keyEnumerator];
NSString *key;
while ((key = [enumerator nextObject])) {
std::string *keyString = new std::string([key UTF8String]);
std::string *valueString = new std::string([[dictionary objectForKey:key] UTF8String]);
map[*keyString] = *valueString;
}
你为什么要使用new
?只需将-UTF8String
的结果直接传递给地图,它就会为您将它们转换为std::string
s:
map[[key UTF8String]] = [[dictionary objectForKey:key] UTF8String];
你现有的new
代码不仅是无用的,但它也泄漏字符串。
你也应该抛弃NSEnumerator
。多年来,我们有更好的方法来列举字典。具体来说,您可以使用快速枚举,也可以使用基于块的枚举。快速枚举循环如下所示:
for (NSString *key in dictionary) {
map[[key UTF8String]] = [[dictionary objectForKey:key] UTF8String];
}
基于块的枚举看起来像这样:
// if map is a local variable it must be declared with __block
// like __block std::map<std::string,std::string> map;
// If it's static, global, or an instance or member variable, then it's fine as-is
[dictionary enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *value, BOOL *stop){
map[[key UTF8String]] = [value UTF8String];
}];
在这种情况下,我会推荐快速枚举循环,因为它不需要修改map
的声明。
相关文章:
- std::map 在 [] 上调用默认构造函数,在 insert() 上调用复制构造函数
- std::map insert && hyperload 导致复制
- C 将作为STD :: MAP复制到STD :: MAP的构造
- 为什么 std::map emplace 需要在 gcc 上有一个复制构造函数
- 如何将 std::map 值复制到非容器数组中
- C++ std::map 和 std::set 擦除复制值,从而使迭代器失效
- 关于从第二个存储值_ty2秒复制std :: Map Iterator的数据的问题
- 与 map 一起使用时复制构造函数常量错误
- 为什么map的元素不需要复制或移动构造函数,而vector需要?
- 如何在map中放置具有"deleted"复制ctor和赋值运算符的类?
- 将std::map复制/插入到boost::bimap中
- 使用 std::string 参数和不可移动/可复制参数构建 std::map
- <TiXmlDocument>在此卸载区域中使用的 map<shared_ptr、double> 不可按位复制
- std::map:插入密钥后,它是否可以复制和移动密钥
- 将包含类的类复制到 std::map
- C++ 将元素复制到 Map 中
- 如何将不可复制且不可移动的对象分配到std::map中
- 以vector、list或map为成员的类需要复制构造函数
- 在c++程序中将Map中的值复制到256x256数组
- 尝试将元素从Map复制到兼容优先级队列时出现无效堆错误