QList Class ReferenceThe QList class is a template class that provides lists. Далее... #include <QList> Inherited by: QItemSelection, QQueue, QSignalSpy, QStringList, and QTestEventList. Замечание: Все функции в этом классе реентерабельны. Открытые типы
Открытые функции
Статические открытые члены
Связанные нечлены класса
Подробное описаниеThe QList class is a template class that provides lists. QList<T> is one of Qt's generic container classes. It stores a list of values and provides fast index-based access as well as fast insertions and removals. QList<T>, QLinkedList<T>, and QVector<T> provide similar functionality. Вот краткий обзор:
Internally, QList<T> is represented as an array of pointers to items of type T. If T is itself a pointer type or a basic type that is no larger than a pointer, or if T is one of Qt's shared classes, then QList<T> stores the items directly in the pointer array. For lists under a thousand items, this array representation allows for very fast insertions in the middle, and it allows index-based access. Furthermore, operations like prepend() and append() are very fast, because QList preallocates memory at both ends of its internal array. (See Algorithmic Complexity for details.) Note, however, that for unshared list items that are larger than a pointer, each append or insert of a new item requires allocating the new item on the heap, and this per item allocation might make QVector a better choice in cases that do lots of appending or inserting, since QVector allocates memory for its items in a single heap allocation. Note that the internal array only ever gets bigger over the life of the list. It never shrinks. The internal array is deallocated by the destructor and by the assignment operator, when one list is assigned to another. Here's an example of a QList that stores integers and a QList that stores QDate values: QList<int> integerList; QList<QDate> dateList; Qt includes a QStringList class that inherits QList<QString> and adds a few convenience functions, such as QStringList::join() and QStringList::find(). (QString::split() creates QStringLists from strings.) QList stores a list of items. The default constructor creates an empty list. To insert items into the list, you can use operator<<(): QList<QString> list; list << "one" << "two" << "three"; // list: ["one", "two", "three"] QList provides these basic functions to add, move, and remove items: insert(), replace(), removeAt(), move(), and swap(). In addition, it provides the following convenience functions: append(), prepend(), removeFirst(), and removeLast(). QList uses 0-based indexes, just like C++ arrays. Для доступа к элементу с позицией по определённому индексу вы можете использовать operator[](). On non-const lists, operator[]() returns a reference to the item and can be used on the left side of an assignment: if (list[0] == "Bob") list[0] = "Robert"; Because QList is implemented as an array of pointers, this operation is very fast (constant time). For read-only access, an alternative syntax is to use at(): for (int i = 0; i < list.size(); ++i) { if (list.at(i) == "Jane") cout << "Found Jane at position " << i << endl; } at() может работать быстрее, чем operator[](), потому что при этом никогда не создается полной копии. A common requirement is to remove an item from a list and do something with it. For this, QList provides takeAt(), takeFirst(), and takeLast(). Here's a loop that removes the items from a list one at a time and calls delete on them: QList<QWidget *> list; ... while (!list.isEmpty()) delete list.takeFirst(); Inserting and removing items at either ends of the list is very fast (constant time in most cases), because QList preallocates extra space on both sides of its internal buffer to allow for fast growth at both ends of the list. If you want to find all occurrences of a particular value in a list, use indexOf() or lastIndexOf(). Первая функция осуществляет поиск вперед от указанной позиции, а последняя - осуществляет поиск назад. Both return the index of a matching item if they find it; otherwise, they return -1. Например: int i = list.indexOf("Jane"); if (i != -1) cout << "First occurrence of Jane is at position " << i << endl; If you simply want to check whether a list contains a particular value, use contains(). If you want to find out how many times a particular value occurs in the list, use count(). If you want to replace all occurrences of a particular value with another, use replace(). QList's value type must be an assignable data type. Это охватывает большинство обычно используемых типов данных, но компилятор не позволит вам хранить как значение, например, QWidget; вместо этого сохраняйте QWidget *. Некоторые функции имеют дополнительные требования; например, indexOf() и lastIndexOf() ожидают, что тип значения поддерживает operator==(). Эти требования отражены в описании функций. Like the other container classes, QList provides Java-style iterators (QListIterator and QMutableListIterator) and STL-style iterators (QList::const_iterator and QList::iterator). In practice, these are rarely used, because you can use indexes into the QList. QList is implemented in such a way that direct index-based access is just as fast as using iterators. QList does not support inserting, prepending, appending or replacing with references to its own values. Это может привести к прерыванию работы вашего приложения с сообщением об ошибке. To make QList as efficient as possible, its member functions don't validate their input before using it. Except for isEmpty(), member functions always assume the list is not empty. Member functions that take index values as parameters always assume their index value parameters are in the valid range. This means QList member functions can fail. If you define QT_NO_DEBUG when you compile, failures will not be detected. If you don't define QT_NO_DEBUG, failures will be detected using Q_ASSERT() or Q_ASSERT_X() with an appropriate message. To avoid failures when your list can be empty, call isEmpty() before calling other member functions. If you must pass an index value that might not be in the valid range, check that it is less than the value returned by size() but not less than 0. See also QListIterator, QMutableListIterator, QLinkedList, and QVector. Описание типов-членовtypedef QList::ConstIteratorQt-style synonym for QList::const_iterator. typedef QList::IteratorQt-style synonym for QList::iterator. typedef QList::const_pointerПсевдоним типа для const T *. Предоставлен для совместимости с STL. typedef QList::const_referenceTypedef for const T &. Предоставлен для совместимости с STL. typedef QList::difference_typeПсевдоним типа для ptrdiff_t. Предоставлен для совместимости с STL. typedef QList::pointerПсевдоним типа для T *. Предоставлен для совместимости с STL. typedef QList::referenceПсевдоним типа для T &. Предоставлен для совместимости с STL. typedef QList::size_typeПсевдоним типа для int. Предоставлен для совместимости с STL. typedef QList::value_typeПсевдоним типа для T. Предоставлен для совместимости с STL. Описание функций-членовQList::QList ()Constructs an empty list. QList::QList ( const QList<T> & other )Создаёт копию other. This operation takes constant time, because QList is implicitly shared. This makes returning a QList from a function very fast. Если экземпляр с разделением данных изменяется, то он будет скопирован (copy-on-write), и это потребует линейного времени. Смотрите также operator=(). QList::~QList ()Destroys the list. References to the values in the list and all iterators of this list become invalid. void QList::append ( const T & value )Inserts value at the end of the list. Пример: QList<QString> list; list.append("one"); list.append("two"); list.append("three"); // list: ["one", "two", "three"] This is the same as list.insert(size(), value). This operation is typically very fast (constant time), because QList preallocates extra space on both sides of its internal buffer to allow for fast growth at both ends of the list. Смотрите также operator<<(), prepend() и insert(). void QList::append ( const QList<T> & value )Это перегруженная функция. Appends the items of the value list to this list. Эта функция была введена в Qt 4.5. See also operator<<() and operator+=(). const T & QList::at ( int i ) constReturns the item at index position i in the list. i must be a valid index position in the list (i.e., 0 <= i < size()). This function is very fast (constant time). Смотрите также value() и operator[](). T & QList::back ()Эта функция обеспечивает совместимость с STL. Это эквивалентно last(). The list must not be empty. If the list can be empty, call isEmpty() before calling this function. const T & QList::back () constЭто перегруженная функция. iterator QList::begin ()Returns an STL-style iterator pointing to the first item in the list. Смотрите также constBegin() и end(). const_iterator QList::begin () constЭто перегруженная функция. void QList::clear ()Removes all items from the list. See also removeAll(). const_iterator QList::constBegin () constReturns a const STL-style iterator pointing to the first item in the list. Смотрите также begin() и constEnd(). const_iterator QList::constEnd () constВозвращает константный итератор в стиле STL, указывающий на воображаемый элемент после последнего элемента в списке. Смотрите также constBegin() и end(). bool QList::contains ( const T & value ) constReturns true if the list contains an occurrence of value; otherwise returns false. Эта функция требует, чтобы у типа значения существовала реализация operator==(). Смотрите также indexOf() и count(). int QList::count ( const T & value ) constReturns the number of occurrences of value in the list. Эта функция требует, чтобы у типа значения существовала реализация operator==(). Смотрите также contains() и indexOf(). int QList::count () constReturns the number of items in the list. This is effectively the same as size(). bool QList::empty () constЭта функция обеспечивает совместимость с STL. It is equivalent to isEmpty() and returns true if the list is empty. iterator QList::end ()Returns an STL-style iterator pointing to the imaginary item after the last item in the list. Смотрите также begin() и constEnd(). const_iterator QList::end () constЭто перегруженная функция. bool QList::endsWith ( const T & value ) constReturns true if this list is not empty and its last item is equal to value; otherwise returns false. Эта функция была введена в Qt 4.5. See also isEmpty() and contains(). iterator QList::erase ( iterator pos )Removes the item associated with the iterator pos from the list, and returns an iterator to the next item in the list (which may be end()). See also insert() and removeAt(). iterator QList::erase ( iterator begin, iterator end )Это перегруженная функция. Удаляет все элементы с begin до (но не включая) end. Возвращает итератор на тот же самый элемент, на который ссылался end перед вызовом. T & QList::first ()Returns a reference to the first item in the list. The list must not be empty. If the list can be empty, call isEmpty() before calling this function. Смотрите также last() и isEmpty(). const T & QList::first () constЭто перегруженная функция. QList<T> QList::fromSet ( const QSet<T> & set ) [static]Returns a QList object with the data contained in set. The order of the elements in the QList is undefined. Пример: QSet<int> set; set << 20 << 30 << 40 << ... << 70; QList<int> list = QList<int>::fromSet(set); qSort(list); See also fromVector(), toSet(), QSet::toList(), and qSort(). QList<T> QList::fromStdList ( const std::list<T> & list ) [static]Returns a QList object with the data contained in list. The order of the elements in the QList is the same as in list. Пример: std::list<double> stdlist; list.push_back(1.2); list.push_back(0.5); list.push_back(3.14); QList<double> list = QList<double>::fromStdList(stdlist); See also toStdList() and QVector::fromStdVector(). QList<T> QList::fromVector ( const QVector<T> & vector ) [static]Returns a QList object with the data contained in vector. Пример: QVector<double> vect; vect << 20.0 << 30.0 << 40.0 << 50.0; QList<double> list = QVector<T>::fromVector(vect); // list: [20.0, 30.0, 40.0, 50.0] See also fromSet(), toVector(), and QVector::toList(). T & QList::front ()Эта функция обеспечивает совместимость с STL. Это эквивалентно first(). The list must not be empty. If the list can be empty, call isEmpty() before calling this function. const T & QList::front () constЭто перегруженная функция. int QList::indexOf ( const T & value, int from = 0 ) constReturns the index position of the first occurrence of value in the list, searching forward from index position from. Возвращает -1, если нет соответствующих элементов. Пример: QList<QString> list; list << "A" << "B" << "C" << "B" << "A"; list.indexOf("B"); // returns 1 list.indexOf("B", 1); // returns 1 list.indexOf("B", 2); // returns 3 list.indexOf("X"); // returns -1 Эта функция требует, чтобы у типа значения существовала реализация operator==(). Note that QList uses 0-based indexes, just like C++ arrays. Negative indexes are not supported with the exception of the value mentioned above. Смотрите также lastIndexOf() и contains(). void QList::insert ( int i, const T & value )Inserts value at index position i in the list. If i is 0, the value is prepended to the list. If i is size(), the value is appended to the list. Пример: QList<QString> list; list << "alpha" << "beta" << "delta"; list.insert(2, "gamma"); // list: ["alpha", "beta", "gamma", "delta"] See also append(), prepend(), replace(), and removeAt(). iterator QList::insert ( iterator before, const T & value )Это перегруженная функция. Вставляет значение value перед элементом, на который указывает итератор before. Возвращает итератор, указывающий на вставленное значение. Note that the iterator passed to the function will be invalid after the call; the returned iterator should be used instead. bool QList::isEmpty () constВозвращает true, если список не содержит элементов; в противном случае возвращается false. Смотрите также size(). T & QList::last ()Returns a reference to the last item in the list. The list must not be empty. If the list can be empty, call isEmpty() before calling this function. Смотрите также first() и isEmpty(). const T & QList::last () constЭто перегруженная функция. int QList::lastIndexOf ( const T & value, int from = -1 ) constReturns the index position of the last occurrence of value in the list, searching backward from index position from. Если from равен -1 (по умолчанию), то поиск начинается с последнего элемента. Возвращает -1, если нет соответствующих элементов. Пример: QList<QString> list; list << "A" << "B" << "C" << "B" << "A"; list.lastIndexOf("B"); // returns 3 list.lastIndexOf("B", 3); // returns 3 list.lastIndexOf("B", 2); // returns 1 list.lastIndexOf("X"); // returns -1 Эта функция требует, чтобы у типа значения существовала реализация operator==(). Note that QList uses 0-based indexes, just like C++ arrays. Negative indexes are not supported with the exception of the value mentioned above. Смотрите также indexOf(). int QList::length () constThis function is identical to count(). Эта функция была введена в Qt 4.5. Смотрите также count(). QList<T> QList::mid ( int pos, int length = -1 ) constReturns a list whose elements are copied from this list, starting at position pos. If length is -1 (the default), all elements from pos are copied; otherwise length elements (or all remaining elements if there are less than length elements) are copied. void QList::move ( int from, int to )Moves the item at index position from to index position to. Пример: QList<QString> list; list << "A" << "B" << "C" << "D" << "E" << "F"; list.move(1, 4); // list: ["A", "C", "D", "E", "B", "F"] This is the same as insert(to, takeAt(from)).This function assumes that both from and to are at least 0 but less than size(). To avoid failure, test that both from and to are at least 0 and less than size(). See also swap(), insert(), and takeAt(). void QList::pop_back ()Эта функция обеспечивает совместимость с STL. It is equivalent to removeLast(). The list must not be empty. If the list can be empty, call isEmpty() before calling this function. void QList::pop_front ()Эта функция обеспечивает совместимость с STL. It is equivalent to removeFirst(). The list must not be empty. If the list can be empty, call isEmpty() before calling this function. void QList::prepend ( const T & value )Inserts value at the beginning of the list. Пример: QList<QString> list; list.prepend("one"); list.prepend("two"); list.prepend("three"); // list: ["three", "two", "one"] This is the same as list.insert(0, value). This operation is usually very fast (constant time), because QList preallocates extra space on both sides of its internal buffer to allow for fast growth at both ends of the list. Смотрите также append() и insert(). void QList::push_back ( const T & value )Эта функция обеспечивает совместимость с STL. It is equivalent to append(value). void QList::push_front ( const T & value )Эта функция обеспечивает совместимость с STL. It is equivalent to prepend(value). int QList::removeAll ( const T & value )Removes all occurrences of value in the list and returns the number of entries removed. Пример: QList<QString> list; list << "sun" << "cloud" << "sun" << "rain"; list.removeAll("sun"); // list: ["cloud", "rain"] Эта функция требует, чтобы у типа значения существовала реализация operator==(). See also removeOne(), removeAt(), takeAt(), and replace(). void QList::removeAt ( int i )Removes the item at index position i. i must be a valid index position in the list (i.e., 0 <= i < size()). See also takeAt(), removeFirst(), removeLast(), and removeOne(). void QList::removeFirst ()Removes the first item in the list. Calling this function is equivalent to calling removeAt(0). The list must not be empty. If the list can be empty, call isEmpty() before calling this function. See also removeAt() and takeFirst(). void QList::removeLast ()Removes the last item in the list. Calling this function is equivalent to calling removeAt(size() - 1). The list must not be empty. If the list can be empty, call isEmpty() before calling this function. See also removeAt() and takeLast(). bool QList::removeOne ( const T & value )Removes the first occurrence of value in the list and returns true on success; otherwise returns false. Пример: QList<QString> list; list << "sun" << "cloud" << "sun" << "rain"; list.removeOne("sun"); // list: ["cloud", ,"sun", "rain"] Эта функция требует, чтобы у типа значения существовала реализация operator==(). Эта функция была введена в Qt 4.4. See also removeAll(), removeAt(), takeAt(), and replace(). void QList::replace ( int i, const T & value )Заменяет элемент в позиции с индексом i на value. i must be a valid index position in the list (i.e., 0 <= i < size()). See also operator[]() and removeAt(). void QList::reserve ( int alloc )Reserve space for alloc elements. If alloc is smaller than the current size of the list, nothing will happen. Use this function to avoid repetetive reallocation of QList's internal data if you can predict how many elements will be appended. Note that the reservation applies only to the internal pointer array. Эта функция была введена в Qt 4.7. int QList::size () constReturns the number of items in the list. See also isEmpty() and count(). bool QList::startsWith ( const T & value ) constReturns true if this list is not empty and its first item is equal to value; otherwise returns false. Эта функция была введена в Qt 4.5. See also isEmpty() and contains(). void QList::swap ( int i, int j )Exchange the item at index position i with the item at index position j. This function assumes that both i and j are at least 0 but less than size(). To avoid failure, test that both i and j are at least 0 and less than size(). Пример: QList<QString> list; list << "A" << "B" << "C" << "D" << "E" << "F"; list.swap(1, 4); // list: ["A", "E", "C", "D", "B", "F"] See also move(). T QList::takeAt ( int i )Removes the item at index position i and returns it. i must be a valid index position in the list (i.e., 0 <= i < size()). If you don't use the return value, removeAt() is more efficient. See also removeAt(), takeFirst(), and takeLast(). T QList::takeFirst ()Removes the first item in the list and returns it. This is the same as takeAt(0). This function assumes the list is not empty. To avoid failure, call isEmpty() before calling this function. This operation takes constant time. If you don't use the return value, removeFirst() is more efficient. See also takeLast(), takeAt(), and removeFirst(). T QList::takeLast ()Removes the last item in the list and returns it. This is the same as takeAt(size() - 1). This function assumes the list is not empty. To avoid failure, call isEmpty() before calling this function. This operation takes constant time. If you don't use the return value, removeLast() is more efficient. See also takeFirst(), takeAt(), and removeLast(). QSet<T> QList::toSet () constReturns a QSet object with the data contained in this QList. Since QSet doesn't allow duplicates, the resulting QSet might be smaller than the original list was. Пример: QStringList list; list << "Julia" << "Mike" << "Mike" << "Julia" << "Julia"; QSet<QString> set = list.toSet(); set.contains("Julia"); // returns true set.contains("Mike"); // returns true set.size(); // returns 2 See also toVector(), fromSet(), and QSet::fromList(). std::list<T> QList::toStdList () constReturns a std::list object with the data contained in this QList. Пример: QList<double> list; list << 1.2 << 0.5 << 3.14; std::list<double> stdlist = list.toStdList(); See also fromStdList() and QVector::toStdVector(). QVector<T> QList::toVector () constReturns a QVector object with the data contained in this QList. Пример: QStringList list; list << "Sven" << "Kim" << "Ola"; QVector<QString> vect = list.toVector(); // vect: ["Sven", "Kim", "Ola"] See also toSet(), fromVector(), and QVector::fromList(). T QList::value ( int i ) constReturns the value at index position i in the list. Если индекс i находится за границами, то функция возвращает значение, создаваемое по умолчанию. If you are certain that the index is going to be within bounds, you can use at() instead, which is slightly faster. Смотрите также at() и operator[](). T QList::value ( int i, const T & defaultValue ) constЭто перегруженная функция. Если индекс i находится за границами, то функция возвращает defaultValue. bool QList::operator!= ( const QList<T> & other ) constReturns true if other is not equal to this list; otherwise returns false. Two lists are considered equal if they contain the same values in the same order. Эта функция требует, чтобы у типа значения существовала реализация operator==(). Смотрите также operator==(). QList<T> QList::operator+ ( const QList<T> & other ) constReturns a list that contains all the items in this list followed by all the items in the other list. Смотрите также operator+=(). QList<T> & QList::operator+= ( const QList<T> & other )Appends the items of the other list to this list and returns a reference to this list. Смотрите также operator+() и append(). QList<T> & QList::operator+= ( const T & value )Это перегруженная функция. Appends value to the list. Смотрите также append() и operator<<(). QList<T> & QList::operator<< ( const QList<T> & other )Appends the items of the other list to this list and returns a reference to this list. See also operator+=() and append(). QList<T> & QList::operator<< ( const T & value )Это перегруженная функция. Appends value to the list. QList<T> & QList::operator= ( const QList<T> & other )Assigns other to this list and returns a reference to this list. bool QList::operator== ( const QList<T> & other ) constReturns true if other is equal to this list; otherwise returns false. Two lists are considered equal if they contain the same values in the same order. Эта функция требует, чтобы у типа значения существовала реализация operator==(). Смотрите также operator!=(). T & QList::operator[] ( int i )Возвращает элемент в позиции с индексом i как изменяемую ссылку. i must be a valid index position in the list (i.e., 0 <= i < size()). This function is very fast (constant time). Смотрите также at() и value(). const T & QList::operator[] ( int i ) constЭто перегруженная функция. Same as at(). Связанные нечлены классаQDataStream & operator<< ( QDataStream & out, const QList<T> & list )Writes the list list to stream out. Эта функция требует, чтобы у типа значения была реализация operator<<(). Смотрите также Формат операторов QDataStream. QDataStream & operator>> ( QDataStream & in, QList<T> & list )Reads a list from stream in into list. Эта функция требует, чтобы у типа значения была реализация operator>>(). Смотрите также Формат операторов QDataStream. |
Попытка перевода Qt документации. Если есть желание присоединиться, или если есть замечания или пожелания, то заходите на форум: Перевод Qt документации на русский язык... Люди внесшие вклад в перевод: Команда переводчиков |