如何在 Qt 6 中将 QList 转换为 QSet

How to convert QList to QSet in Qt 6

我正在将我的应用程序移植到 Qt 6,在阅读文档时我看到 类 被清理了很多,QListQVector 是统一的,QStringList 现在是 QList<QString> 的别名等等。

但是现在这给了我一个问题。

在我的代码(即 Qt 5)中,我将 QStringList 转换为 QSet 以消除列表中的重复项。我浏览了新文档,但我还没有看到在 Qt 6 中将 QList 转换为 QSet 的方法。

那么如何将 QList 转换为 QSet?或者这是不可能的,我需要编写一个辅助函数来删除重复项?

编辑:我正在使用 Qt 6.0.1。

你是对的,在code or the doc中看到QStringList是QList

的child
class QStringList : public QList<QString>
{

所以你可以调用QSet toSet() const;直接因为方法是 public.

有了这个,你可以直接解压QStringlist的内容到qset

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString str = "one,two,three,four,one";
    QStringList strlt = str.split(QChar(','));

    const QSet<QString> strVe = strlt.toSet();
    qDebug() << strVe;

    return a.exec();
}

我必须承认我还在使用 Qt5。

但是,QListQSet提醒我要std::liststd::set。 对于后者,已经有另一种(更灵活的)方法来实现这样的事情: 使用带有迭代器的构造。 Qt6 文档中的简短检查。说服我,这也应该在 Qt 类 中工作:

QSet::QSet(InputIterator first, InputIterator last)

Constructs a set with the contents in the iterator range [first, last).

The value type of InputIterator must be convertible to T.

Note: If the range [first, last) contains duplicate elements, the first one is retained.

This function was introduced in Qt 5.14.

其中 first 设置为

QList::iterator QList::begin()

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

last

QList::iterator QList::end()

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

放在一起应该是什么样子:

QList<QString> aList;
// populate list
QSet<QString> aSet(aList.begin(), aList.end());

OP 注意到 Qt-5 文档。已经包含有关此的提示:

QSet QList::toSet() const

Note: Since Qt 5.14, range constructors are available for Qt's generic container classes and should be used in place of this method.

OP 还提到了一个方便的包装器:

template <typename T>
QSet<T> QListToQSet(const QList<T>& qlist)
{
  return QSet<T> (qlist.constBegin(), qlist.constEnd());
}

应用于上述示例:

QList<QString> aList;
// populate list
QSet<QString> aSet = QListToQSet(aList);

更通用的转换工具可能是这样的:

template <typename T, template<typename> typename C>
QSet<T> toQSet(const C<T> &container)
{
  return QSet<T>(container.begin(), container.end());
}

即使与匹配的 std 容器一起工作也可以:

std::vector<QString> aVec = { "Hello", "World", "Hello" };
QSet<QString> aSet = toSet(aVec);