python - Qt 相当于 Python 的 range() 函数,返回 QList<int> 吗?

标签 python qt integer range qlist

如果没有等效的函数;是否可以干净地生成 QList<int>(1, 2, 3, 4, 5 ... )用一行代码,避免 for loop或者必须编写自己的函数?

最佳答案

我不知道 Qt 容器的特殊性,但在 STL 中你可以这样做:

std::vector<int> v(n); std::iota(v.begin(), v.end(), 1);

或者,如果不使用 C++11,std::generate_n(v.begin(), v.end(), my_iota(1));其中 my_iota 是您编写的仿函数,它仅返回 n++,n 的初始值在该仿函数中提供。

如果 Qt 容器提供符合 STL OutputIterator 概念的迭代器,那么您应该可以使用 std::generate 或 std::iota。

<小时/>

Qt 容器(QList 和 QVector)提供可以利用此功能的 STL 兼容迭代器:

#include <QDebug>
#include <QVector>
#include <numeric>

inline QVector<int> range(int start, int end)
{
    QVector<int> l(end-start+1);
    std::iota(l.begin(), l.end(), start);
    return l;
}

int main()
{
    qDebug() << range(-3, 4);
    return 0;
}

打印

QVector(-3, -2, -1, 0, 1, 2, 3, 4)

关于python - Qt 相当于 Python 的 range() 函数,返回 QList<int> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34443169/

相关文章:

python - tf.GradientTape() 返回 None

c++ - 在标题栏中添加一个按钮

c++ - 在Mac上的Qt-隐藏主窗口时,应用停止响应停靠菜单图标的上下文菜单中的操作

javascript - 从 Javascript 中的字符串中提取多个整数

python - Numpy 和 Scipy 与 Amazon Elastic MapReduce

python - 迭代 python 列表对象并调用每个对象的方法

c++ - 如何将着色表应用于我的灰度 8 位图像并在 Qt 中正确转换它?

C:拆分整数并将其转换为 ASCII

javascript - 如何在Javascript中循环4个变量的值?

python - 如何将不同值的行连接成新列的单行?