容器存放string指针
2009-08-02 20:03
148 查看
假如set中存放string指针,想当然可能会如此写:
但是在定义setPtr时,使用了默认的less<string*>仿函数,即插入元素的时候比较的是指针,并非指针内容,因此,应该自定义比较类型函数
定义应该改为:std::set<std::string*, StringPtrlLess> setPtr;这样做了之后,比较顺序就对了。
但是呢,std::copy(setPtr.begin(), setPtr.end(), std::ostream_iterator<string>(std::cout, "/n"));不能用,因为ostream_iterator<string>接受string类型,但是传给它的却是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());
}
相关文章推荐
- c++ map 容器不存放指针
- STL容器里存放对象还是指针(原)
- STL容器里存放对象还是指针?
- STL容器里存放对象还是指针
- STL容器中 存放指针与对象区别 遍历删除与释放操作
- STL容器里存放对象还是指针(转)
- STL容器里存放对象还是指针
- STL容器里存放对象还是指针
- STL容器里存放对象还是指针
- “标准容器中存放引用”与“指向引用的指针(pointer to reference)”
- 容器存放指针造成的内存泄露问题
- STL容器里存放对象还是指针
- STL容器里存放对象还是指针
- 【编程练习】将string容器保存在字符指针数组中
- 关联容器存放的是指针时,自定义比较函数模板
- 转:STL容器里存放对象还是指针
- STL容器里存放对象还是指针[仅把图片敲成文字]
- C++智能指针,指针容器原理及简单实现(auto_ptr,scoped_ptr,ptr_vector).
- 条款20:为指针的关联容器指定比较类型
- Effective STL 为包含指针的关联容器指定比较类型