简体   繁体   中英

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

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

Since you say your keys should become the indexes into the vector, you can sort your keys.
Untested example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM