简体   繁体   中英

Fixed size std::vector

I'm currently in the process of changing the way I access my data structures, and I'm reviewing one of two solutions in the general case for vectors of vectors.

My incentive is simple; I want cache locality without giving up my interfaces.

I know the max-size of my vectors at compile time, but they won't always be reaching the max. Common case is about 80%, and the total size of each vector is to be relatively small. If I reach that max, I have made an error in logic somewhere, and want it to throw an error.

The first solution that came to mind, was to use a Pool allocator with std::vector, seemed like a good idea, but maybe a bit messy; having not used allocators properly before, I wasn't too sure of the solution. I'm not much of a fan for storing the data separate to its owners, and I want the implementation to be as transparent as possible.

The second solution works great for me at the moment, but I want to make it a little bit less in line. At the moment, it is thus:

class Foo {
public:
        std::array<Bar, 10> bars;
        size_t used;

        // std::vector<Bar> bars; // reserved to 10... maybe

        void add(int var1, int var2) {
                if (used >= bars.size()) throw "Error";
                bars[used] = Bar(var1, var2);
                ++used;

                // std::vector alternative
                // bars.push_back(Bar(var1, var2));
        }
        void remove(size_t idx) {
                bars[idx] = bars.back();
                --used;

                // bars.back().~Bar(); // should happen, not sure if safe

                // std::vector alternative
                // bars[idx] = bars.back();
                // bars.pop_back();
        }
}

Which, as mentioned, works great. However, if I wanted to move this solution elsewhere, I'd rather not have to implement it again, and have proper semantics in terms of destruction (similar to that of an actual vector).

So, I was wondering what a good solution could be? Currently, I've started wrapping an std::array , but it is starting to get messy, and I'm sure this is solved problem.

See this link for several options for fixed-size data structures with a vector-like interface. In particular, boost::auto_buffer and eastl::fixed_vector seem viable options for your code.

Yet another alternative is to use Hinnant's stack allocator with the regular std::vector , but MSVC++ has some trouble compiling it.

Boost has a MultiArray class intended for this purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM