C++ 初始化 QList 的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18998488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:24:51  来源:igfitidea点击:

What is the right way to initialize a QList?

c++qtqlist

提问by msgmaxim

What is the right way to initialize QList? I want to make this code shorter:

初始化 QList 的正确方法是什么?我想让这段代码更短:

QSplitter splitter;
QList<int> list;
list.append(1);
list.append(1);
splitter.setSizes(list);

But when I use initialization from std::list, it doesn't seem be working:

但是当我从 std::list 使用初始化时,它似乎不起作用:

splitter.setSizes(QList<int>::fromStdList(std::list<int>(1, 1)));

In latter case, the splitter seems to divide in ratio 1:0.

在后一种情况下,分路器似乎以 1:0 的比例进行分频。

回答by lpapp

You could use the following code:

您可以使用以下代码:

QList<int> list = QList<int>() << 1 << 1;

or initializer list with C++11:

或 C++11 的初始化列表:

QList<int> list({1, 1});

You can enable the latter with the -std=c++0x or -std=c++11 option for gcc. You will also need the relevant Qt version for that where initializer list support has been added to the QList constructor.

您可以使用 gcc 的 -std=c++0x 或 -std=c++11 选项启用后者。您还需要相关的 Qt 版本,因为在 QList 构造函数中添加了初始化列表支持。

回答by Tomaz Canabrava

Never use the QList<int>() << 1 << 1;variant, as it's really slow. use always the list({1, 1})variant.

永远不要使用QList<int>() << 1 << 1;变体,因为它真的很慢。始终使用list({1, 1})变体。

source: https://www.angrycane.com.br/en/2018/06/19/speeding-up-cornercases/

来源:https: //www.angrycane.com.br/en/2018/06/19/speeding-up-cornercases/