将NSDictionary转换为std::vector

Convert NSDictionary to std::vector

本文关键字:vector std NSDictionary 转换      更新时间:2023-10-16

我想将一个从整数映射到浮点值的NSDictionary转换为c++ std::vector,其中原始NSDictionary中的键是vector的索引。

我有代码,我认为会工作,但它似乎创建一个向量大于字典中的键值对的数量。我猜这与我索引向量的方式有关。

任何帮助都非常感谢。

下面是我的代码:

 static std::vector<float> convert(NSDictionary* dictionary)
  {
      std::vector<float> result(16);
      NSArray* keys = [dictionary allKeys];
      for(id key in keys)
      {        
          id value = [dictionary objectForKey: key];
          float fValue = [value floatValue];
          int index = [key intValue];
          result.insert(result.begin() + index, fValue);
      }
      return result;
  }

用数字初始化vector对象将创建该数的起始表项。在本例中,vector从16个元素开始,每次插入都会添加元素,因此最终得到16 + N元素。

如果你想改变一个元素的值,只需给它赋值。不要使用insert:

result[index] = fValue;

但是,你真的应该使用map<int, float>:

std::map<int, float> result;
NSArray* keys = [dictionary allKeys];
for(id key in keys)
{        
    id value = [dictionary objectForKey: key];
    float fValue = [value floatValue];
    int index = [key intValue];
    result[index] = fValue;
}

既然您说您的键应该成为向量的索引,那么您可以对键进行排序。
未经测试的例子:

static std::vector<float> convert(NSDictionary* dictionary)
{
    std::vector<float> result;
    NSArray* keys = [dictionary allKeys];
    result.reserve([keys count]); // since you know the extent
    for (id key in [keys sortedArrayUsingSelector:@selector(compare:)])
    {        
        id value = [dictionary objectForKey:key];
        float fValue = [value floatValue];
        int index = [key intValue];
        result.push_back(fValue);
    }
    return result;
}
相关文章: