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

# QValueVector Class Reference

The QValueVector class is a value-based template class that provides a dynamic array. More...

`#include <qvaluevector.h>`

List of all member functions.

## Public Members

- typedef T value_type
- typedef value_type * pointer
- typedef const value_type * const_pointer
- typedef value_type * iterator
- typedef const value_type * const_iterator
- typedef value_type & reference
- typedef const value_type & const_reference
- typedef size_t size_type
- typedef ptrdiff_t difference_type
- QValueVector ()
- QValueVector ( const QValueVector<T> & v )
- QValueVector ( size_type n, const T & val = T ( ) )
- QValueVector ( std::vector<T> & v )
- ~QValueVector ()
- QValueVector<T> & operator= ( const QValueVector<T> & v )
- QValueVector<T> & operator= ( const std::vector<T> & v )
- size_type size () const
- bool empty () const
- size_type capacity () const
- iterator begin ()
- const_iterator begin () const
- iterator end ()
- const_iterator end () const
- reference at ( size_type i, bool * ok = 0 )
- const_reference at ( size_type i, bool * ok = 0 ) const
- reference operator[] ( size_type i )
- const_reference operator[] ( size_type i ) const
- reference front ()
- const_reference front () const
- reference back ()
- const_reference back () const
- void push_back ( const T & x )
- void pop_back ()
- iterator insert ( iterator pos, const T & x )
- iterator insert ( iterator pos, size_type n, const T & x )
- void reserve ( size_type n )
- void resize ( size_type n, const T & val = T ( ) )
- void clear ()
- iterator erase ( iterator pos )
- iterator erase ( iterator first, iterator last )
- bool operator== ( const QValueVector<T> & x )

## Protected Members

- void detach ()

## Detailed Description

The QValueVector class is a value-based template class that provides a dynamic array.

QValueVector is a Qt implementation of an STL-like vector container. It can be used in your application if the standard `vector` is not available. QValueVector is part of the Qt Template Library.

QValueVector<T> defines a template instance to create a vector of values that all have the class T. Please note that QValueVector does not store pointers to the members of the vector; it holds a copy of every member. QValueVector is said to be value based; in contrast, QPtrList and QDict are pointer based.

QValueVector contains and manages a collection of objects of type T and provides random access iterators that allow the contained objects to be addressed. QValueVector owns the contained elements. For more relaxed ownership semantics, see QPtrCollection and friends which are pointer-based containers.

QValueVector provides good performance if you append or remove elements from the end of the vector. If you insert or remove elements from anywhere but the end, performance is very bad. The reason for this is that elements will need to be copied into new positions.

Some classes cannot be used within a QValueVector - for example, all classes derived from QObject and thus all classes that implement widgets. Only values can be used in a QValueVector. To qualify as a value the class must provide:

- A copy constructor
- An assignment operator
- A default constructor, i.e., a constructor that does not take any arguments.

Note that C++ defaults to field-by-field assignment operators and copy constructors if no explicit version is supplied. In many cases this is sufficient.

QValueVector uses an STL-like syntax to manipulate and address the objects it contains. See this document for more information.

Example:

        #include <qvaluevector.h>
        #include <qstring.h>
        #include <stdio.h>

        class Employee
        {
        public:
            Employee(): s(0) {}
            Employee( const QString& name, int salary )
                : n(name), s(salary)
            {}

            QString     name()   const              { return n; }
            int         salary() const              { return s; }
            void        setSalary( int salary )     { s = salary; }
        private:
            QString     n;
            int         s;
        };

        int main()
        {
            typedef QValueVector<Employee> EmployeeVector;
            EmployeeVector vec( 4 );        // vector of 4 Employees

            vec[0] = Employee("Bill", 50000);
            vec[1] = Employee("Steve",80000);
            vec[2] = Employee("Ron",  60000);

            Employee joe( "Joe", 50000 );
            vec.push_back( joe );
            joe.setSalary( 4000 );

            EmployeeVector::iterator it;
            for( it = vec.begin(); it != vec.end(); ++it )
                printf( "%s earns %d\n", (*it).name().latin1(), (*it).salary() );

            return 0;
        }

Program output:

            Bill earns 50000
            Steve earns 80000
            Ron earns 60000
            Joe earns 50000

As you can see, the latest changes to Joe's salary did not affect the value in the vector because the vector created a copy of Joe's entry.

There are several ways to find items in the vector. The begin() and end() functions return iterators to the beginning and end of the vector. The advantage of getting an iterator is that you can now move forward or backward from this position by incrementing/decrementing the iterator. The iterator returned by end() points to the element which is one past the last element in the container. The past-the-end iterator is still associated with the vector it belongs to, however it is not dereferenceable; operator*() will not return a well-defined value. If the vector is empty(), the iterator returned by begin() will equal the iterator returned by end().

