我有一些通用代码用于删除 vector 中的指针或 Map 的值。
有没有更好的方法(不使用 shared_ptrs 或任何 tr1 扩展)?
代码是否正确?
这是我的代码:
我有一个命名空间
#ifndef CONTAINERDELETE_H
#define CONTAINERDELETE_H
#include <functional>
#include <map>
#include <vector>
#include <algorithm>
namspace ContainerDelete{
template<class A, class B>
struct DeleteMap
{
bool operator()( pair<A,B> &x) const
{
delete x.second;
return true;
}
};
template<class T>
struct DeleteVector
{
bool operator()(T &x) const
{
delete x;
return true;
}
};
}
#endif
然后我会在一些代码中使用这个命名空间来删除 map 或 vector 。
测试 map 删除。
#include "ContainerDelete.h"
using namespace std;
// Test function.
void TestMapDeletion()
{
// Add 10 string to map.
map<int,B*> testMap;
for( int Idx = 0; Idx < 10; ++Idx )
{
testMap[Idx] = new B();
}
// Now delete the map in a single line.
for_each( testMap.begin(),
testMap.end(),
ContainerDelete::DeleteMap<int,B*>());
}
测试 vector 删除
// Test Function.
void TestVectorDeletion()
{
// Add 10 string to vector.
vector<B*> testVector;
for( int Index = 0; Index < 10; ++Index )
{
testVector.push_back( new B());
}
// Now delete the vector in a single line.
for_each( testVector.begin(),
testVector.end(),
ContainerDelete::DeleteVector<B*>());
}
谢谢,
迈克
最佳答案
如果减少通用性会更好:
struct DeleteVector
{
template<class T> //use the template here!
void operator()(T &x) const
{
delete x;
}
};
如果你这样做,那么你可以简单地这样写:
for_each(testVector.begin(),
testVector.end(),
ContainerDelete::DeleteVector());
使用 DeleteVector
时无需传递类型参数,因为它不再是类模板了!
同样,您可以实现 DeleteMap
仿函数。
您还应该将 DeleteVector
重命名为 DeleteT
,将 DeleteMap
重命名为 DeletePairSecond
,因为这两者都可以更普遍地使用。例如,DeleteT
甚至可以与 std::list
一起使用,甚至可以与数组一起使用。
关于用于删除 Map 和指针 vector 中的指针值的 C++ 通用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8231026/