Qt:Документация 4.3.2/q3memarray

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск
40px Внимание: Актуальная версия перевода документации находится здесь

__NOTOC__

Image:qt-logo.png

Главная · Все классы · Основные классы · Классы по группам · Модули · Функции

Image:trolltech-logo.png

Содержание

[править] Q3MemArray Class Reference
[ Qt3Support module]

The Q3MemArray class is a template class that provides arrays of simple types. Далее...

 #include <Q3MemArray>

This class is part of the Qt 3 support library. It is provided to keep old source code working. Мы настоятельно не рекомендуем использовать этот класс в новом коде. See Porting to Qt 4 for more information.

[править] Открытые типы

[править] Открытые функции

[править] Защищенные функции


[править] Подробное описание

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

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

Q3MemArray 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). Q3MemArray uses bitwise operations to copy and compare array elements.

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

Q3MemArray 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.

Пример:

 #include <qmemarray.h>
 #include <stdio.h>
 
 Q3MemArray<int> fib( int num ) // returns fibonacci array
 {
     Q_ASSERT( num > 2 );
     Q3MemArray<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()
 {
     Q3MemArray<int> a = fib( 6 ); // get first 6 fibonaccis
     for ( int i = 0; i < a.size(); i++ )
         qDebug( "%d: %d", i, a[i] );
 
     qDebug( "1 is found %d times", a.contains(1) );
     qDebug( "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 Q3MemArray 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 Q3MemArray 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. Пример:

 // MyStruct may be padded to 4 or 8 bytes
 struct MyStruct
 {
     short i; // 2 bytes
     char c;  // 1 byte
 };
 
 Q3MemArray<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.

Q3MemArray 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.


[править] Описание типов

[править]
typedef Q3MemArray::ConstIterator

A const Q3MemArray iterator.

See also begin() and end().

[править]
typedef Q3MemArray::Iterator

A Q3MemArray iterator.

See also begin() and end().


[править] Описание функций-членов

[править]
Q3MemArray::Q3MemArray ( int arg1, int arg2 ) [protected]

Constructs an array without allocating array space. The arguments arg1 and arg2 should be zero. Use at your own risk.

[править]
Q3MemArray::Q3MemArray ()

Constructs a null array.

Смотрите также isNull().

[править]
Q3MemArray::Q3MemArray ( 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().

[править]
Q3MemArray::Q3MemArray ( const Q3MemArray<type> & a )

Constructs a shallow copy of a.

See also assign().

[править]
Q3MemArray::Q3MemArray ( const QVector<type> & vector )

Constructs a copy of vector.

[править]
Q3MemArray::~Q3MemArray ()

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

[править]
Q3MemArray<type> & Q3MemArray::assign ( const Q3MemArray<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=().

[править]
Q3MemArray<type> & Q3MemArray::assign ( const type * data, uint size )

Эта перегруженная функция предоставлена для удобства.

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; Q3MemArray will call free() on it at the right time.

[править]
type & Q3MemArray::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 Q3MemArray::begin ()

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

[править]
ConstIterator Q3MemArray::begin () const

Эта перегруженная функция предоставлена для удобства.

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

[править]
int Q3MemArray::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 Q3MemArray::contains ( const type & v ) const

Returns the number of times v occurs in the array.

See also find().

[править]
Q3MemArray<type> Q3MemArray::copy () const

Returns a deep copy of this array.

See also detach() and duplicate().

[править]
uint Q3MemArray::count () const

Returns the same as size().

See also size().

[править]
type * Q3MemArray::data () const

Returns a pointer to the actual array data.

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

Смотрите также isNull().

[править]
void Q3MemArray::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().

[править]
Q3MemArray<type> & Q3MemArray::duplicate ( const Q3MemArray<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().

[править]
Q3MemArray<type> & Q3MemArray::duplicate ( const type * data, uint size )

Эта перегруженная функция предоставлена для удобства.

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 Q3MemArray::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 Q3ValueList and QMap, for example.

[править]
ConstIterator Q3MemArray::end () const

Эта перегруженная функция предоставлена для удобства.

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 Q3ValueList and QMap, for example.

[править]
bool Q3MemArray::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 Q3MemArray::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 Q3MemArray::isEmpty () const

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

isEmpty() is equivalent to isNull() for Q3MemArray (unlike QString).

[править]
bool Q3MemArray::isNull () const

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

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

[править]
uint Q3MemArray::nrefs () const

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

[править]
void Q3MemArray::resetRawData ( const type * data, uint size )

Removes internal references to the raw data that was set using setRawData(). This means that Q3MemArray no longer has access to the data, so you are free to manipulate data as you wish. You can now use the Q3MemArray 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 Q3MemArray::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 Q3GArray::MemOptim (the default) or Q3GArray::SpeedOptim. When optimizing for speed rather than memory consumption, the array uses a smart grow and shrink algorithm that might allocate more memory than is actually needed for size elements. This speeds up subsequent resize operations, for example when appending many elements to an array, since the space has already been allocated.

See also size().

[править]
bool Q3MemArray::resize ( uint size )

Эта перегруженная функция предоставлена для удобства.

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().

[править]
Q3MemArray<type> & Q3MemArray::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 Q3MemArray data without allocating memory or copying data.

Example I (intended use):

 static char bindata[] = { 231, 1, 44, ... };
 QByteArray  a;
 a.setRawData( bindata, sizeof(bindata) );   // a points to bindata
 QDataStream 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, ... };
 QByteArray  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(), Q3MemArray will attempt to deallocate or reallocate the raw data, which might not be too good. Be careful.

See also resetRawData().

[править]
uint Q3MemArray::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 Q3MemArray::sort ()

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

See also bsearch().

[править]
bool Q3MemArray::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().

[править]
Q3MemArray::operator QVector<type> () const

Automatically converts the Q3MemArray<type> into a QVector<type>.

[править]
Q3MemArray::operator const type * () const

Cast operator. Returns a pointer to the array.

Смотрите также data().

[править]
bool Q3MemArray::operator!= ( const Q3MemArray<type> & a ) const

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

The two arrays are compared bitwise.

Смотрите также operator==().

[править]
Q3MemArray<type> & Q3MemArray::operator= ( const Q3MemArray<type> & a )

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

Equivalent to assign( a ).

[править]
bool Q3MemArray::operator== ( const Q3MemArray<type> & a ) const

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

The two arrays are compared bitwise.

Смотирте также operator!=().

[править]
type & Q3MemArray::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().



Copyright © 2007 Trolltech Trademarks
Qt 4.3.2