您的位置:首页 > 其它

容器存放string指针

2009-08-02 20:03 148 查看
假如set中存放string指针,想当然可能会如此写:

std::set<std::string*> setPtr;
typedef std::set<std::string*>::iterator it_setptr;

setPtr.insert(new std::string("hong"));
setPtr.insert(new std::string("STL"));
setPtr.insert(new std::string("sportStl"));

for (it_setptr it=setPtr.begin(); it!=setPtr.end(); ++it)
{
std::cout << **it << std::endl;
}


但是在定义setPtr时,使用了默认的less<string*>仿函数,即插入元素的时候比较的是指针,并非指针内容,因此,应该自定义比较类型函数

struct StringPtrlLess:
public binary_function<const std::string*, const std::string*, bool>
{
bool operator()(const string* pstrLhs, const string* pstrRhs) const
{
return *pstrLhs < *pstrRhs;
}
};


定义应该改为:std::set<std::string*, StringPtrlLess> setPtr;这样做了之后,比较顺序就对了。

但是呢,std::copy(setPtr.begin(), setPtr.end(), std::ostream_iterator<string>(std::cout, "/n"));不能用,因为ostream_iterator<string>接受string类型,但是传给它的却是string*。可以试试解引用:

// 传入T*,返回const T&
struct Dereference
{
template<typename T>
const T& operator()(const T* ptr) const
{
return *ptr;
}
};


完整代码如下:

#include <iostream>

#pragma warning(disable:4786)
#include <set>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

struct StringPtrlLess: public binary_function<const std::string*, const std::string*, bool> { bool operator()(const string* pstrLhs, const string* pstrRhs) const { return *pstrLhs < *pstrRhs; } };

// 传入T*,返回const T& struct Dereference { template<typename T> const T& operator()(const T* ptr) const { return *ptr; } };

void testString()
{
std::set<std::string*, StringPtrlLess> setPtr;
typedef std::set<std::string*>::iterator it_setptr;

setPtr.insert(new std::string("hong"));
setPtr.insert(new std::string("STL"));
setPtr.insert(new std::string("sportStl"));
for (it_setptr it=setPtr.begin(); it!=setPtr.end(); ++it)
{
std::cout << **it << std::endl;
}

std::cout << "-------------------" << std::endl;
std::transform(setPtr.begin(), setPtr.end(),
std::ostream_iterator<string>(std::cout, "/n"),
Dereference());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: