Movatterモバイル変換


[0]ホーム

URL:


We bake cookies in your browser for a better experience. Using this site means that you consent.Read More

Menu

Qt Documentation

QVector Class

TheQVector class is a template class that provides a dynamic array.More...

Header:#include <QVector>
Inherited By:

Q3ValueVector,QPolygon,QPolygonF,QStack, andQXmlStreamAttributes

Note: All functions in this class arereentrant.

Public Types

typedefConstIterator
typedefIterator
typedefconst_iterator
typedefconst_pointer
typedefconst_reference
typedefdifference_type
typedefiterator
typedefpointer
typedefreference
typedefsize_type
typedefvalue_type

Public Functions

QVector()
QVector(int size)
QVector(int size, const T & value)
QVector(const QVector<T> & other)
QVector(std::initializer_list<T> args)
~QVector()
voidappend(const T & value)
const T &at(int i) const
referenceback()
const_referenceback() const
iteratorbegin()
const_iteratorbegin() const
intcapacity() const
voidclear()
const_iteratorconstBegin() const
const T *constData() const
const_iteratorconstEnd() const
boolcontains(const T & value) const
intcount(const T & value) const
intcount() const
T *data()
const T *data() const
boolempty() const
iteratorend()
const_iteratorend() const
boolendsWith(const T & value) const
iteratorerase(iterator pos)
iteratorerase(iterator begin, iterator end)
QVector<T> &fill(const T & value, int size = -1)
T &first()
const T &first() const
T &front()
const_referencefront() const
intindexOf(const T & value, int from = 0) const
voidinsert(int i, const T & value)
iteratorinsert(iterator before, int count, const T & value)
voidinsert(int i, int count, const T & value)
iteratorinsert(iterator before, const T & value)
boolisEmpty() const
T &last()
const T &last() const
intlastIndexOf(const T & value, int from = -1) const
QVector<T>mid(int pos, int length = -1) const
voidpop_back()
voidpop_front()
voidprepend(const T & value)
voidpush_back(const T & value)
voidpush_front(const T & value)
voidremove(int i)
voidremove(int i, int count)
voidreplace(int i, const T & value)
voidreserve(int size)
voidresize(int size)
intsize() const
voidsqueeze()
boolstartsWith(const T & value) const
voidswap(QVector<T> & other)
QList<T>toList() const
std::vector<T>toStdVector() const
Tvalue(int i) const
Tvalue(int i, const T & defaultValue) const
booloperator!=(const QVector<T> & other) const
QVector<T>operator+(const QVector<T> & other) const
QVector<T> &operator+=(const QVector<T> & other)
QVector<T> &operator+=(const T & value)
QVector<T> &operator<<(const T & value)
QVector<T> &operator<<(const QVector<T> & other)
QVector<T> &operator=(const QVector<T> & other)
QVector<T>operator=(QVector<T> && other)
booloperator==(const QVector<T> & other) const
T &operator[](int i)
const T &operator[](int i) const

Static Public Members

QVector<T>fromList(const QList<T> & list)
QVector<T>fromStdVector(const std::vector<T> & vector)

Related Non-Members

QDataStream &operator<<(QDataStream & out, const QVector<T> & vector)
QDataStream &operator>>(QDataStream & in, QVector<T> & vector)

Detailed Description

TheQVector class is a template class that provides a dynamic array.

QVector<T> is one of Qt's genericcontainer classes. It stores its items in adjacent memory locations and provides fast index-based access.

QList<T>,QLinkedList<T>, andQVarLengthArray<T> provide similar functionality. Here's an overview:

  • For most purposes,QList is the right class to use. Operations likeprepend() andinsert() are usually faster than withQVector because of the wayQList stores its items in memory (seeAlgorithmic Complexity for details), and its index-based API is more convenient thanQLinkedList's iterator-based API. It also expands to less code in your executable.
  • If you need a real linked list, with guarantees ofconstant time insertions in the middle of the list and iterators to items rather than indexes, useQLinkedList.
  • If you want the items to occupy adjacent memory positions, or if your items are larger than a pointer and you want to avoid the overhead of allocating them on the heap individually at insertion time, then useQVector.
  • If you want a low-level variable-size array,QVarLengthArray may be sufficient.

Here's an example of aQVector that stores integers and aQVector that storesQString values:

QVector<int> integerVector;QVector<QString> stringVector;

QVector stores a vector (or array) of items. Typically, vectors are created with an initial size. For example, the following code constructs aQVector with 200 elements:

QVector<QString> vector(200);

The elements are automatically initialized with a default-constructed value. If you want to initialize the vector with a different value, pass that value as the second argument to the constructor:

QVector<QString> vector(200,"Pass");

You can also callfill() at any time to fill the vector with a value.

QVector uses 0-based indexes, just like C++ arrays. To access the item at a particular index position, you can use operator[](). On non-const vectors, operator[]() returns a reference to the item that can be used on the left side of an assignment:

if (vector[0]=="Liz")    vector[0]="Elizabeth";

For read-only access, an alternative syntax is to useat():

for (int i=0; i< vector.size();++i) {if (vector.at(i)=="Alfonso")        cout<<"Found Alfonso at position "<< i<< endl;}

at() can be faster than operator[](), because it never causes adeep copy to occur.

Another way to access the data stored in aQVector is to calldata(). The function returns a pointer to the first item in the vector. You can use the pointer to directly access and modify the elements stored in the vector. The pointer is also useful if you need to pass aQVector to a function that accepts a plain C++ array.

If you want to find all occurrences of a particular value in a vector, useindexOf() orlastIndexOf(). The former searches forward starting from a given index position, the latter searches backward. Both return the index of the matching item if they found one; otherwise, they return -1. For example:

int i= vector.indexOf("Harumi");if (i!=-1)    cout<<"First occurrence of Harumi is at position "<< i<< endl;

If you simply want to check whether a vector contains a particular value, usecontains(). If you want to find out how many times a particular value occurs in the vector, usecount().

QVector provides these basic functions to add, move, and remove items:insert(),replace(),remove(),prepend(),append(). With the exception ofappend() andreplace(), these functions can be slow (linear time) for large vectors, because they require moving many items in the vector by one position in memory. If you want a container class that provides fast insertion/removal in the middle, useQList orQLinkedList instead.

Unlike plain C++ arrays, QVectors can be resized at any time by callingresize(). If the new size is larger than the old size,QVector might need to reallocate the whole vector.QVector tries to reduce the number of reallocations by preallocating up to twice as much memory as the actual data needs.

If you know in advance approximately how many items theQVector will contain, you can callreserve(), askingQVector to preallocate a certain amount of memory. You can also callcapacity() to find out how much memoryQVector actually allocated.

Note that using non-const operators and functions can causeQVector to do a deep copy of the data. This is due toimplicit sharing.

QVector's value type must be anassignable data type. This covers most data types that are commonly used, but the compiler won't let you, for example, store aQWidget as a value; instead, store aQWidget *. A few functions have additional requirements; for example,indexOf() andlastIndexOf() expect the value type to supportoperator==(). These requirements are documented on a per-function basis.

Like the other container classes,QVector providesJava-style iterators (QVectorIterator andQMutableVectorIterator) andSTL-style iterators (QVector::const_iterator andQVector::iterator). In practice, these are rarely used, because you can use indexes into theQVector.

In addition toQVector, Qt also providesQVarLengthArray, a very low-level class with little functionality that is optimized for speed.

QVector doesnot support inserting, prepending, appending or replacing with references to its own values. Doing so will cause your application to abort with an error message.

See alsoQVectorIterator,QMutableVectorIterator,QList, andQLinkedList.

Member Type Documentation

typedef QVector::ConstIterator

Qt-style synonym forQVector::const_iterator.

typedef QVector::Iterator

Qt-style synonym forQVector::iterator.

typedef QVector::const_iterator

The QVector::const_iterator typedef provides an STL-style const iterator forQVector andQStack.

QVector provides bothSTL-style iterators andJava-style iterators. The STL-style const iterator is simply a typedef for "const T *" (pointer to const T).

See alsoQVector::constBegin(),QVector::constEnd(),QVector::iterator, andQVectorIterator.

typedef QVector::const_pointer

Typedef for const T *. Provided for STL compatibility.

typedef QVector::const_reference

Typedef for T &. Provided for STL compatibility.

typedef QVector::difference_type

Typedef for ptrdiff_t. Provided for STL compatibility.

typedef QVector::iterator

The QVector::iterator typedef provides an STL-style non-const iterator forQVector andQStack.

QVector provides bothSTL-style iterators andJava-style iterators. The STL-style non-const iterator is simply a typedef for "T *" (pointer to T).

See alsoQVector::begin(),QVector::end(),QVector::const_iterator, andQMutableVectorIterator.

typedef QVector::pointer

Typedef for T *. Provided for STL compatibility.

typedef QVector::reference

Typedef for T &. Provided for STL compatibility.

typedef QVector::size_type

Typedef for int. Provided for STL compatibility.

typedef QVector::value_type

Typedef for T. Provided for STL compatibility.

Member Function Documentation

QVector::QVector()

Constructs an empty vector.

See alsoresize().

QVector::QVector(int size)

Constructs a vector with an initial size ofsize elements.

The elements are initialized with a default-constructed value.

See alsoresize().

QVector::QVector(int size, constT & value)

Constructs a vector with an initial size ofsize elements. Each element is initialized withvalue.

See alsoresize() andfill().

QVector::QVector(constQVector<T> & other)

Constructs a copy ofother.

This operation takesconstant time, becauseQVector isimplicitly shared. This makes returning aQVector from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and that takeslinear time.

See alsooperator=().

QVector::QVector(std::initializer_list<T> args)

Construct a vector from the std::initilizer_list given byargs.

This constructor is only enabled if the compiler supports C++0x

This function was introduced in Qt 4.8.

QVector::~QVector()

Destroys the vector.

void QVector::append(constT & value)

Insertsvalue at the end of the vector.

Example:

QVector<QString> vector(0);vector.append("one");vector.append("two");vector.append("three");// vector: ["one", "two", "three"]

This is the same as calling resize(size() + 1) and assigningvalue to the new last element in the vector.

This operation is relatively fast, becauseQVector typically allocates more memory than necessary, so it can grow without reallocating the entire vector each time.

See alsooperator<<(),prepend(), andinsert().

constT & QVector::at(int i) const

Returns the item at index positioni in the vector.

i must be a valid index position in the vector (i.e., 0 <=i <size()).

See alsovalue() andoperator[]().

reference QVector::back()

This function is provided for STL compatibility. It is equivalent tolast().

const_reference QVector::back() const

This is an overloaded function.

iterator QVector::begin()

Returns an STL-style iterator pointing to the first item in the vector.

See alsoconstBegin() andend().

const_iterator QVector::begin() const

This is an overloaded function.

int QVector::capacity() const

Returns the maximum number of items that can be stored in the vector without forcing a reallocation.

The sole purpose of this function is to provide a means of fine tuningQVector's memory usage. In general, you will rarely ever need to call this function. If you want to know how many items are in the vector, callsize().

See alsoreserve() andsqueeze().

void QVector::clear()

Removes all the elements from the vector and releases the memory used by the vector.

const_iterator QVector::constBegin() const

Returns a const STL-style iterator pointing to the first item in the vector.

See alsobegin() andconstEnd().

constT * QVector::constData() const

Returns a const pointer to the data stored in the vector. The pointer can be used to access the items in the vector. The pointer remains valid as long as the vector isn't reallocated.

This function is mostly useful to pass a vector to a function that accepts a plain C++ array.

See alsodata() andoperator[]().

const_iterator QVector::constEnd() const

Returns a const STL-style iterator pointing to the imaginary item after the last item in the vector.

See alsoconstBegin() andend().

bool QVector::contains(constT & value) const

Returns true if the vector contains an occurrence ofvalue; otherwise returns false.

This function requires the value type to have an implementation ofoperator==().

See alsoindexOf() andcount().

