C++ std::vector<bool>

本文详细介绍了C++中vector<bool>的特殊实现方式及其成员函数。与普通的vector相比,vector<bool>通过位操作来节省内存空间,并提供了一些特有的成员函数如flip。此外,文章还给出了一个使用flip函数翻转元素的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

std::vector
template < class T, class Alloc = allocator<T> > class vector; // generic template
template <class Alloc> class vector<bool,Alloc>;               // bool specialization(特殊化)
Vector of bool

This is a specialized version of vector, which is used for elements of type bool and optimizes(最优化) for space.

It behaves like the unspecialized version of vector, with the following changes:

The storage is not necessarily an array of bool values, but the library implementation may optimize storage so that each value is stored in a single bit.

Elements are not constructed using the allocator object, but their value is directly set on the proper bit in the internal storage.

Member function flip and a new signature(签名) for member swap.

A special member type, reference, a class that accesses individual bits in the container's internal storage with an interface that emulates(模仿) a bool reference. Conversely(相反的), member type const_reference is a plain bool.

The pointer and iterator types used by the container are not necessarily neither pointers nor conforming iterators, although they shall simulate(模拟) most of their expected behavior.

These changes provide a quirky interface to this specialization and favor memory optimization over processing (which may or may not suit your needs). In any case, it is not possible to instantiate the unspecialized template of vector for bool directly. Workarounds to avoid this range from using a different type (char, unsigned char) or container (like deque) to use wrapper types or further specialize for specific allocator types.

bitset is a class that provides a similar functionality for fixed-size arrays of bits.

Member functions
  • flip: Flip bits (public member function )
  • swap: Swap containers or elements (public member function )
Non-member class specializations
  • hash<vector>: Hash for vector (class template specialization )
Data races

Simultaneous access to different elements is not guaranteed to be thread-safe (as storage bytes may be shared by multiple bits).

Example
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char **argv)
{
    vector<bool> flags;

    flags.push_back(true);
    flags.push_back(false);
    flags.push_back(false);
    flags.push_back(true);

    flags.flip(); // false true true false

    cout << "flags value:";
    for(int i=0; i < flags.size(); i++)
        cout << " " << flags.at(i);

    cout << "\n";
    return 0;
}
Reference

cplusplus


转载于:https://www.cnblogs.com/zi-xing/p/6389263.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值