Insert rvalue in bst - c++

I'm trying to write an STL like container for BST. I have two different functions to insert lvalue and rvalue. Function with rvalue overwrites the all the previous inserted values.
Here is the code:
std::pair<iterator, bool> insert( value_type&& value ) {
return insert_unique( std::move( value ) );
}
template<typename Vp_> std::pair<iterator, bool> insert_unique( Vp_&& value ) {
node_holder_ h_ = make_node_holder( std::move( value ) );
node_pointer_ root_ = ( *header_ ).parent_;
node_pointer_ inserted_node = h_.release();
if ( root_ == nullptr ) {
( *header_ ).parent_ = inserted_node;
( *header_ ).left_ = inserted_node;
( *header_ ).right_ = inserted_node;
inserted_node->parent_ = header_;
size_++;
return std::make_pair( make_iterator( inserted_node ), true );
}
node_pointer_ parent = root_;
node_pointer_ x = root_;
while ( x != nullptr ) {
parent = x;
if ( compare_( inserted_node->key_, x->key_ ) )
x = x->left_;
else if ( compare_( x->key_, inserted_node->key_ ) )
x = x->right_;
else
return std::make_pair( make_iterator( x ), false );
}
if ( compare_( inserted_node->key_, parent->key_ ) )
parent->left_ = inserted_node;
else
parent->right_ = inserted_node;
inserted_node->parent_ = parent;
// Update leftmost and right most
if ( compare_( inserted_node->key_, leftmost()->key_ ) ) ( *header_ ).left_ = inserted_node;
if ( !( compare_( inserted_node->key_, rightmost()->key_ ) ) &&
!( compare_( rightmost()->key_, inserted_node->key_ ) ) ) {
( *header_ ).right_ = inserted_node;
inserted_node->right_ = header_;
}
size_++;
return std::make_pair( make_iterator( inserted_node ), true );
}
node_holder_ make_node_holder( value_type&& value ) {
// std::cout << "args holders " << std::endl;
node_allocator_& na_ = get_allocator();
node_holder_ nh_( na_.allocate( 1 ), node_destructor_( na_ ) );
node_traits_::construct( na_, nh_.get(), std::move( value ) );
nh_.get_deleter().value_constructed_ = true;
return std::move( nh_ );
}
I referred to the talk by Scott-Meyers and cascaded the rvalue by using std::move. But, there is some error in the code which is causing the overwrite. Can you please share if you are able to identify the error causing this issue?
Code repository. The bst.h class is in lib/ directory.
Please share if you have any other comments and feedback on the code.

Related

double probe hash table

