Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# TQMemArray Class Reference

The TQMemArray class is a template class that provides arrays of simple types. More...

All the functions in this class are reentrant when TQt is built with thread support.

`#include <ntqmemarray.h>`

Inherited by TQByteArray and TQPointArray.

List of all member functions.

## Public Members

- typedef type * Iterator
- typedef const type * ConstIterator
- TQMemArray ()
- TQMemArray ( int size )
- TQMemArray ( const TQMemArray<type> & a )
- ~TQMemArray ()
- TQMemArray<type> & operator= ( const TQMemArray<type> & a )
- type * data () const
- uint nrefs () const
- uint size () const
- uint count () const
- bool isEmpty () const
- bool isNull () const
- bool resize ( uint size )
- bool resize ( uint size, Optimization optim )
- bool truncate ( uint pos )
- bool fill ( const type & v, int size = -1 )
- virtual void detach ()
- TQMemArray<type> copy () const
- TQMemArray<type> & assign ( const TQMemArray<type> & a )
- TQMemArray<type> & assign ( const type * data, uint size )
- TQMemArray<type> & duplicate ( const TQMemArray<type> & a )
- TQMemArray<type> & duplicate ( const type * data, uint size )
- TQMemArray<type> & setRawData ( const type * data, uint size )
- void resetRawData ( const type * data, uint size )
- int find ( const type & v, uint index = 0 ) const
- int contains ( const type & v ) const
- void sort ()
- int bsearch ( const type & v ) const
- type & operator[] ( int index ) const
- type & at ( uint index ) const
- operator const type * () const
- bool operator== ( const TQMemArray<type> & a ) const
- bool operator!= ( const TQMemArray<type> & a ) const
- Iterator begin ()
- Iterator end ()
- ConstIterator begin () const
- ConstIterator end () const

## Protected Members

- TQMemArray ( int, int )

## Related Functions

- TQ_UINT16 tqChecksum ( const char * data, uint len )
- TQDataStream & operator<< ( TQDataStream & s, const TQByteArray & a )
- TQDataStream & operator>> ( TQDataStream & s, TQByteArray & a )

## Detailed Description

The TQMemArray class is a template class that provides arrays of simple types.

TQMemArray is implemented as a template class. Define a template instance TQMemArray<X> to create an array that contains X items.

TQMemArray stores the array elements directly in the array. It can only deal with simple types (i.e. C++ types, structs, and classes that have no constructors, destructors, or virtual functions). TQMemArray uses bitwise operations to copy and compare array elements.

The TQPtrVector collection class is also a kind of array. Like most collection classes, it uses pointers to the contained items.

TQMemArray uses explicit sharing with a reference count. If more than one array shares common data and one of the arrays is modified, all the arrays are modified.

The benefit of sharing is that a program does not need to duplicate data when it is not required, which results in lower memory use and less copying of data.

An alternative to TQMemArray is TQValueVector. The TQValueVector class also provides an array of objects, but can deal with objects that have constructors (specifically a copy constructor and a default constructor). TQValueVector provides an STL-compatible syntax and is implicitly shared.

Example:

        #include <ntqmemarray.h>
        #include <stdio.h>

        TQMemArray<int> fib( int num ) // returns fibonacci array
        {
            Q_ASSERT( num > 2 );
            TQMemArray<int> f( num ); // array of ints

            f[0] = f[1] = 1;
            for ( int i = 2; i < num; i++ )
                f[i] = f[i-1] + f[i-2];

            return f;
        }

        int main()
        {
            TQMemArray<int> a = fib( 6 ); // get first 6 fibonaccis
            for ( int i = 0; i < a.size(); i++ )
                tqDebug( "%d: %d", i, a[i] );

            tqDebug( "1 is found %d times", a.contains(1) );
            tqDebug( "5 is found at index %d", a.find(5) );

            return 0;
        }

Program output:

        0: 1
        1: 1
        2: 2
        3: 3
        4: 5
        5: 8
        1 is found 2 times
        5 is found at index 4

Note concerning the use of TQMemArray for manipulating structs or classes: Compilers will often pad the size of structs of odd sizes up to the nearest word boundary. This will then be the size TQMemArray will use for its bitwise element comparisons. Because the remaining bytes will typically be uninitialized, this can cause find() etc. to fail to find the element. Example:

        // MyStruct may be padded to 4 or 8 bytes
        struct MyStruct
        {
            short i; // 2 bytes
            char c;  // 1 byte
        };

        TQMemArray<MyStruct> a(1);
        a[0].i = 5;
        a[0].c = 't';

        MyStruct x;
        x.i = '5';
        x.c = 't';
        int i = a.find( x ); // may return -1 if the pad bytes differ

To work around this, make sure that you use a struct where sizeof() returns the same as the sum of the sizes of the members either by changing the types of the struct members or by adding dummy members.

