jfritz42
jfritz42

Reputation: 5993

What is the difference between boost::container::vector and std::vector

What is the difference between boost::container::vector and std::vector?

Upvotes: 20

Views: 12218

Answers (2)

alfC
alfC

Reputation: 16242

There are several differences that I could compile:

° No specialization of boost::container::vector<bool> (source @roeland)

decltype(std::vector<bool>(10)[0]) == std::_Bit_reference
decltype(boost::container::vector<bool>(10)[0]) == bool&

° Uses Boost allocator infrastructure, which (especially in C++1x) is more flexible that the standard allocator, doesn't ignore certain traits that are provided by the allocator. (source: http://www.boost.org/doc/libs/1_59_0/doc/html/interprocess/allocators_containers.html#interprocess.allocators_containers.containers_explained.stl_container_requirements)

std::vector<double>::allocator_type == std::allocator<double>
boost::container::vector<double>::alloctor_type == boost::container::new_allocator<double>

In particular, one can still specify the reference and pointer types to be different from T& and T* (see Is it still possible to customize STL vector's "reference" type?)

° Support for recursive containers (source: The Boost C++ Libraries by Boris Schäling).

Some (old?) implementations of STL didn't support incomplete value types (they were not required in the first place), in particular recursive containers.

using boost::container::vector;

struct animal{
    vector<animal> children; // may not work with std::vector
};

int main(){
    animal parent;
    animal child1;
    animal child2;

    parent.children.push_back(child1);
    parent.children.push_back(child2);
}

° std::vector is a specification not an implementation. There is only one implementation boost::container::vector across all platforms, so more assumptions can be made (for example originally std::vector was not required to use contiguous memory) (source: The Boost C++ Libraries by Boris Schäling).

Upvotes: 5

roeland
roeland

Reputation: 5741

A case where you may need the boost version instead of the standard version is when you encounter the <bool> specialization.

std::vector<bool> is implemented as a bitset, it doesn't store its element as an array of bool.

This means for instance the following code will not work:

template<T>
void handleElement(T &element);

// suppose we get a bool vector:
std::vector<bool> v = ....;
// then this fails because v[i] is a proxy object
handleElement(v[0]);

boost::container::vector<bool> has no such specialization.

Upvotes: 14

Related Questions