I am trying to edit my hash table to form a double hashing class but can't seem to get it right.
I was wondering if anyone had any insight. I was told that all I needed to do was edit the findPos() where I now have to provide new probes using a new strategy.
**I did some research and it says in double probing you would use R-(x mod R) where R >size and a prime smaller than the table size. So do I make a new rehash function?
here is my code:
template <typename HashedObj>
class HashTable
{
public:
explicit HashTable( int size = 101 ) : array( nextPrime( size ) )
{ makeEmpty( ); }
bool contains( const HashedObj & x ) const
{
return isActive( findPos( x ) );
}
void makeEmpty( )
{
currentSize = 0;
for( auto & entry : array )
entry.info = EMPTY;
}
bool insert( const HashedObj & x )
{
// Insert x as active
int currentPos = findPos( x );
if( isActive( currentPos ) )
return false;
if( array[ currentPos ].info != DELETED )
++currentSize;
array[ currentPos ].element = x;
array[ currentPos ].info = ACTIVE;
// Rehash;
if( currentSize > array.size( ) / 2 )
rehash( );
return true;
}
bool insert( HashedObj && x )
{
// Insert x as active
int currentPos = findPos( x );
if( isActive( currentPos ) )
return false;
if( array[ currentPos ].info != DELETED )
++currentSize;
array[ currentPos ] = std::move( x );
array[ currentPos ].info = ACTIVE;
// Rehash; see Section 5.5
if( currentSize > array.size( ) / 2 )
rehash( );
return true;
}
bool remove( const HashedObj & x )
{
int currentPos = findPos( x );
if( !isActive( currentPos ) )
return false;
array[ currentPos ].info = DELETED;
return true;
}
enum EntryType { ACTIVE, EMPTY, DELETED };
private:
struct HashEntry
{
HashedObj element;
EntryType info;
HashEntry( const HashedObj & e = HashedObj{ }, EntryType i = EMPTY )
: element{ e }, info{ i } { }
HashEntry( HashedObj && e, EntryType i = EMPTY )
: element{ std::move( e ) }, info{ i } { }
};
vector<HashEntry> array;
int currentSize;
bool isActive( int currentPos ) const
{ return array[ currentPos ].info == ACTIVE; }
int findPos( const HashedObj & x ) const
{
int offset = 1;
int currentPos = myhash( x );
while( array[ currentPos ].info != EMPTY &&
array[ currentPos ].element != x )
{
currentPos += offset; // Compute ith probe
offset += 2;
if( currentPos >= array.size( ) )
currentPos -= array.size( );
}
return currentPos;
}
void rehash( )
{
vector<HashEntry> oldArray = array;
// Create new double-sized, empty table
array.resize( nextPrime( 2 * oldArray.size( ) ) );
for( auto & entry : array )
entry.info = EMPTY;
// Copy table over
currentSize = 0;
for( auto & entry : oldArray )
if( entry.info == ACTIVE )
insert( std::move( entry.element ) );
}
size_t myhash( const HashedObj & x ) const
{
static hash<HashedObj> hf;
return hf( x ) % array.size( );
}
};
I am not sure of understanding your code, but let me pose some observations that they should not be considered as an answer, but their size is greater that what is allowed to comment.
If you use quadratic probing, then I think in the method findPos() you should advance currentPos in some as currentPos*currentPos % array.size(). Currently, as I see, you increase currentPos in one unity (offset is initially 1), after 2 unities, after 4 and so on
Probably you are trying a fast way for compute the quadratic probe. If this is the case, then offset should not be increased by two, but multiplied by two. That would be some as offset *= 2, but because you should count the number of collisions you should increase offset.
Maybe a simpler way would be:
currentPos += 2*offset++ - 1; // fast way of doing quadratic resolution
Your resizing is ok, given that it guarantees that the table will be at least half empty and consequently the search of availables entries when the insertion is executed is guaranteed.
Good luck
It appears that you want to implement double hashing for probing. This is a technique for resolving collisions by using a second hash of the input key. In the original quadratic function, you continually add an increasing offset to the index value until you find an empty spot in the hash table. The only important difference in a double hashing function would be the value of the offset.
If I were you, I would create a new hash function which is similar to the first one, but I would replace the return statement with return R - ( hf(x) % R ); for a provided R value. Then I would change findPos to set offset equal to this second hash function (Also remember to remove the offset += 2; line because the offset is no longer increasing).

How to optimize out the space a class reference member takes?

template<typename T>
struct UninitializedField
{
T& X;
inline UninitializedField( ) : X( *( T* )&DATA )
{
}
protected:
char DATA[ sizeof( T ) ];
};
int main( )
{
UninitializedField<List<int>> LetsTest;
printf( "%u, %u\n", sizeof( LetsTest ), sizeof( List<int> ) );
}
I am trying to program a class that wraps an object without being automatically initialize\constructed.
But when I execute my program the output is:
8, 4
Is there a way to optimize out the dereference to get into the object in X and the space it takes?
template<typename T>
struct UninitializedField {
__inline UninitializedField( const T &t ) {
*( ( T* )this ) = t;
}
__inline UninitializedField( bool Construct = false, bool Zero = true ) {
if ( Zero )
memset( this, 0, sizeof( *this ) );
if ( Construct )
*( ( T* )this ) = T( );
}
__inline T *operator->( ) {
return ( T* )this;
}
__inline T &operator*( ) {
return *( ( T* )this );
}
protected:
char DATA[ sizeof( T ) ];
};
There isn't any space taken, and with compiler-optimization on there's no call to function.

Segmentation fault due possible loose pointers

