Qstring Assignment Operator C++

Detailed Description

The QStringList class provides a list of strings.

QStringList inherits from QList<QString>. Like QList, QStringList is implicitly shared. It provides fast index-based access as well as fast insertions and removals. Passing string lists as value parameters is both fast and safe.

All of QList's functionality also applies to QStringList. For example, you can use isEmpty() to test whether the list is empty, and you can call functions like append(), prepend(), insert(), replace(), removeAll(), removeAt(), removeFirst(), removeLast(), and removeOne() to modify a QStringList. In addition, QStringList provides a few convenience functions that make handling lists of strings easier:

Adding strings

Strings can be added to a list using the append(), operator+=() and operator<<() functions. For example:

QStringList fonts; fonts <<"Arial"<<"Helvetica"<<"Times"<<"Courier";

Iterating over the strings

To iterate over a list, you can either use index positions or QList's Java-style and STL-style iterator types:

Indexing:

for (int i =0; i < fonts.size(); ++i) cout << fonts.at(i).toLocal8Bit().constData() << endl;

Java-style iterator:

QStringListIterator javaStyleIterator(fonts); while (javaStyleIterator.hasNext()) cout << javaStyleIterator.next().toLocal8Bit().constData() << endl;

STL-style iterator:

QStringList::const_iterator constIterator; for (constIterator = fonts.constBegin(); constIterator != fonts.constEnd(); ++constIterator) cout << (*constIterator).toLocal8Bit().constData() << endl;

The QStringListIterator class is simply a type definition for QListIterator<QString>. QStringList also provide the QMutableStringListIterator class which is a type definition for QMutableListIterator<QString>.

Manipulating the strings

QStringList provides several functions allowing you to manipulate the contents of a list. You can concatenate all the strings in a string list into a single string (with an optional separator) using the join() function. For example:

To break up a string into a string list, use the QString::split() function:

The argument to split can be a single character, a string, or a QRegExp.

In addition, the operator+() function allows you to concatenate two string lists into one. To sort a string list, use the sort() function.

QString list also provides the filter() function which lets you to extract a new list which contains only those strings which contain a particular substring (or match a particular regular expression):

The contains() function tells you whether the list contains a given string, while the indexOf() function returns the index of the first occurrence of the given string. The lastIndexOf() function on the other hand, returns the index of the last occurrence of the string.

Finally, the replaceInStrings() function calls QString::replace() on each string in the string list in turn. For example:

QStringList files; files <<"$QTDIR/src/moc/moc.y"<<"$QTDIR/src/moc/moc.l"<<"$QTDIR/include/qconfig.h"; files.replaceInStrings("$QTDIR","/usr/lib/qt");

Member Function Documentation

QStringList::QStringList()

Constructs an empty string list.

QStringList::QStringList(const QString & str)

Constructs a string list that contains the given string, str. Longer lists are easily created like this:

See also append().

QStringList::QStringList(const QStringList & other)

Constructs a copy of the other string list.

This operation takes constant time because QStringList is implicitly shared, making the process of returning a QStringList from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and that takes linear time.

See also operator=().

QStringList::QStringList(const QList<QString> & other)

Constructs a copy of other.

This operation takes constant time, because QStringList is implicitly shared. This makes returning a QStringList from a function very fast. If a shared instance is modified, it will be copied (copy-on-write), and that takes linear time.

See also operator=().

QStringList::QStringList(std::initializer_list<QString> args)

Construct a list from a std::initializer_list given by args.

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

This function was introduced in Qt 4.8.

