S
Shriramana Sharma
I have been wanting to use a container with efficient inserts and deletes in the middle. Hence it seems list is my choice. But I also require indexed access which list doesn't provide. Hence I thought of the following workaround. Since I'm not an expert, I'd like comments from the experts here. Thanks.
--- randomlist.hpp ---
# include <list>
# include <algorithm>
# include <stdexcept>
namespace std
{
template < typename T >
class randomlist : public list<T>
{
typedef typename list<T>::reference reference ;
typedef typename list<T>::const_reference const_reference ;
typedef typename list<T>::size_type size_type ;
typedef typename list<T>::iterator iterator ;
protected :
void range_check ( size_type n ) const
{
if ( n >= this->size() ) throw std:ut_of_range ( "randomlist index out of range" ) ;
}
public :
// element access
// this is what is missing from list
reference operator [] ( size_type n )
{
iterator it = this->begin() ;
std::advance ( it, n ) ;
return *it ;
}
const_reference operator [] ( size_type n ) const
{
iterator it = this->begin() ;
std::advance ( it, n ) ;
return *it ;
}
reference at ( size_type n )
{
range_check ( n ) ;
return (*this)[n] ;
}
const_reference at ( size_type n ) const
{
range_check ( n ) ;
return (*this)[n] ;
}
} ;
} // namespace std
--- randomlist-test.cpp ---
# include "randomlist.hpp"
# include <iostream>
using namespace std ;
int main ()
{
randomlist<int> l1 ;
l1 << 1 << 2 << -1 << 4 << -5 << 6 ;
cout << l1[6] << endl ;
cout << l1.at(6) << endl ;
// list<int> l2 ;
// l2 . push_back ( 10 ) ;
// cout << l2[0] << endl ;
}
--- randomlist.hpp ---
# include <list>
# include <algorithm>
# include <stdexcept>
namespace std
{
template < typename T >
class randomlist : public list<T>
{
typedef typename list<T>::reference reference ;
typedef typename list<T>::const_reference const_reference ;
typedef typename list<T>::size_type size_type ;
typedef typename list<T>::iterator iterator ;
protected :
void range_check ( size_type n ) const
{
if ( n >= this->size() ) throw std:ut_of_range ( "randomlist index out of range" ) ;
}
public :
// element access
// this is what is missing from list
reference operator [] ( size_type n )
{
iterator it = this->begin() ;
std::advance ( it, n ) ;
return *it ;
}
const_reference operator [] ( size_type n ) const
{
iterator it = this->begin() ;
std::advance ( it, n ) ;
return *it ;
}
reference at ( size_type n )
{
range_check ( n ) ;
return (*this)[n] ;
}
const_reference at ( size_type n ) const
{
range_check ( n ) ;
return (*this)[n] ;
}
} ;
} // namespace std
--- randomlist-test.cpp ---
# include "randomlist.hpp"
# include <iostream>
using namespace std ;
int main ()
{
randomlist<int> l1 ;
l1 << 1 << 2 << -1 << 4 << -5 << 6 ;
cout << l1[6] << endl ;
cout << l1.at(6) << endl ;
// list<int> l2 ;
// l2 . push_back ( 10 ) ;
// cout << l2[0] << endl ;
}