int QVector::count(constT & value) const

Returns the number of occurrences ofvalue in the vector.

This function requires the value type to have an implementation ofoperator==().

See alsocontains() andindexOf().

int QVector::count() const

This is an overloaded function.

Same assize().

T * QVector::data()

Returns a pointer to the data stored in the vector. The pointer can be used to access and modify the items in the vector.

Example:

QVector<int> vector(10);int*data= vector.data();for (int i=0; i<10;++i)    data[i]=2* i;

The pointer remains valid as long as the vector isn't reallocated.

This function is mostly useful to pass a vector to a function that accepts a plain C++ array.

See alsoconstData() andoperator[]().

constT * QVector::data() const

This is an overloaded function.

bool QVector::empty() const

This function is provided for STL compatibility. It is equivalent toisEmpty(), returning true if the vector is empty; otherwise returns false.

iterator QVector::end()

Returns an STL-style iterator pointing to the imaginary item after the last item in the vector.

See alsobegin() andconstEnd().

const_iterator QVector::end() const

This is an overloaded function.

bool QVector::endsWith(constT & value) const

Returns true if this vector is not empty and its last item is equal tovalue; otherwise returns false.

This function was introduced in Qt 4.5.

See alsoisEmpty() andlast().

iterator QVector::erase(iterator pos)

Removes the item pointed to by the iteratorpos from the vector, and returns an iterator to the next item in the vector (which may beend()).

See alsoinsert() andremove().

iterator QVector::erase(iterator begin,iterator end)

This is an overloaded function.

Removes all the items frombegin up to (but not including)end. Returns an iterator to the same item thatend referred to before the call.

QVector<T> & QVector::fill(constT & value,int size = -1)

Assignsvalue to all items in the vector. Ifsize is different from -1 (the default), the vector is resized to sizesize beforehand.

Example:

QVector<QString> vector(3);vector.fill("Yes");// vector: ["Yes", "Yes", "Yes"]vector.fill("oh",5);// vector: ["oh", "oh", "oh", "oh", "oh"]

See alsoresize().

T & QVector::first()

Returns a reference to the first item in the vector. This function assumes that the vector isn't empty.

See alsolast() andisEmpty().

constT & QVector::first() const

This is an overloaded function.

[static]QVector<T> QVector::fromList(constQList<T> & list)

Returns aQVector object with the data contained inlist.

Example:

QStringList list;list<<"Sven"<<"Kim"<<"Ola";QVector<QString> vect=QVector<QString>::fromList(list);// vect: ["Sven", "Kim", "Ola"]

See alsotoList() andQList::toVector().

[static]QVector<T> QVector::fromStdVector(conststd::vector<T> & vector)

Returns aQVector object with the data contained invector. The order of the elements in theQVector is the same as invector.

Example:

std::vector<double> stdvector;vector.push_back(1.2);vector.push_back(0.5);vector.push_back(3.14);QVector<double> vector=QVector<double>::fromStdVector(stdvector);

See alsotoStdVector() andQList::fromStdList().

T & QVector::front()

This function is provided for STL compatibility. It is equivalent tofirst().

const_reference QVector::front() const

This is an overloaded function.

int QVector::indexOf(constT & value,int from = 0) const

Returns the index position of the first occurrence ofvalue in the vector, searching forward from index positionfrom. Returns -1 if no item matched.

Example:

QVector<QString> vector;vector<<"A"<<"B"<<"C"<<"B"<<"A";vector.indexOf("B");// returns 1vector.indexOf("B",1);// returns 1vector.indexOf("B",2);// returns 3vector.indexOf("X");// returns -1

This function requires the value type to have an implementation ofoperator==().

See alsolastIndexOf() andcontains().

void QVector::insert(int i, constT & value)

Insertsvalue at index positioni in the vector. Ifi is 0, the value is prepended to the vector. Ifi issize(), the value is appended to the vector.

Example:

QVector<QString> vector;vector<<"alpha"<<"beta"<<"delta";vector.insert(2,"gamma");// vector: ["alpha", "beta", "gamma", "delta"]