bool QStringList::contains(const QString & str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns true if the list contains the string str; otherwise returns false. The search is case insensitive if cs is Qt::CaseInsensitive; the search is case sensitive by default.

See also indexOf(), lastIndexOf(), and QString::contains().

QStringList QStringList::filter(const QString & str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const

Returns a list of all the strings containing the substring str.

If cs is Qt::CaseSensitive (the default), the string comparison is case sensitive; otherwise the comparison is case insensitive.

QStringList list; list <<"Bill Murray"<<"John Doe"<<"Bill Clinton"; QStringList result; result = list.filter("Bill");

This is equivalent to

QStringList result; foreach (constQString&str, list) { if (str.contains("Bill")) result += str; }

See also contains().

QStringList QStringList::filter(const QRegExp & rx) const

This is an overloaded function.

Returns a list of all the strings that match the regular expression rx.

int QStringList::indexOf(const QRegExp & rx, int from = 0) const

Returns the index position of the first exact match of rx in the list, searching forward from index position from. Returns -1 if no item matched.

By default, this function is case sensitive.

See also lastIndexOf(), contains(), and QRegExp::exactMatch().

int QStringList::indexOf(const QString & value, int from = 0) const

Returns the index position of the first occurrence of value in the list, searching forward from index position from. Returns -1 if no item matched.

See also lastIndexOf(), contains(), and QList::indexOf().

int QStringList::indexOf(QRegExp & rx, int from = 0) const

This function overloads indexOf().

Returns the index position of the first exact match of rx in the list, searching forward from index position from. Returns -1 if no item matched.

By default, this function is case sensitive.

If an item matched, the rx regular expression will contain the matched objects (see QRegExp::matchedLength, QRegExp::cap).

This function was introduced in Qt 4.5.

See also lastIndexOf(), contains(), and QRegExp::exactMatch().

QString QStringList::join(const QString & separator) const

Joins all the string list's strings into a single string with each element separated by the given separator (which can be an empty string).

See also QString::split().

int QStringList::lastIndexOf(const QRegExp & rx, int from = -1) const

Returns the index position of the last exact match of rx in the list, searching backward from index position from. If from is -1 (the default), the search starts at the last item. Returns -1 if no item matched.

By default, this function is case sensitive.

See also indexOf(), contains(), and QRegExp::exactMatch().

int QStringList::lastIndexOf(const QString & value, int from = -1) const

Returns the index position of the last occurrence of value in the list, searching backward from index position from. If from is -1 (the default), the search starts at the last item. Returns -1 if no item matched.

By default, this function is case sensitive.

See also indexOf() and QList::lastIndexOf().

int QStringList::lastIndexOf(QRegExp & rx, int from = -1) const

This function overloads lastIndexOf().

Returns the index position of the last exact match of rx in the list, searching backward from index position from. If from is -1 (the default), the search starts at the last item. Returns -1 if no item matched.

By default, this function is case sensitive.

If an item matched, the rx regular expression will contain the matched objects (see QRegExp::matchedLength, QRegExp::cap).

This function was introduced in Qt 4.5.

See also indexOf(), contains(), and QRegExp::exactMatch().

int QStringList::removeDuplicates()

This function removes duplicate entries from a list. The entries do not have to be sorted. They will retain their original order.

Returns the number of removed entries.

This function was introduced in Qt 4.5.

QStringList & QStringList::replaceInStrings(const QString & before, const QString & after, Qt::CaseSensitivity cs = Qt::CaseSensitive)

Returns a string list where every string has had the before text replaced with the after text wherever the before text is found. The before text is matched case-sensitively or not depending on the cs flag.

For example:

QStringList list; list <<"alpha"<<"beta"<<"gamma"<<"epsilon"; list.replaceInStrings("a","o");

See also QString::replace().

QStringList & QStringList::replaceInStrings(const QRegExp & rx, const QString & after)

This is an overloaded function.

Replaces every occurrence of the regexp rx, in each of the string lists's strings, with after. Returns a reference to the string list.

For example:

QStringList list; list <<"alpha"<<"beta"<<"gamma"<<"epsilon"; list.replaceInStrings(QRegExp("^a"),"o");

For regular expressions that contain capturing parentheses, occurrences of \1, \2, ..., in after are replaced with rx.cap(1), rx.cap(2), ...

For example:

QStringList list; list <<"Bill Clinton"<<"Murray, Bill"; list.replaceInStrings(QRegExp("^(.*), (.*)$"),"\\2 \\1");

void QStringList::sort()

Sorts the list of strings in ascending order (case sensitively).

Sorting is performed using Qt's qSort() algorithm, which operates in linear-logarithmic time, i.e. O(n log n).

If you want to sort your strings in an arbitrary order, consider using the QMap class. For example, you could use a QMap<QString, QString> to create a case-insensitive ordering (e.g. with the keys being lower-case versions of the strings, and the values being the strings), or a QMap<int, QString> to sort the strings by some integer index.

See also qSort().

QStringList QStringList::operator+(const QStringList & other) const

Returns a string list that is the concatenation of this string list with the other string list.

See also append().

QStringList & QStringList::operator<<(const QString & str)

Appends the given string, str, to this string list and returns a reference to the string list.

See also append().

QStringList & QStringList::operator<<(const QStringList & other)

This is an overloaded function.

Appends the other string list to the string list and returns a reference to the latter string list.

C++ gives almost god-like powers to the designer of a class. Object "life cycle" management means taking complete control over the behavior of objects during birth, reproduction, and death. You have already seen how constructors manage the birth of an object and how destructors are used to manage the death of an object. This section investigates the reproduction process: the use of copy constructors and assignment operators.

A copy constructor is a constructor that has a prototype like this:

ClassName(const ClassName & x);

The purpose of a copy constructor is to create an object that is an exact copy of an existing object of the same class.

An assignment operator for a class overloads the symbol and gives it a meaning that is specific to the class. There is one particular version of the assignment operator that has the following prototype:

ClassName& operator=(const ClassName& x);

Because it is possible to have several different overloaded versions of the in a class, we call this particular version the copy assignment operator.

Example 2.16. src/lifecycle/copyassign/fraction.h

[ . . . . ] class Fraction { public: Fraction(int n, int d) ; Fraction(const Fraction& other) ; Fraction& operator=(const Fraction& other) ; Fraction multiply(Fraction f2) ; static report() ; private: int m_Numer, m_Denom; static int s_assigns; static int s_copies; static int s_ctors; }; [ . . . . ]

Regular constructor

Copy constructor

Copy assignment operator


The version of in Example 2.16 has three counters, defined in Example 2.17, so that you can count the total number of times each member function is called. This should help you to better understand when objects are copied.

Example 2.17. src/lifecycle/copyassign/fraction.cpp

[ . . . . ] int Fraction::s_assigns = 0; int Fraction::s_copies = 0; int Fraction::s_ctors = 0; Fraction::Fraction(const Fraction& other) : m_Numer(other.m_Numer), m_Denom(other.m_Denom) { ++s_copies; } Fraction& Fraction::operator=(const Fraction& other) { if (this != &other) { m_Numer = other.m_Numer; m_Denom = other.m_Denom; ++s_assigns; } return *this; } [ . . . . ]

Static member definitions.

operator=() should always do nothing in the case of self- assignment.

operator=() should always return *this, to allow for chaining i.e. a=b=c.


Example 2.18 uses this class to create, copy, and assign some objects.

Example 2.18. src/lifecycle/copyassign/copyassign.cpp

#include <> #include "fraction.h" int main() { cout(stdout); Fraction twothirds(2,3); Fraction threequarters(3,4); Fraction acopy(twothirds); Fraction f4 = threequarters; cout << "after declarations - " << Fraction::report(); f4 = twothirds; cout << "\nbefore multiply - " << Fraction::report(); f4 = twothirds.multiply(threequarters); cout << "\nafter multiply - " << Fraction::report() << endl; return 0; }

Using 2-arg constructor.

Using copy constructor.

Also using copy constructor.

Assignment.

Several objects are created here.


Here is the output of this program.

copyassign> ./copyassign after declarations - [assigns: 0 copies: 2 ctors: 2] before multiply - [assigns: 1 copies: 2 ctors: 2] after multiply - [assigns: 2 copies: 3 ctors: 3] copyassign>
Question

As you can see, the call to creates three objects. Can you explain why?

2.11. Copy Constructors and Assignment Operators

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *