Search code examples
c++objective-cobjective-c++

Convert NSDictionary to std::vector


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.

Here is the code I have:

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

Solution

  • 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;
    

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