For large vectors, this operation can be slow (linear time), because it requires moving all the items at indexesi and above by one position further in memory. If you want a container class that provides a fast insert() function, useQLinkedList instead.

See alsoappend(),prepend(), andremove().

iterator QVector::insert(iterator before,int count, constT & value)

Insertscount copies ofvalue in front of the item pointed to by the iteratorbefore. Returns an iterator pointing at the first of the inserted items.

void QVector::insert(int i,int count, constT & value)

This is an overloaded function.

Insertscount copies ofvalue at index positioni in the vector.

Example:

QVector<double> vector;vector<<2.718<<1.442<<0.4342;vector.insert(1,3,9.9);// vector: [2.718, 9.9, 9.9, 9.9, 1.442, 0.4342]

iterator QVector::insert(iterator before, constT & value)

This is an overloaded function.

Insertsvalue in front of the item pointed to by the iteratorbefore. Returns an iterator pointing at the inserted item.

bool QVector::isEmpty() const

Returns true if the vector has size 0; otherwise returns false.

See alsosize() andresize().

T & QVector::last()

Returns a reference to the last item in the vector. This function assumes that the vector isn't empty.

See alsofirst() andisEmpty().

constT & QVector::last() const

This is an overloaded function.

int QVector::lastIndexOf(constT & value,int from = -1) const

Returns the index position of the last occurrence of the valuevalue in the vector, searching backward from index positionfrom. Iffrom is -1 (the default), the search starts at the last item. Returns -1 if no item matched.

Example:

QList<QString> vector;vector<<"A"<<"B"<<"C"<<"B"<<"A";vector.lastIndexOf("B");// returns 3vector.lastIndexOf("B",3);// returns 3vector.lastIndexOf("B",2);// returns 1vector.lastIndexOf("X");// returns -1

This function requires the value type to have an implementation ofoperator==().

See alsoindexOf().

QVector<T> QVector::mid(int pos,int length = -1) const

Returns a vector whose elements are copied from this vector, starting at positionpos. Iflength is -1 (the default), all elements afterpos are copied; otherwiselength elements (or all remaining elements if there are less thanlength elements) are copied.

void QVector::pop_back()

This function is provided for STL compatibility. It is equivalent to erase(end() - 1).

void QVector::pop_front()

This function is provided for STL compatibility. It is equivalent to erase(begin()).

void QVector::prepend(constT & value)

Insertsvalue at the beginning of the vector.

Example:

QVector<QString> vector;vector.prepend("one");vector.prepend("two");vector.prepend("three");// vector: ["three", "two", "one"]

This is the same as vector.insert(0,value).

For large vectors, this operation can be slow (linear time), because it requires moving all the items in the vector by one position further in memory. If you want a container class that provides a fast prepend() function, useQList orQLinkedList instead.

See alsoappend() andinsert().

void QVector::push_back(constT & value)

This function is provided for STL compatibility. It is equivalent to append(value).

void QVector::push_front(constT & value)

This function is provided for STL compatibility. It is equivalent to prepend(value).

void QVector::remove(int i)

This is an overloaded function.

Removes the element at index positioni.

See alsoinsert(),replace(), andfill().

void QVector::remove(int i,int count)

This is an overloaded function.

Removescount elements from the middle of the vector, starting at index positioni.

See alsoinsert(),replace(), andfill().

void QVector::replace(int i, constT & value)

Replaces the item at index positioni withvalue.

i must be a valid index position in the vector (i.e., 0 <=i <size()).

See alsooperator[]() andremove().

void QVector::reserve(int size)

Attempts to allocate memory for at leastsize elements. If you know in advance how large the vector will be, you can call this function, and if you callresize() often you are likely to get better performance. Ifsize is an underestimate, the worst that will happen is that theQVector will be a bit slower.

The sole purpose of this function is to provide a means of fine tuningQVector's memory usage. In general, you will rarely ever need to call this function. If you want to change the size of the vector, callresize().

See alsosqueeze() andcapacity().

void QVector::resize(int size)

