读书人

vector包装类,该怎么解决

发布时间: 2013-07-04 11:45:55 作者: rapoo

vector包装类
说下背景,一个容器,一个读取线程,一个写入线程,由于具体逻辑比较复杂,在读线程中很多地方都访问到了容器,每一处都添加同步,太麻烦了,而且代码又不是一个人写,难保有人不加同步直接读写容器。所以打算自己包装下STL容器,支持多个线程同时读写。
但是在重写begin方法的时候出现了问题。贴出关键代码

类型定义



没有研究STL源码之前,自认为很了解迭代器与指针之间的区别,但是当我看了STL源码之后,发觉自己越来越分不清迭代器与指针之间的区别了。vector包装类,该怎么解决

在线等各位高手解答困惑。。。。。
[解决办法]
加个 typename 就行了:

typedef typename std::vector<T>::iterator iterator;


[解决办法]
没有人保证std::vector::iterator一定是一个指针。
所以,你应该:
    typedef typename std::vector<T>::size_type size_type; 


typedef typename std::vector<T>::value_type value_type;
typedef ypename std::vector<T>::reference reference;
typedef ypename std::vector<T>::const_reference const_reference;
typedef ypename std::vector<T>::iterator iterator;
//typedef std::vector<T>::iterator iterator;
//这里通不过是因为少了typename
//在语法检查时编译器还不知道T是什么,自然也不知道vector<T>是什么
//也就无法确定std::vector<T>::iterator是类型
//所以要用typename来告诉它。
typedef ypename std::vector<T>::const_iterator const_iterator;



此外,实现begin并返回指针或者返回vector<T>::iterator与你的意图相违背,因为调用代码得到迭代器之后,你就无法再控制它了是否“不加同步直接读写”了。
[解决办法]
引用:
Quote: 引用:

没有人保证std::vector::iterator一定是一个指针。
所以,你应该:
    typedef typename std::vector<T>::size_type size_type;
typedef typename std::vector<T>::value_type value_type;
typedef ypename std::vector<T>::reference reference;
typedef ypename std::vector<T>::const_reference const_reference;
typedef ypename std::vector<T>::iterator iterator;
//typedef std::vector<T>::iterator iterator;
//这里通不过是因为少了typename
//在语法检查时编译器还不知道T是什么,自然也不知道vector<T>是什么
//也就无法确定std::vector<T>::iterator是类型
//所以要用typename来告诉它。
typedef ypename std::vector<T>::const_iterator const_iterator;


此外,实现begin并返回指针或者返回vector<T>::iterator与你的意图相违背,因为调用代码得到迭代器之后,你就无法再控制它了是否“不加同步直接读写”了。


感谢你的回复。按照你的做法,修改之后是OK的,我现在有个疑问,就是假如按照我之前的写法,那begin方法该如何写呢?


如果使用value_type*作为iterator,那么应该:


iterator begin()
{
return &m_vecCon.begin[0];
}
const_iterator begin() const
{
return &m_vecCon.begin[0];
}
iterator end()
{
return begin() + size();
}
const_iterator end() const
{


return begin() + size();
}

读书人网 >C++

热点推荐