1

我需要接受字符串键值对的 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;
    }
4

1 回答 1

4

你为什么要使用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.

于 2013-01-20T21:45:40.277 回答