Search code examples
c++stdvector

Allocate two std::vectors after each other on memory in nested data structure


Let's say I have a data structure that looks something like this:

#include <vector>
#include <cstdef>

struct one {
    one(size_t n) : vec(n) {}
    std::vector<int> vec;
    // + some other stuff
};


struct entity {
    entity(size_t n) : One(n), Two(n) {}
    one One;
    one Two;
};

I want to have vec from Two allocated on memory right after vec from One ends, as it can make differences in performance. In C this would be easy by using pointer arrays. However I was wondering if there is a c++ style (using std::vectors) solution for that, maybe adapting the constructors?


Solution

  • You can use the span for this

    #include <algorithm>
    #include <iostream>
    #include <memory>
    #include <ranges>
    #include <span>
    
    struct Part {
        Part(int *ptr, std::size_t n)
            : span(ptr, n)
        {
            std::ranges::fill(span, std::rand());
        }
    
        std::span<int> span;
    };
    
    struct Entity {
        Entity(std::size_t n)
            : mem(new int[n * 2]),
              first(mem.get(), n),
              second(mem.get() + n, n)
        {}
    
        std::unique_ptr<int[]> mem;
        Part first;
        Part second;
    };
    
    int main()
    {
        Entity ent(10);
        const auto print = [](int a){ std::cout << a << std::endl; };
        std::ranges::for_each(ent.first.span, print);
        std::ranges::for_each(ent.second.span, print);
    }
    

    example in compiler explorer