I'm having some issues regarding a segment fault
Program received signal SIGSEGV, Segmentation fault.
0x0000000000403a62 in std::_Deque_iterator<float, float&, float*>::_Deque_iterator (this=0x7fffffffc5c0, __x=...)
at /usr/include/c++/4.6/bits/stl_deque.h:136
136 _M_last(__x._M_last), _M_node(__x._M_node) { }
(gdb) up
#1 0x0000000000403a0f in std::deque<float, std::allocator<float> >::begin (this=0x64) at /usr/include/c++/4.6/bits/stl_deque.h:1010
1010 { return this->_M_impl._M_start; }
(gdb) up
#2 0x000000000040326f in std::deque<float, std::allocator<float> >::front (this=0x64) at /usr/include/c++/4.6/bits/stl_deque.h:1286
1286 { return *begin(); }
(gdb) up
#3 0x000000000040248c in std::queue<float, std::deque<float, std::allocator<float> > >::front (this=0x64)
at /usr/include/c++/4.6/bits/stl_queue.h:165
165 return c.front();
(gdb) up
#4 0x0000000000402ee3 in KDTree::Node::Create (this=0x6251c0, coords=0x623ec0, limit=500) at KDTree.hxx:64
64 if( ( *itC ) -> front() > maxAbove ) maxAbove = ( *itC ) -> front();
Here's the piece of code
template< class T, class D >
void KDTree< T, D >::Node::
Create( Coords* coords, D limit )
{
Coords* newCoordsBelowMedian = new Coords();
Coords* newCoordsAboveMedian = new Coords();
D maxAbove = 0,
minAbove = 0,
maxBelow = 0,
minBelow = 0;
this -> m_Coords = coords;
this -> m_Median = GetMedian( *coords );
typename Coords :: iterator itC = this -> m_Coords -> begin( );
//Change of coordinates for next iteration
for( ; itC != this -> m_Coords -> end( ); itC++ )
{
Dims* newDim = *itC;
D value = newDim -> front( );
newDim -> pop( );
newDim -> push( value );
if( newDim -> front() >= this -> m_Median ) newCoordsAboveMedian -> insert( );
else newCoordsBelowMedian -> insert( );
}
typename Coords :: iterator itCA = newCoordsAboveMedian -> begin( );
typename Coords :: iterator itCB = newCoordsBelowMedian -> begin( );
minBelow = std::numeric_limits<D>::max();
minAbove = std::numeric_limits<D>::max();
//Max radius
for( ; itC != newCoordsAboveMedian -> end( ); itCA++ )
{
if( ( *itC ) -> front() > maxAbove ) maxAbove = ( *itC ) -> front();
if( ( *itC ) -> front() < minAbove ) minAbove = ( *itC ) -> front();
}
for( ; itC != newCoordsBelowMedian -> end( ); itCB++ )
{
if( ( *itC ) -> front() > maxBelow ) maxBelow = ( *itC ) -> front();
if( ( *itC ) -> front() > maxBelow ) minBelow = ( *itC ) -> front();
}
if( abs( maxAbove - minAbove ) < limit && newCoordsAboveMedian -> size() > 0 )
{
this -> m_R = new Node();
this -> m_R -> Create( newCoordsAboveMedian, limit );
}
if( abs( maxBelow - minBelow ) < limit && newCoordsAboveMedian -> size() > 0 )
{
this -> m_L = new Node();
this -> m_L -> Create( newCoordsBelowMedian, limit );
}
}
I suspect is because pointers at the first for are being lost upon completion, however, I don't know any solution to this issue, any thoughts?
It seems itC is an iterator for this -> m_Coords which got run to the end in the first loop. The same iterator is used to control the later loops. Did you mean this loop
for( ; itC != newCoordsAboveMedian -> end( ); itCA++ )
{
if( ( *itC ) -> front() > maxAbove ) maxAbove = ( *itC ) -> front();
if( ( *itC ) -> front() < minAbove ) minAbove = ( *itC ) -> front();
}
To read
for( ; itCA != newCoordsAboveMedian -> end( ); itCA++ )
{
if( ( *itCA ) -> front() > maxAbove ) maxAbove = ( *itCA ) -> front();
if( ( *itCA ) -> front() < minAbove ) minAbove = ( *itCA ) -> front();
}
... or, what I would do if I were to write this loop:
for (typename Coords::iterator it = newCoordsAboveMedian->begin( ),
end = newCoordsAboveMedian->end();
it != end; ++it) {
if( ( *it ) -> front() > maxAbove ) maxAbove = ( *it ) -> front();
if( ( *it ) -> front() < minAbove ) minAbove = ( *it ) -> front();
}
(likewise for the other loop).

how can i oveload a subscript operator of a template class

