IT TIP

왜 벡터

itqueen 2021. 1. 5. 20:46
반응형

왜 벡터:: reference는 bool에 대한 참조를 반환하지 않습니까?


#include <vector>

struct A
{
    void foo(){}
};

template< typename T >
void callIfToggled( bool v1, bool &v2, T & t )
{
    if ( v1 != v2 )
    {
        v2 = v1;
        t.foo();
    }
}

int main()
{
    std::vector< bool > v= { false, true, false };

    const bool f = false;
    A a;

    callIfToggled( f, v[0], a );
    callIfToggled( f, v[1], a );
    callIfToggled( f, v[2], a );
}

위의 예제를 컴파일하면 다음 오류가 발생합니다.

dk2.cpp: In function 'int main()':
dk2.cpp:29:28: error: no matching function for call to 'callIfToggled(const bool&, std::vector<bool>::reference, A&)'
dk2.cpp:29:28: note: candidate is:
dk2.cpp:13:6: note: template<class T> void callIfToggled(bool, bool&, T&)

다음과 같이 g ++ (버전 4.6.1)을 사용하여 컴파일했습니다.

g++ -O3 -std=c++0x -Wall -Wextra -pedantic dk2.cpp

왜 이런 일이 발생합니까? 인가 vector<bool>::reference되지 bool&? 아니면 컴파일러의 버그입니까?
아니면 내가 멍청한 짓을하고 있는가? :)


Vector는 bool 전용 입니다.

그것은 표준의 실수로 간주됩니다. 사용 vector<char>하는 대신 :

template<typename t>
struct foo {
  using type = t;
};
template<>
struct foo<bool> {
  using type = char;
};

template<typename t, typename... p>
using fixed_vector = std::vector<typename foo<t>::type, p...>;

때때로 벡터 내부에 포함 된 부울에 대한 참조가 필요할 수 있습니다. 불행히도를 사용 vector<char>하면 문자에 대한 참조 만 제공 할 수 있습니다. 정말로 필요한 경우 Boost Containers 라이브러리를bool& 확인하십시오 . 특수화되지 않은 버전의 .vector<bool>


Your expectations are normal, but the problem is that std::vector<bool> has been a kind of experiment by the C++ commitee. It is actually a template specialization that stores the bool values tightly packed in memory: one bit per value.

And since you cannot have a reference to a bit, there's your problem.


std::vector< bool > packs its contents so each Boolean value is stored in one bit, eight bits to a byte. This is memory-efficient but computationally intensive, since the processor must perform arithmetic to access the requested bit. And it doesn't work with bool reference or pointer semantics, since bits within a byte do not have addresses in the C++ object model.

You can still declare a variable of type std::vector<bool>::reference and use it as if it were bool&. This allows generic algorithms to be compatible.

std::vector< bool > bitvec( 22 );
std::vector< bool >::reference third = bitvec[ 2 ];
third = true; // assign value to referenced bit

In C++11, you can work around this using auto and the && specifier which automatically selects an lvalue reference bound to the vector element or an rvalue reference bound to a temporary.

std::vector< bool > bitvec( 22 );
auto &&third = bitvec[ 2 ]; // obtain a std::vector< bool >::reference
third = true; // assign value to referenced bit

std::vector<bool> is a non conforming container. To optimize space, it packs bools and cannot provide reference.

Use boost::dynamic_bitset instead.


Just my 2 cents:

std::vector<bool>::reference is a typedef for struct _Bit_reference which is defined as

typedef unsigned long _Bit_type;

struct _Bit_reference
  {
    _Bit_type * _M_p;
    _Bit_type _M_mask;

    // constructors, operators, etc...

    operator bool() const
    { return !!(*_M_p & _M_mask); }
  };

Changing the function like this, it works (well, compiles at least, haven't tested):

template< typename T >
void callIfToggled( bool v1, std::vector<bool>::reference v2, T & t )
{
    bool b = v2;  
    if ( v1 != b )
    {
        v2 = v1;
        t.foo();
    }
}

EDIT: I changed the condition from (v1 != v2), which wasn't a good idea, to (v1 != b).


Make a structure with a bool in it, and make the vector<> using that struct type.

Try:

vector<struct sb> where sb is struct {boolean b];

then you can say

push_back({true})

do

typedef struct sbool {bool b;} boolstruct; and then vector<boolstruct> bs;

ReferenceURL : https://stackoverflow.com/questions/8399417/why-vectorboolreference-doesnt-return-reference-to-bool

반응형