C++是否存在支持下标访问时自动填充中间空位的容器或相关库?
问题解答
目前没有专门的第三方库单独提供该特性的容器,该需求实现成本极低,你可以基于STL现有容器自行封装即可,下面是两种常见场景的实现方案:
下标访问密集场景(基于std::vector封装)
适合大部分下标都会被用到的场景,内存连续访问效率高,核心逻辑是重载operator[]时自动扩容:
#include <vector> #include <stdexcept> template <typename T> class auto_fill_vector { private: std::vector<T> m_data; public: // 写操作重载,自动填充默认值扩容 T& operator[](size_t index) { if (index >= m_data.size()) { m_data.resize(index + 1, T{}); } return m_data[index]; } // 可选:只读操作重载,按需决定是否允许越界 const T& operator[](size_t index) const { if (index >= m_data.size()) { throw std::out_of_range("Index out of range"); } return m_data[index]; } // 可选:按需暴露std::vector的原生方法 size_t size() const { return m_data.size(); } void clear() { m_data.clear(); } auto begin() { return m_data.begin(); } auto end() { return m_data.end(); } };
测试效果完全匹配你给出的示例:
auto_fill_vector<int> m; m[0] = 2; // 内部存储:[2] m[1] = 3; // 内部存储:[2, 3] m[4] = 5; // 内部存储:[2, 3, 0, 0, 5] m[10] = 1; // 内部存储:[2, 3, 0, 0, 5, 0, 0, 0, 0, 0, 1]
下标访问稀疏场景(基于std::unordered_map封装)
适合大部分下标不会被用到的场景,比vector节省内存,只存储实际赋值过的元素,访问时判断下标是否存在,不存在则返回默认值:
#include <unordered_map> #include <algorithm> template <typename T> class sparse_auto_fill_map { private: std::unordered_map<size_t, T> m_data; size_t m_max_index = -1; public: T& operator[](size_t index) { m_max_index = std::max(m_max_index, index); return m_data[index]; } // 获取下标对应值,不存在则返回默认值 T get(size_t index) const { if (index > m_max_index) { throw std::out_of_range("Index out of range"); } auto it = m_data.find(index); return it != m_data.end() ? it->second : T{}; } size_t size() const { return m_max_index + 1; } };
内容的提问来源于stack exchange,提问作者LeoAlmDiniz
相关产品推荐
相关产品推荐

