C ++在编译时计算和排序向量 [英] C++ calculate and sort vector at compile time
问题描述
我有一个 A类
,它有一个 std :: vector< int>
当创建 A
的实例时,需要填充此向量。
计算可能需要一些时间,我想知道如果:
1)它可以在编译时完成。
2)向量可以排序编译时间以及
I have a class A
that has a std::vector<int>
as attribute.
A needs to fill this vector when an instance of A
is created.
The calculation can take some time and I would like to know if :
1) it can be done at compile time.
2) the vector can be sorted at compile time as well
我不熟悉元编程,我现在没有找到办法。这不是操作系统的具体问题。
I am not familiar with metaprogramming and I didn't find a way to do it for now. It's not an OS specific question.
这是 A.cpp
文件:
#include "A.h"
#define SIZEV 100
A::A()
{
fillVector();
}
void A::fillVector()
{
// m_vector is an attribute of class "A"
// EXPECTATION 1 : fill the vector with the following calculation at compile time
const int a=5;
const int b=7;
const int c=9;
for(int i=0;i<SIZEV;i++){
for(int j=0;j<SIZEV;j++){
for(int k=0;k<SIZEV;k++){
this->m_vector.push_back(a*i+b*j+c*k);
}
}
}
// EXPECTATION 2 : sort the vector as compile time
}
std::vector<int> A::getVector() const
{
return m_vector;
}
void A::setVector(const std::vector<int> &vector)
{
m_vector = vector;
}
和 main.cpp
(Qt应用程序,但并不重要):
and the main.cpp
(Qt app but doesn't matter):
#include <QCoreApplication>
#include "A.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
A a;
auto vec = a.getVector();
// use vec, etc ...
return app.exec();
}
推荐答案
A std :: vector< int>
没有任何 constexpr
构造函数(因为 constexpr
)。因此,您不能在编译时对 std :: vector< int>
进行排序。
A std::vector<int>
does not have any constexpr
constructors (because dynamic memory allocation is disallowed for constexpr
). So you can't sort a std::vector<int>
at compile-time.
a std :: array
N
自己写排序例程,因为 std :: sort
不是 constexpr
。
You can create a std::array<int, N>
at compile-time for a constant N
, but you'd have to write your own sorting routine because std::sort
is not constexpr
either.
您还可以写一个 Boost.MPL 编译时向量或列表,并使用 sort
例程。但是这不会扩展到 std :: array
。
You can also write a Boost.MPL compile-time vector or list and use the sort
routine of that. But this won't scale as well as std::array
.
另一个攻击角度可能是存储将向量转换为 static
变量,并在程序初始化时进行排序。您的程序只需要一点点开始,但它不会影响其主要功能的其余部分。
Another angle of attack might be to store the vector into a static
variable and do the sorting at program initialization. Your program just takes a bit longer to start, but it won't affect the rest of its main functionality.
由于排序是 O(N log N)
,您甚至可能有一个两步构建,排序的向量到一个文件,并编译/链接到你的主程序,或将它在 O(N)
在程序启动时加载到 static
变量。
Since sorting is O(N log N)
, you might even have a two-step build and write the sorted vector to a file, and either compile/link it to your main program, or load it in O(N)
at program startup into a static
variable.
这篇关于C ++在编译时计算和排序向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!