TQMemArray data can be traversed by iterators (see begin() and end()). The number of items is returned by count(). The array can be resized with resize() and filled using fill().

You can make a shallow copy of the array with assign() (or operator=()) and a deep copy with duplicate().

Search for values in the array with find() and contains(). For sorted arrays (see sort()) you can search using bsearch().

You can set the data directly using setRawData() and resetRawData(), although this requires care.

See also Shared Classes and Non-GUI Classes.

## Member Type Documentation

### TQMemArray::ConstIterator

A const TQMemArray iterator.

See also begin() and end().

### TQMemArray::Iterator

A TQMemArray iterator.

See also begin() and end().

## Member Function Documentation

### TQMemArray::TQMemArray ( int, int )`[protected]`

Constructs an array without allocating array space. The arguments should be (0, 0). Use at your own risk.

### TQMemArray::TQMemArray ()

Constructs a null array.

See also isNull().

### TQMemArray::TQMemArray ( int size )

Constructs an array with room for size elements. Makes a null array if size == 0.

The elements are left uninitialized.

See also resize() and isNull().

### TQMemArray::TQMemArray ( const TQMemArray<type> & a )

Constructs a shallow copy of a.

See also assign().

### TQMemArray::~TQMemArray ()

Dereferences the array data and deletes it if this was the last reference.

### TQMemArray<type> & TQMemArray::assign ( const TQMemArray<type> & a )

Shallow copy. Dereferences the current array and references the data contained in a instead. Returns a reference to this array.

See also operator=().

### TQMemArray<type> & TQMemArray::assign ( const type * data, uint size )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Shallow copy. Dereferences the current array and references the array data data, which contains size elements. Returns a reference to this array.

Do not delete data later; TQMemArray will call free() on it at the right time.

### type & TQMemArray::at ( uint index ) const

Returns a reference to the element at position index in the array.

This can be used to both read and set an element.

See also operator[]().

### Iterator TQMemArray::begin ()

Returns an iterator pointing at the beginning of this array. This iterator can be used in the same way as the iterators of TQValueList and TQMap, for example.

### ConstIterator TQMemArray::begin () const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns a const iterator pointing at the beginning of this array. This iterator can be used in the same way as the iterators of TQValueList and TQMap, for example.

### int TQMemArray::bsearch ( const type & v ) const

In a sorted array (as sorted by sort()), finds the first occurrence of v by using a binary search. For a sorted array this is generally much faster than find(), which does a linear search.

Returns the position of v, or -1 if v could not be found.

See also sort() and find().

### int TQMemArray::contains ( const type & v ) const

Returns the number of times v occurs in the array.

See also find().

### TQMemArray<type> TQMemArray::copy () const

Returns a deep copy of this array.

See also detach() and duplicate().

### uint TQMemArray::count () const

Returns the same as size().

See also size().

Example: scribble/scribble.cpp.

### type * TQMemArray::data () const

Returns a pointer to the actual array data.

The array is a null array if data() == 0 (null pointer).

See also isNull().

Examples: fileiconview/qfileiconview.cpp and network/networkprotocol/nntp.cpp.

### void TQMemArray::detach ()`[virtual]`

Detaches this array from shared array data; i.e. it makes a private, deep copy of the data.

Copying will be performed only if the reference count is greater than one.

See also copy().

Reimplemented in TQBitArray.

### TQMemArray<type> & TQMemArray::duplicate ( const TQMemArray<type> & a )

Deep copy. Dereferences the current array and obtains a copy of the data contained in a instead. Returns a reference to this array.

See also copy().

### TQMemArray<type> & TQMemArray::duplicate ( const type * data, uint size )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Deep copy. Dereferences the current array and obtains a copy of the array data data instead. Returns a reference to this array. The size of the array is given by size.

See also copy().

### Iterator TQMemArray::end ()

Returns an iterator pointing behind the last element of this array. This iterator can be used in the same way as the iterators of TQValueList and TQMap, for example.

### ConstIterator TQMemArray::end () const

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Returns a const iterator pointing behind the last element of this array. This iterator can be used in the same way as the iterators of TQValueList and TQMap, for example.

### bool TQMemArray::fill ( const type & v, int size = -1 )

Fills the array with the value v. If size is specified as different from -1, then the array will be resized before being filled.

Returns TRUE if successful, i.e. if size is -1, or size is != -1 and the memory can be allocated; otherwise returns FALSE.

See also resize().

### int TQMemArray::find ( const type & v, uint index = 0 ) const

Finds the first occurrence of v, starting at position index.

Returns the position of v, or -1 if v could not be found.

See also contains().

### bool TQMemArray::isEmpty () const

Returns TRUE if the array is empty; otherwise returns FALSE.

isEmpty() is equivalent to isNull() for TQMemArray (unlike TQString).

