[英]Having trouble in C++ Creating vector of pointers or map of Pointer values
[英]C++ Generic code for deleting pointer value in Map and vector of pointers
我有一些通用代码用于删除向量中的指针或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
然后我会在一些代码中使用此命名空间来删除地图或矢量。
测试图删除。
#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*>());
}
测试矢量删除
// 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
,甚至可以用于数组。
代码还可以。 我无法想象有任何其他方法可以删除指针。 您所能做的就是减少显式类型规范,如上层问题。 我知道一个更丑陋的方法:函数推导出模板参数的类型。 所以你可以用第一个参数 - vector,second - ptr编写模板函数,然后使用std :: bind of vector参数使这个函数接受一个参数--ptr。 但是仿函数更好,更灵活。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.