Lig*_*ica 6 c++ implementation containers
容器喜欢std::basic_string并std::vector在内部容量耗尽时执行自动重新分配.该标准规定,在重新分配后,.capacity() >= .size().
在执行重新分配时,主流工具链使用了哪些实际乘数?
更新
到目前为止,我有:
Dinkumware:1.5(配备MSVS和可能的ICC)
GNU libstdc ++:2(附带GCC和可能的ICC)
RW/Apache stdcxx:1.618
STLport:2
老问题的新答案。
理由:可以通过编程方式并使用在线编译器相对容易地回答这个问题。这是一个可以帮助您回答这个问题的程序:
#include <climits>
#include <cstddef>
#include <cstdlib>
#ifndef _MSC_VER
# include <cxxabi.h>
#endif
#include <iostream>
#include <memory>
#include <string>
#include <typeinfo>
#include <type_traits>
#include <limits>
#include <vector>
#include <string>
template <typename T>
std::string
type_name()
{
typedef typename std::remove_reference<T>::type TR;
std::unique_ptr<char, void(*)(void*)> own
(
#ifndef _MSC_VER
abi::__cxa_demangle(typeid(TR).name(), nullptr,
nullptr, nullptr),
#else
nullptr,
#endif
std::free
);
std::string r = own != nullptr ? own.get() : typeid(TR).name();
if (std::is_const<TR>::value)
r += " const";
if (std::is_volatile<TR>::value)
r += " volatile";
if (std::is_lvalue_reference<T>::value)
r += "&";
else if (std::is_rvalue_reference<T>::value)
r += "&&";
return r;
}
template <class C>
void
test()
{
C c;
std::cout << type_name<C>() << ":\n";
std::size_t c0 = c.capacity();
std::cout << " Initial capacity is " << c0 << '\n';
c.resize(c0);
for (int i = 0; i < 10; ++i)
{
c.push_back(typename C::value_type{});
std::size_t c1 = c.capacity();
if (c0 != 0)
{
float f = static_cast<float>(c1)/c0;
std::cout << " growth factor appears to be " << f << '\n';
}
c0 = c1;
c.resize(c0);
}
}
int
main()
{
test<std::vector<int>>();
test<std::string>();
}
Run Code Online (Sandbox Code Playgroud)
大多数复杂性都是不必要的,因为它只是为了开始type_name工作。
libstdc++:
http://melpon.org/wandbox/permlink/njaIG2uiR2vlCLZz
对于向量和字符串来说,似乎都回答了实心 2。
对比:
http://webcompiler.cloudapp.net
对于向量和字符串来说都非常接近 1.5。
库++
http://melpon.org/wandbox/permlink/mXshrLJHgNuvE1mD
对于向量和字符串来说都非常接近 2。
请注意,该程序还告诉您短字符串缓冲区的用途string:libstdc++ 和 VS 均为 15,libc++ 为 22。