我想将NSDictionary映射整数转换为浮点值到C ++ std :: vector中,其中原始NSDictionary中的键是向量的索引。
我有我认为可行的代码,但它似乎创建了一个大于字典中键值对数的向量。我猜测它与我索引到矢量的方式有关。
非常感谢任何帮助。
这是我的代码:
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;
}
答案 0 :(得分:4)
使用数字初始化矢量会创建许多条目。在这种情况下,您的向量将以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;
}
答案 1 :(得分:0)
由于您说您的密钥应成为向量中的索引,因此您可以对密钥进行排序 未经测试的例子:
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;
}