🔧intermediate
constexpr std::vector
Use dynamic allocation at compile time
Example Code
cpp
#include <vector>#include <algorithm>#include <numeric>// C++20 allows constexpr dynamic allocationconstexpr int sum_of_squares(int n) { std::vector<int> squares; squares.reserve(n); for (int i = 1; i <= n; ++i) { squares.push_back(i * i); } return std::accumulate(squares.begin(), squares.end(), 0);}// Compile-time sortingconstexpr auto get_sorted_data() { std::vector<int> data = {5, 2, 8, 1, 9, 3}; std::sort(data.begin(), data.end()); // Must return fixed-size type for constexpr std::array<int, 6> result; std::copy(data.begin(), data.end(), result.begin()); return result;}int main() { // Computed at compile time constexpr int result = sum_of_squares(5); // 1+4+9+16+25 = 55 static_assert(result == 55); constexpr auto sorted = get_sorted_data(); static_assert(sorted[0] == 1); static_assert(sorted[5] == 9); return 0;}Explanation
C++20 allows constexpr std::vector and other dynamic allocations, as long as all memory is deallocated before the constant evaluation completes. This enables complex compile-time computations.
Key Points
- 1std::vector can be used in constexpr
- 2Memory must be freed before evaluation ends
- 3std::sort and algorithms work at compile time
- 4Enables complex compile-time logic