首先C++标准并没有规定vector的增长方式,题目说vector内部内存扩展方式是翻倍其实严格来说是错的,只是现代大多数编译器这么决定罢了,并不是说标准规定了,这个编译器想怎么干事编译器的事,比如说MS的Visual studio就不是这么干的,不多说,直接看代码。 #include <iostream> #include <vector> int main() { std::vector<int>::size_type sz; std::vector<int> foo; sz = foo.capacity(); std::cout << "making foo grow:\n"; for (int i = 0; i<100; ++i) { foo.push_back(i); if (sz != foo.capacity()) { sz = foo.capacity(); std::cout << "capacity changed: " << sz << '\n'; } } std::vector<int> bar; sz = bar.capacity(); bar.reserve(100); // this is the only difference with foo above std::cout << "making bar grow:\n"; for (int i = 0; i<100; ++i) { bar.push_back(i); if (sz != bar.capacity()) { sz = bar.capacity(); std::cout << "capacity changed: " << sz << '\n'; } } return 0; }
bitset<3> bb; bb[0] = 1; bb[1] = false; bb[2] = 0;