2011-09-04 127 views
2

我想將NSDictionary映射整數轉換爲浮點值,轉換爲C++ std :: vector,其中原始NSDictionary的鍵是向量的索引。將NSDictionary轉換爲std :: 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; 
    } 
+3

爲什麼不使用'std :: map'。它是STD中的NSDictionary的對應物。也許你的鍵沒有排序,你不能在'std :: vector'上任意插入索引。你需要按順序執行:0,1,2,3 ... –

+1

因爲我正在寫一個插件,它給了我一個NSDictionary,並且希望將它傳遞給我使用的API,它需要一個std :: vector – ekj

回答

4

正在初始化向量與多家生成很多條目開始說起。在這種情況下,您的矢量將以16個元素開始,並且每個插入元素都將添加元素,因此您將以16 + N元素結束。

如果您想將元素更改爲新值,只需指定給它。不要使用插入:

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; 
} 
+0

第一個解決方案看起來可能是正確的。我不能使用std :: map,因爲我正在編寫一個插件,它給了我一個NSDictionary,並且希望將它傳遞給我正在使用的需要std :: vector的API。 由此,你如何獲得代碼塊的工作? – ekj

+0

@ekj:請問每個問題有一個問題。 –

+0

對不起,我只是想在我的堆棧溢出發帖。但我明白:--D。我是一個n00b這裏 – ekj

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; 
} 
+0

我認爲排序是不必要的,如果假設的關鍵是形成一個連續的集合(如果排序)。我現在的工作方式是初始化vector [鍵數],然後使用result [index] = fValue – ekj

+0

這可能是一個更有效的實現。但我認爲不需要地圖,是我的觀點。 – Richard

相關問題