The fastest way to access an element of a vector is by using operator[]. This function provides random access and will return a reference to the element located at the specified index. Thus, you can access every element directly, in constant time, providing you know the location of the element. It is undefined to access an element that does not exist (your application will probably crash). For example:

      QValueVector<int> vec1;  // an empty vector
      vec1[10] = 4;  // WARNING: undefined, probably a crash

      QValueVector<QString> vec2(25); // initialize with 25 elements
      vec2[10] = "Dave";  // OK

Whenever inserting, removing or referencing elements in a vector, always make sure you are referring to valid positions. For example:

      void func( QValueVector<int>& vec )
      {
          if ( vec.size() > 10 ) {
              vec[9] = 99; // OK
          }
      };

The iterators provided by vector are random access iterators, therefore you can use them with many generic algorithms, for example, algorithms provided by the STL or the QTL.

Another way to find an element in the vector is by using the std::find() or qFind() algorithms. For example:

      QValueVector<int> vec;
      ...
      QValueVector<int>::const_iterator it = qFind( vec.begin(), vec.end(), 3 );
      if ( it != vector.end() )
          // 'it' points to the found element

It is safe to have multiple iterators on the vector at the same time. Since QValueVector manages memory dynamically, all iterators can become invalid if a memory reallocation occurs. For example, if some member of the vector is removed, iterators that point to the removed element and to all following elements become invalidated. Inserting into the middle of the vector will invalidate all iterators. For convenience, the function back() returns a reference to the last element in the vector, and front() one for the first. If the vector is empty(), both back() and front() have undefined behavior (your application will crash or do unpredictable things). Use back() and front() with caution, for example:

      QValueVector<int> vec( 3 );
      vec.push_back( 1 );
      vec.push_back( 2 );
      vec.push_back( 3 );
      ...
      if ( !vec.empty() ) {
          // OK: modify the first element
          int& i = vec.front();
          i = 18;
      }
      ...
      QValueVector<double> dvec;
      double d = dvec.back(); // undefined behavior

Because QValueVector manages memory dynamically, it is recommended to contruct a vector with an initial size. Inserting and removing elements happens fastest when:

- Inserting or removing elements happens at the end() of the vector
- The vector does not need to allocate additional memory

By creating a QValueVector with a sufficiently large initial size, there will be less memory allocations. Do not use an initial size that is too big, since it will still take time to construct all the empty entries, and the extra space may be wasted if it is never used.

Because QValueVector is value-based there is no need to be careful about deleting elements in the vector. The vector holds its own copies and will free them if the corresponding member or the vector itself is deleted. You can force the vector to free all of its items with clear().

QValueVector is shared implicitly, which means it can be copied in constant time. If multiple QValueVector instances share the same data and one needs to modify its contents, this modifying instance makes a copy and modifies its private copy; it thus does not affect the other instances. This is often called "copy on write". If a QValueVector is being used in a multi-threaded program, you must protect all access to the vector. See QMutex.

There are several ways to insert elements into the vector. The push_back() function insert elements into the end of the vector. The insert() can be used to add elements at specific positions within the vector (normally, inserting elements at the end() of the vector is fastest).

Items can be also be removed from the vector in several ways. There are several variants of the erase() function which removes a specific element, or range of elements, from the vector.

Vectors can be also sorted with various STL algorithms , or it can be sorted using the Qt Template Library. For example with qBubbleSort():

Example:

        QValueVector<int> v( 4 );
        v.push_back( 5 );
        v.push_back( 8 );
        v.push_back( 3 );
        v.push_back( 4 );
        qBubbleSort( v );

QValueVector stores its elements in contiguous memory. This means that you can use a QValueVector in any situation that requires an array.

See also Qt Template Library Classes, Implicitly and Explicitly Shared Classes and Non-GUI Classes.

## Member Type Documentation

### QValueVector::const_iterator

The vector's const iterator type.

### QValueVector::const_pointer

The const pointer to T type.

### QValueVector::const_reference

The const reference to T type.

### QValueVector::difference_type

A signed integral type used to represent the distance between two iterators.

### QValueVector::iterator

The vector's iterator type.

### QValueVector::pointer

The pointer to T type.

### QValueVector::reference

The reference to T type.

### QValueVector::size_type

An unsigned integral type, used to represent various sizes.

### QValueVector::value_type

The type of the object stored in the vector.

## Member Function Documentation

### QValueVector::QValueVector ()

Constructs an empty vector without any elements. To create a vector which reserves an initial amount of space for elements, use `QValueVector(size_type n)`.

### QValueVector::QValueVector ( const QValueVector<T> & v )

Constructs a copy of v.

This operation costs O(1) time because QValueVector is shared implicitly.

The first modification to the vector does however take O(n) time.

### QValueVector::QValueVector ( size_type n, const T & val = T ( ) )

Constructs a vector with an initial size of n elements. Each element is initialized with the value of val.

### QValueVector::QValueVector ( std::vector<T> & v )

Constructs a copy of v.

