gpt4 book ai didi

c++ - 如何告诉auto推断vector 的元素的非引用类型

转载 作者:行者123 更新时间:2023-12-01 14:53:59 30 4
gpt4 key购买 nike

这是代码:

int main()
{
std::vector<bool> b(5,false);
auto b0=b[0];
cout<<b0;
b[0]=true;
cout<<b0;
std::vector<int> i(5,false);
auto i0=i[0];
cout<<i0;
i[0]=true;
cout<<i0;

return 0;
}

0100

变量b0具有引用类型(std::_ Bit_reference),而i0是常规int。告诉auto推断某些非引用类型(例如bool)的正确语法是什么?

最佳答案

您将获得std::_Bit_reference,因为std::vector具有专用于bool模板的化(即std::vector<bool>)的“可能”节省空间的实现。

作为cppreference says, vector 以位而不是字节存储值:

The manner in which std::vector is made space efficient (as well as whether it is optimized at all) is implementation defined. One potential optimization involves coalescing vector elements such that each element occupies a single bit instead of sizeof(bool) bytes.



正如 templatetypedef所说, auto可以推断出第一件事,这恰好是从位获取 bool(boolean) 值的一种奇特类型。

Exposes class std::vector::reference as a method of accessing individual bits. In particular, objects of this class are returned by operator[] by value.



>operator bool() const;
>(until C++11)
>operator bool() const noexcept;
>(since C++11)
>Returns the value of the referenced bit.

它可以隐式转换为 bool(boolean) (AFAIK),因此您不必担心将其传递给需要 bool参数的函数。

关于c++ - 如何告诉auto推断vector <bool>的元素的非引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59327430/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com