### bool TQMemArray::isNull () const

Returns TRUE if the array is null; otherwise returns FALSE.

A null array has size() == 0 and data() == 0.

### uint TQMemArray::nrefs () const

Returns the reference count for the shared array data. This reference count is always greater than zero.

### TQMemArray::operator const type * () const

Cast operator. Returns a pointer to the array.

See also data().

### bool TQMemArray::operator!= ( const TQMemArray<type> & a ) const

Returns TRUE if this array is different from a; otherwise returns FALSE.

The two arrays are compared bitwise.

See also operator==().

### TQMemArray<type> & TQMemArray::operator= ( const TQMemArray<type> & a )

Assigns a shallow copy of a to this array and returns a reference to this array.

Equivalent to assign( a ).

### bool TQMemArray::operator== ( const TQMemArray<type> & a ) const

Returns TRUE if this array is equal to a; otherwise returns FALSE.

The two arrays are compared bitwise.

See also operator!=().

### type & TQMemArray::operator[] ( int index ) const

Returns a reference to the element at position index in the array.

This can be used to both read and set an element. Equivalent to at().

See also at().

### void TQMemArray::resetRawData ( const type * data, uint size )

Removes internal references to the raw data that was set using setRawData(). This means that TQMemArray no longer has access to the data, so you are free to manipulate data as you wish. You can now use the TQMemArray without affecting the original data, for example by calling setRawData() with a pointer to some other data.

The arguments must be the data and length, size, that were passed to setRawData(). This is for consistency checking.

See also setRawData().

### bool TQMemArray::resize ( uint size, Optimization optim )

Resizes (expands or shrinks) the array to size elements. The array becomes a null array if size == 0.

Returns TRUE if successful, or FALSE if the memory cannot be allocated.

New elements are not initialized.

optim is either `TQGArray::MemOptim` (the default) or `TQGArray::SpeedOptim`.

Note: By default, `SpeedOptim` is not available for general use since it is only available if TQt is built in a particular configuration.

See also size().

Example: fileiconview/qfileiconview.cpp.

### bool TQMemArray::resize ( uint size )

This is an overloaded member function, provided for convenience. It behaves essentially like the above function.

Resizes (expands or shrinks) the array to size elements. The array becomes a null array if size == 0.

Returns TRUE if successful, i.e. if the memory can be allocated; otherwise returns FALSE.

New elements are not initialized.

See also size().

### TQMemArray<type> & TQMemArray::setRawData ( const type * data, uint size )

Sets raw data and returns a reference to the array.

Dereferences the current array and sets the new array data to data and the new array size to size. Do not attempt to resize or re-assign the array data when raw data has been set. Call resetRawData(data, size) to reset the array.

Setting raw data is useful because it sets TQMemArray data without allocating memory or copying data.

Example I (intended use):

        static char bindata[] = { 231, 1, 44, ... };
        TQByteArray  a;
        a.setRawData( bindata, sizeof(bindata) );   // a points to bindata
        TQDataStream s( a, IO_ReadOnly );            // open on a's data
        s >> <something>;                           // read raw bindata
        a.resetRawData( bindata, sizeof(bindata) ); // finished

Example II (you don't want to do this):

        static char bindata[] = { 231, 1, 44, ... };
        TQByteArray  a, b;
        a.setRawData( bindata, sizeof(bindata) );   // a points to bindata
        a.resize( 8 );                              // will crash
        b = a;                                      // will crash
        a[2] = 123;                                 // might crash
        // forget to resetRawData: will crash

Warning: If you do not call resetRawData(), TQMemArray will attempt to deallocate or reallocate the raw data, which might not be too good. Be careful.

See also resetRawData().

### uint TQMemArray::size () const

Returns the size of the array (maximum number of elements).

The array is a null array if size() == 0.

See also isNull() and resize().

### void TQMemArray::sort ()

Sorts the array elements in ascending order, using bitwise comparison (memcmp()).

See also bsearch().

### bool TQMemArray::truncate ( uint pos )

Truncates the array at position pos.

Returns TRUE if successful, i.e. if the memory can be allocated; otherwise returns FALSE.

Equivalent to resize(pos).

See also resize().

## Related Functions

### TQDataStream & operator<< ( TQDataStream & s, const TQByteArray & a )

Writes byte array a to the stream s and returns a reference to the stream.

See also Format of the TQDataStream operators.

### TQDataStream & operator>> ( TQDataStream & s, TQByteArray & a )

Reads a byte array into a from the stream s and returns a reference to the stream.

See also Format of the TQDataStream operators.

### TQ_UINT16 tqChecksum ( const char * data, uint len )

Returns the CRC-16 checksum of len bytes starting at data.

The checksum is independent of the byte order (endianness).

This file is part of the TQt toolkit. Copyright © 1995-2007 Trolltech. All Rights Reserved.