【问题标题】:why the size of two vector<bool> bVec = { true,false,true,false,true}; vector<char> cVec = { 'a', 'b', 'c', 'd', 'e' }; are different?为什么两个向量的大小<bool> bVec = { true,false,true,false,true};向量<char> cVec = { 'a', 'b', 'c', 'd', 'e' };是不同的?
【发布时间】:2017-01-23 09:46:25
【问题描述】:
#include <iostream>
#include<vector>
using namespace std;
bool a;
char c;
int main() {

    vector<bool> bVec = { true,false,true,false,true};
    vector<char> cVec = { 'a', 'b', 'c', 'd', 'e' }; 
    cout<<sizeof( bVec );cout<<endl;
    cout<<sizeof( cVec );
    cout<<endl;
    cout<<sizeof(a);
    cout<<endl;
    cout<<sizeof(c);

    return 0;
}

当我编译这段代码时,我得到 cVec 的大小为 20 和 bvec 的大小为 12 。但是为什么大小不一样?

【问题讨论】:

标签: c++ vector std


【解决方案1】:

std::vector&lt;bool&gt;std::vector 的一个特例,它以节省空间的方式存储数据并返回代理对象而不是bool&amp; 来操作数据。因此,它通常具有与普通 std::vector 不同的成员数据,因此存在大小差异。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-05
    • 2014-11-05
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 2017-07-29
    相关资源
    最近更新 更多