gpt4 book ai didi

C++ 在编译时计算和排序 vector

转载 作者:可可西里 更新时间:2023-11-01 14:53:26 25 4
gpt4 key购买 nike

我有一个 class A有一个std::vector<int>作为属性。 A需要在 A 的实例时填充此 vector 被 build 。计算可能需要一些时间,我想知道是否:

  1. 它可以在编译时完成。
  2. vector 也可以在编译时排序

我对元编程不熟悉,暂时没有找到方法。这不是特定于操作系统的问题。

这是 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 应用程序但没关系):

#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> 进行排序在编译时。

您可以创建一个 std::array<int, N>在编译时常量 N , 但你必须编写自己的排序程序,因为 std::sort不是 constexpr任何一个。

你也可以写一个Boost.MPL编译时 vector 或列表并使用 sort例行公事。但这不会像std::array 那样扩展。 .

另一个攻击角度可能是将 vector 存储到 static 中变量并在程序初始化时进行排序。您的程序只是需要更长的时间来启动,但不会影响其其余主要功能。

因为排序是 O(N log N) ,你甚至可能有一个两步构建并将排序后的 vector 写入一个文件,然后将它编译/链接到你的主程序,或者将它加载到 O(N) 中。在程序启动时进入 static变量。

关于C++ 在编译时计算和排序 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32660523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com