Sets the size of the vector tosize. Ifsize is greater than the current size, elements are added to the end; the new elements are initialized with a default-constructed value. Ifsize is less than the current size, elements are removed from the end.

See alsosize().

int QVector::size() const

Returns the number of items in the vector.

See alsoisEmpty() andresize().

void QVector::squeeze()

Releases any memory not required to store the items.

The sole purpose of this function is to provide a means of fine tuningQVector's memory usage. In general, you will rarely ever need to call this function.

See alsoreserve() andcapacity().

bool QVector::startsWith(constT & value) const

Returns true if this vector is not empty and its first item is equal tovalue; otherwise returns false.

This function was introduced in Qt 4.5.

See alsoisEmpty() andfirst().

void QVector::swap(QVector<T> & other)

Swaps vectorother with this vector. This operation is very fast and never fails.

This function was introduced in Qt 4.8.

QList<T> QVector::toList() const

Returns aQList object with the data contained in thisQVector.

Example:

QVector<QString> vect;vect<<"red"<<"green"<<"blue"<<"black";QList<QString> list= vect.toList();// list: ["red", "green", "blue", "black"]

See alsofromList() andQList::fromVector().

std::vector<T> QVector::toStdVector() const

Returns a std::vector object with the data contained in thisQVector. Example:

QVector<double> vector;vector<<1.2<<0.5<<3.14;std::vector<double> stdvector= vector.toStdVector();

See alsofromStdVector() andQList::toStdList().

T QVector::value(int i) const

Returns the value at index positioni in the vector.

If the indexi is out of bounds, the function returns a default-constructed value. If you are certain thati is within bounds, you can useat() instead, which is slightly faster.

See alsoat() andoperator[]().

T QVector::value(int i, constT & defaultValue) const

This is an overloaded function.

If the indexi is out of bounds, the function returnsdefaultValue.

bool QVector::operator!=(constQVector<T> & other) const

Returns true ifother is not equal to this vector; otherwise returns false.

Two vectors are considered equal if they contain the same values in the same order.

This function requires the value type to have an implementation ofoperator==().

See alsooperator==().

QVector<T> QVector::operator+(constQVector<T> & other) const

Returns a vector that contains all the items in this vector followed by all the items in theother vector.

See alsooperator+=().

QVector<T> & QVector::operator+=(constQVector<T> & other)

Appends the items of theother vector to this vector and returns a reference to this vector.

See alsooperator+() andappend().

QVector<T> & QVector::operator+=(constT & value)

This is an overloaded function.

Appendsvalue to the vector.

See alsoappend() andoperator<<().

QVector<T> & QVector::operator<<(constT & value)

Appendsvalue to the vector and returns a reference to this vector.

See alsoappend() andoperator+=().

QVector<T> & QVector::operator<<(constQVector<T> & other)

Appendsother to the vector and returns a reference to the vector.

QVector<T> & QVector::operator=(constQVector<T> & other)

Assignsother to this vector and returns a reference to this vector.

QVector<T> QVector::operator=(QVector<T> && other)

bool QVector::operator==(constQVector<T> & other) const

Returns true ifother is equal to this vector; otherwise returns false.

Two vectors are considered equal if they contain the same values in the same order.

This function requires the value type to have an implementation ofoperator==().

See alsooperator!=().

T & QVector::operator[](int i)

Returns the item at index positioni as a modifiable reference.

i must be a valid index position in the vector (i.e., 0 <=i <size()).

Note that using non-const operators can causeQVector to do a deep copy.

See alsoat() andvalue().

constT & QVector::operator[](int i) const

This is an overloaded function.

Same as at(i).

Related Non-Members

QDataStream &operator<<(QDataStream & out, constQVector<T> & vector)

Writes the vectorvector to streamout.

This function requires the value type to implementoperator<<().

See alsoFormat of the QDataStream operators.

QDataStream &operator>>(QDataStream & in,QVector<T> & vector)

Reads a vector from streamin intovector.

This function requires the value type to implementoperator>>().

See alsoFormat of the QDataStream operators.

© 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of theGNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.


[8]ページ先頭

©2009-2025 Movatter.jp