将NSDictionary转换为std :: vector

编程入门 行业动态 更新时间:2024-10-11 07:31:21
本文介绍了将NSDictionary转换为std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想将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

本文发布于:2023-11-05 18:19:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   NSDictionary   vector   std

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!