Re: stl help needed
On Oct 29, 11:57 am, DJ Dharme <donjuandharmap...@gmail.com> wrote:
Hi,
I really like to use stl as much as possible in my code. B=
ut I
found it really hard to understand by looking into there source code.
I have no idea about what iterator traits, heaps and allocators are.
So I started to write my own container class to learn templates. I
thought about a sorted vector class which have a additional two
methods sort and insert sorted. The usage of this class is like this.
1. We can reserve some space and push all the items to the vector and
then do a sort.
2. We can insert a new item to a sorted vector by using a binary
search.
Here is my initial code. Can somebody help me to modify it so that I
can understand the concepts behind stl. How can I use allocators,
iterator traits in this class?
[ snip ]
Why aren't you using a std::vector in your type instead of reinventing
the wheel?
The type's name is missleading to me unless you sort upon insertion
(in which case you then have an associative container, see std::set<
).
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
template < typename T, typename Predicate = std::less< T > >
class sorted_vector
{
std::vector< T > m_vt;
public:
sortable_vector() : m_vt() { }
// member functions
void push_back( const T& r_t )
{
m_vt.push_back( r_t );
}
void sort()
{
std::sort( m_vt.begin(), m_vt.end() );
}
// iteration
typedef typename std::vector< T >::iterator iterator;
iterator begin() { return m_vt.begin(); }
iterator end() { return m_vt.end(); }
typedef typename std::vector< T >::const_iterator const_iterator;
const_iterator begin() const { return m_vt.begin(); }
const_iterator end() const { return m_vt.end(); }
// friend op<<
friend
std::ostream&
operator<<( std::ostream& os, const sorted_vector< T >& sv )
{
std::copy( sv.begin(),
sv.end(),
std::ostream_iterator< T >(os, "\n") );
return os;
}
};
int main()
{
sortable_vector< std::string > strings;
strings.push_back("bbb bbb");
strings.push_back("aaa aaa");
strings.push_back("ccc ccc");
std::cout << strings << std::endl;
strings.sort();
std::cout << strings << std::endl;
std::cout << "Press ENTER to EXIT.\n";
std::cin.get();
}
/*
bbb bbb
aaa aaa
ccc ccc
aaa aaa
bbb bbb
ccc ccc
*/
As far as iterator traits are concerned, you worry about
iterator_tag(s) when some templated algorithm has specializations for
the different types of iterators (random access iterators, input
iterators, output iterators, etc).