我想将NSDictionary映射为浮点值的整数转换为C ++ std :: vector,其中原始NSDictionary的键为向量的索引.
I want to convert an NSDictionary mapping integers to floating point values into a C++ std::vector where the key from the original NSDictionary is the index into the vector.
我有一些我认为可以使用的代码,但似乎创建的矢量大于字典中键-值对的数量.我想这与我索引到向量的方式有关.
I have code that I thought would work, but it seems to create a vector larger than the number of key-value pairs in the dictionary. I'm guessing its something to do with the way I am indexing into the vector.
任何帮助都将不胜感激.
Any help greatly appreciated.
这是我的代码:
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; }推荐答案
使用数字初始化向量会创建很多条目.在这种情况下,向量将以16个元素开始,并且每个插入将添加元素,因此最终将以16 + N 个元素
Initialising a vector with a number creates that many entries to begin with. In this case, your vector will start with 16 elements, and each insert will add elements, so you'll end up with 16 + N elements.
如果要将元素更改为新值,只需为其分配.不要使用插入:
If you want to change an element to a new value simply assign to it. Don't use insert:
result[index] = fValue;但是,您实际上应该只使用map<int, float>:
However, you really should just use 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; }更多推荐
将NSDictionary转换为std :: vector
发布评论