将NSDictionary转换为std::vector
Convert NSDictionary to std::vector
我想将一个从整数映射到浮点值的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;
}
相关文章:
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 连接和压缩标准::vector<std::字符串的最佳方法>
- C++从 std::vector<std::function<中删除 std::function>>
- 如何在构造函数初始值设定项列表中使用 n 个元素初始化 std::vector<std::time_t>
- 如何使用 CUDA 将 std::vector<std::string> 复制到 GPU 设备
- 编译错误 std::vector<std::shared_ptr<T>>迭代器和擦除方法
- 将 std::vector<std::unique_ptr<T>> 移动到 std::vector<std::shared_ptr<T>>
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- 使用 std::vector<std::future<int>> 和 std::async 启动几个线程时中止
- 为什么转置这个 std::vector<std::vector<std::string> > 这么慢?
- 是否有可能在没有复制的情况下传递 std::vector<int> 作为参数来获得 std::vector<std::array<int, 3>>?
- 在 boost::<double>asio::buffer 中使用像 std::vector<std::complex> 这样的参数
- 如何从 std::initializer_list<char const* 构建 std::vector<std::string>>
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?
- 在 std::vector<std::vector 中重新存储内部向量<TYPE>>
- 将 std::vector<std::string> 转换为 const char* const*
- 不能将结构push_back() 转换为 std::vector<std::shared_ptr<theStruct>> theVector
- SWIG:传递一个 std::vector< std::vector <double> >指向 python 的指针
- 将 std::vector<std::p air<const K, V>*> 转换为 std::vector<std::p air<const K, V>&g