This operation costs O(1) time because QValueVector is shared implicitly.

The first modification to the vector does however take O(n) time.

### QValueVector::~QValueVector ()

Destroys the vector, destroying all elements and freeing the memory. References to the values in the vector and all iterators of this vector become invalidated. Note that it is impossible for an iterator to check whether or not it is valid - QValueVector is tuned for performance, not error checking.

### reference QValueVector::at ( size_type i, bool * ok = 0 )

Returns a reference to the element with index i. If ok is non-null, and the index i is out of range, `*<em>ok</em>` is set to FALSE and the returned reference is undefined. If the index i is within the range of the vector, and ok is non-null, `*<em>ok</em>` is set to TRUE and the returned reference is well defined.

### const_reference QValueVector::at ( size_type i, bool * ok = 0 ) const

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

Returns a const reference to the element with index i. If ok is non-null, and the index i is out of range, `*<em>ok</em>` is set to FALSE and the returned reference is undefined. If the index i is within the range of the vector, and ok is non-null, `*<em>ok</em>` is set to TRUE and the returned reference is well defined.

### reference QValueVector::back ()

Returns a reference to the last element in the vector. If there is no last element, this function has undefined behavior.

### const_reference QValueVector::back () const

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

Returns a const reference to the last element in the vector. If there is no last element, this function has undefined behavior.

### iterator QValueVector::begin ()

Returns an iterator pointing to the beginning of the vector. If the vector is empty(), the returned iterator will equal end().

### const_iterator QValueVector::begin () const

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

Returns a const iterator pointing to the beginning of the vector. If the vector is empty(), the returned iterator will equal end().

### size_type QValueVector::capacity () const

Returns the maximum number of elements possible without memory reallocation. If memory reallocation takes place, some or all iterators may become invalidated.

### void QValueVector::clear ()

Removes all elements from the vector.

### void QValueVector::detach ()`[protected]`

If the vector does not share its data with another QValueVector instance, nothing happens. Otherwise the function creates a new copy of this data and detaches from the shared one. This function is called whenever the vector is modified. The implicit sharing mechanism is implemented this way.

### bool QValueVector::empty () const

Returns TRUE if the vector is empty, otherwise FALSE. Equivalent to size()==0, but is faster.

### iterator QValueVector::end ()

Returns an iterator pointing behind the last element of the vector.

### const_iterator QValueVector::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 the vector.

### iterator QValueVector::erase ( iterator pos )

Removes the element at position pos and returns the position of the next element.

### iterator QValueVector::erase ( iterator first, iterator last )

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

Removes all elements from first up to but not including last and returns the position of the next element.

### reference QValueVector::front ()

Returns a reference to the first element in the vector. If there is no first element, this function has undefined behavior.

### const_reference QValueVector::front () const

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

Returns a const reference to the first element in the vector. If there is no first element, this function has undefined behavior.

### iterator QValueVector::insert ( iterator pos, const T & x )

Inserts a copy of x at the position immediately before pos.

### iterator QValueVector::insert ( iterator pos, size_type n, const T & x )

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

Inserts n copies of x immediately before position x.

### QValueVector<T> & QValueVector::operator= ( const QValueVector<T> & v )

Assigns v to this vector and returns a reference to this vector.

All iterators of the current vector become invalidated by this operation. The cost of such an assignment is O(1) since QValueVector is implicitly shared.

### QValueVector<T> & QValueVector::operator= ( const std::vector<T> & v )

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

Assigns v to this vector and returns a reference to this vector.

All iterators of the current vector become invalidated by this operation. The cost of such an assignment is O(1) since QValueVector is implicitly shared.

### bool QValueVector::operator== ( const QValueVector<T> & x )

Returns TRUE if each element in this vector equals each corresponding element in x, otherwise FALSE is returned.

### reference QValueVector::operator[] ( size_type i )

Returns a reference to the element at index i. If i is out of range, this function has undefined behavior.

### const_reference QValueVector::operator[] ( size_type i ) const

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

Returns a const reference to the element at index i. If i is out of range, this function has undefined behavior.

### void QValueVector::pop_back ()

Removes the last element from the vector.

### void QValueVector::push_back ( const T & x )

Appends a copy of x to the end of the vector.

### void QValueVector::reserve ( size_type n )

Increases the vector's capacity. If n is less than or equal to capacity(), nothing happens. Otherwise, additional memory is allocated so that capacity() will be increased to a value greater than or equal to n. All iterators will then become invalidated. Note that the vector's size() and the values of existing elements remain unchanged.

### void QValueVector::resize ( size_type n, const T & val = T ( ) )

Changes the size of the vector to n. If n is greater than the current size(), elements are added to the end and initialized with the value of val. If n is less than size(), elements are removed from the end. If n is equal to size() nothing happens.

### size_type QValueVector::size () const

Returns the number of elements in the vector.

This file is part of the Qt toolkit, copyright © 1995-2001 Trolltech, all rights reserved.