i have to basically edit a quadratic probing file to work as a hash_map library but i'm having trouble overloading the subscript operator so i can modify that specefic index.
the code i have so far is:
template <typename HashedObj, typename storedObj >
class HashTable
{
public:
int& operator [] (const int nIndex)
{
return array[nIndex];//THIS IS WHATS WRONG
}
//create hashtable with siz of 101
explicit HashTable(int size = 101) : array( nextPrime( size ) )
{ makeEmpty( ); }
//return true if current index is active
bool contains( const HashedObj & x ) const
{
return isActive( findPos( x ) );
}
//initiallize index as empty
void makeEmpty( )
{
currentSize = 0;
for( int i = 0; i < array.size( ); i++ )
array[ i ].info = EMPTY;
}
//insert object into hash index and mark index as active
bool insert( const HashedObj & x )
{
// Insert x as active
int currentPos = findPos( x );
if( isActive( currentPos ) )
return false;
array[ currentPos ] = HashEntry( x, ACTIVE );
if( ++currentSize > array.size( ) / 2 )
rehash( );
return true;
}
//search for obj and mark index as deleted
bool remove( const HashedObj & x )
{
int currentPos = findPos( x );
if( !isActive( currentPos ) )
return false;
array[ currentPos ].info = DELETED;
return true;
}
//declare three different entry types
enum EntryType { ACTIVE, EMPTY, DELETED };
private:
//each hash index stores the following
struct HashEntry
{
//THIS WILL BE STRINGS OR INTS
HashedObj element;
//THIS WILL BE VECTOR STRINGS
storedObj ilement;
//index status is stored
EntryType info;
//each entry is made of hashed obj and stored obj and the status is empty
HashEntry( const HashedObj & e = HashedObj( ), const storedObj & f = storedObj( ),EntryType i = EMPTY )
: element( e ), ilement( f ),info( i ) { }
};
//create an array of hashentries
vector<HashEntry> array;
//currentsize of the hash table is stored here
int currentSize;
bool isActive( int currentPos ) const
{ return array[ currentPos ].info == ACTIVE; }
int findPos( const HashedObj & x ) const
{
int offset = 1;
int currentPos = myhash( x );
while( array[ currentPos ].info != EMPTY &&
array[ currentPos ].element != x )
{
currentPos += offset; // Compute ith probe
offset += 2;
if( currentPos >= array.size( ) )
currentPos -= array.size( );
}
return currentPos;
}
void rehash( )
{
vector<HashEntry> oldArray = array;
// Create new double-sized, empty table
array.resize( nextPrime( 2 * oldArray.size( ) ) );
for( int j = 0; j < array.size( ); j++ )
array[ j ].info = EMPTY;
// Copy table over
currentSize = 0;
for( int i = 0; i < oldArray.size( ); i++ )
if( oldArray[ i ].info == ACTIVE )
insert( oldArray[ i ].element );
}
int myhash( const HashedObj & x ) const
{
int hashVal = hashing( x );
hashVal %= array.size( );
if( hashVal < 0 )
hashVal += array.size( );
return hashVal;
}
};
int hashing( const string & key );
int hashing( int key );
the point is for main code to be able to do something like:
wordsByLength[words[i].length()] = words[i];
where words[i] will be a vector. i'm also assuming that i will need to modify the = operator later on but i'm not so sure
Think about what your subscript operator shall return. Is it int&? The simplest choice would be HashEntry:
template <typename HashedObj, typename storedObj >
class HashTable
{
public:
HashEntry& operator [] (int nIndex) // read/write version
{
return array[nIndex];
}
const HashEntry& operator [] (int nIndex) const // read only version
{
return array[nIndex];//THIS IS WHATS WRONG
}
...
};
But it is private. So either make it public - but this breaks somehow your encapsulation.
Because your are inserting HashedObj - then probably this is your desired return type:
template <typename HashedObj, typename storedObj >
class HashTable
{
public:
HashedObj& operator [] (int nIndex) // read/write version
{
return array[nIndex].element;
}
const HashedObj& operator [] (int nIndex) const // read only version
{
return array[nIndex].element;
}
...
};

Format the output of qDebug for QMaps

