哪个更好? - 向地图添加条目的3种方法

时间:2013-02-05 03:01:51

标签: c++ map vector

我在sourceFile.cpp中有以下代码。首先调用functionA()并插入key1,key2和key3的条目。然后调用functionB()来使用3个键的向量。退出functionC()后,我想释放所有内存。将三个键的条目放入地图的三种方法中,这是正确/更好的吗?

Class ClassA { ... }

ClassA *key1 = new ClassA();
ClassA *key2 = new ClassA();
ClassA *key3 = new ClassA();

static map<ClassA*, vector<pair<char*, char*> > > stringMap;

// which way of adding an entry into StringMap is better? key1, key2 or key3
void functionA() {
    // insert entries into stringMap for key1 and key2
    vector<pair<char*, char*> > *v1 = new vector<pair<char*, char*> >();
    stringMap[key1] = *v1;
    stringMap[key2]; // map will insert one vector<pair<char*, char*> > object
    // is this vector object on heap or stack?

    vector<pair<char*, char*> > v3;
    stringMap[key3] = v3; // 
}

void functionB() {
    // get entries for key1, key2 and key3
    // use vector.push_back() to populate vectors
}

void functionC() {
    // so when program exits this function, all memory is released
    vector<pair<char*, char*> > *v1 = stringMap[key1];
    v1->clear(); // or loop and v1->erase() 
    stringMap.erase(key1);
    delete v1;

    vector<pair<char*, char*> > v2 = stringMap[key2];
    v2.clear();
    stringMap.erase(key2);
    // v2 was inserted by map, does it need to delete v2 ??? 

    // what about the vector for key3?
}

0 个答案:

没有答案