i am currently in the process of maintaining a legacy app. This has quite a few structures like:
QMap<QString, QMap<QString, QMap<QString, QMap<QString, QVariant> > > > Dep;
As interfaces are hardly used and I only need to make minor adjustments, I would like to keep the structure as it is, although some refactoring might be needed anyway.
But to be able to understand what is going on, currently I just put some qDebug() << Dep; in there, and try to understand the output.
Problem is that it has no formatting at all. Does anyone know of a little script to create a better understandable display format? Or maybe of some patches to Qt?
To give you an example for my suffering:
QMap(("Test enable|test enable block", QMap(("disabled", QMap(("testblock1", QMap(("enableblock", QVariant(QString, "false") ) ) ) ) ) ( "enabled" , QMap(("testblock1", QMap(("enableblock", QVariant(QString, "true") ) ) ) ) ) ) ) ( "Test enable|test enable key" , QMap(("disabled", QMap(("testblock1|testkey", QMap(("enablekey", QVariant(QString, "false") ) ) ) ) ) ( "enabled" , QMap(("testblock1|testkey", QMap(("enablekey", QVariant(QString, "true") ) ) ) ) ) ) ) ( "testinsertitems|Insert item" , QMap(("test1", QMap(("testinsertitems|testinsert", QMap(("insertitems", QVariant(QVariantMap, QMap(("test1", QVariant(QString, "test1") ) ) ) ) ) ) ( "testinsertitems|testremove" , QMap(("removeitems", QVariant(QVariantMap, QMap(("test1", QVariant(QString, "test1") ) ) ) ) ) ) ) ) ( "test2" , QMap(("testinsertitems|testinsert", QMap(("insertitems", QVariant(QVariantMap, QMap(("test2", QVariant(QString, "test2") ) ) ) ) ) ) ( "testinsertitems|testremove" , QMap(("removeitems", QVariant(QVariantMap, QMap(("test2", QVariant(QString, "test2") ) ) ) ) ) ) ) ) ) ) ( "testsetminmax|test setmin" , QMap(("2", QMap(("testsetminmax|testkey1", QMap(("setmin", QVariant(int, 2) ) ) ) ( "testsetminmax|testkey2" , QMap(("setmax", QVariant(int, 2) ) ) ) ) ) ( "3" , QMap(("testsetminmax|testkey1", QMap(("setmin", QVariant(int, 3) ) ) ) ( "testsetminmax|testkey2" , QMap(("setmax", QVariant(int, 3) ) ) ) ) ) ) ) ( "testsetvalue|test set value" , QMap(("2", QMap(("testsetvalue|testkey1", QMap(("setvalue", QVariant(QString, "2") ) ) ) ( "testsetvalue|testkey2" , QMap(("setvalue", QVariant(QString, "2") ) ) ) ( "testsetvalue|testkey3" , QMap(("setvalue", QVariant(QString, "2") ) ) ) ) ) ( "3" , QMap(("testsetvalue|testkey1", QMap(("setvalue", QVariant(QString, "3") ) ) ) ( "testsetvalue|testkey2" , QMap(("setvalue", QVariant(QString, "3") ) ) ) ( "testsetvalue|testkey3" , QMap(("setvalue", QVariant(QString, "3") ) ) ) ) ) ) ) )
Thanks
This one is for n-dimensions and will use the standard qDebug output for known types:
template<class NonMap>
struct Print
{
static void print(const QString& tabs, const NonMap& value)
{
qDebug() << tabs << value;
}
};
template <class Key, class ValueType >
struct Print<class QMap<Key, ValueType> >
{
static void print(const QString& tabs, const QMap< Key, ValueType>& map )
{
const QString extraTab = tabs + "\t";
QMapIterator<Key, ValueType> iterator(map);
while(iterator.hasNext())
{
iterator.next();
qDebug() << tabs << iterator.key();
Print<ValueType>::print(extraTab, iterator.value());
}
}
};
template<class Type>
void printMe(const Type& type )
{
Print<Type>::print("", type);
};
A four dimensional structure is notoriously hard to visualize.
But how about some small loops?
typedef QMap<QString, QVariant> T1;
typedef QMap<QString, T1> T2;
typedef QMap<QString, T2> T3;
foreach( T3 i, dep ) {
cout << "******" << i.key() << "*******" << endl << endl;
foreach ( T2 j, i.value() ) {
cout << j.key() << ":" << endl;
foreach ( T3 k, j.value() ) {
cout << k.key() << "= ";
foreach ( QVariant l, k.value() ) {
cout << l.key() << ": " << l.value() << " ";
}
cout << endl;
}
}
}
Using namespace std, of course. Add in setw() as you like. Hope you get the idea.