Skip to content

Instantly share code, notes, and snippets.

@Kerogi
Created May 24, 2019 08:31
test std::vector allocation pattern
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>
#include <bitset>
template<typename> struct int_ { typedef int type; };
struct has_no_member_to_string {};
struct check_member_to_string : has_no_member_to_string {};
template<typename T, typename int_<decltype(T::to_string)>::type = 0>
std::string to_string_f(T&& v, check_member_to_string) {
return v.to_string();
}
template<typename T>
std::string to_string_f(T&& v, has_no_member_to_string) {
return std::to_string(v);
}
template<typename T>
bool comp_string_repr(T&& a, T&& b)
{
return to_string_f(a, check_member_to_string()).length() < to_string_f(b, check_member_to_string()).length();
}
template<class IterT>
size_t longest_element(IterT begin_it, const IterT& end_it)
{
auto it = std::max_element(begin_it, end_it, comp_string_repr<decltype(*begin_it)>);
if(it != end_it)
return to_string_f(*it, check_member_to_string()).length();
return 0;
}
template<typename T, typename int_<decltype(T::to_string)>::type = 0>
void to_ostream(std::ostream& os, T &&v, check_member_to_string) {
os<<v.to_string();
}
template<typename T>
void to_ostream(std::ostream& os, T &&v, has_no_member_to_string) {
os<<v;
}
template<class T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
size_t max_item_length = longest_element(v.begin(), v.end()) ;
os<<"|"<<v.size()<<"/"<<v.capacity()<<"|";
os<<"[";
bool first = true;
size_t i = 0;
const char delim[] = ",";
for(;i<v.size(); ++i) {
if(!first) os<<delim;
os<<std::setw(max_item_length);
to_ostream(os, v[i], check_member_to_string());
first = false;
}
for(;i<v.capacity(); ++i) {
if(!first) os<<delim;
os<<std::setw(max_item_length)<<'_';
first = false;
}
return os<<"]";
}
template<class T, class Func>
void
test_vector_allocations(Func func, int count=10, int step = 1) {
std::vector<T> vec;
for(int i=0; i < count; ++i) {
std::cout <<vec<< "\n";
func(vec,i*step);
}
std::cout <<vec<< "\n";
}
int main()
{
std::cout << "std::vector<int> - 65 push_back(s)\n";
test_vector_allocations<int>([](std::vector<int>& v, int counter){v.push_back(counter);}, 65);
std::cout << "\n";
std::cout << "std::vector<int> - 65 reserve(s)\n";
test_vector_allocations<int>([](std::vector<int>& v, int counter){v.reserve(counter+1);}, 65 );
std::cout << "\n";
std::cout << "std::vector<bool> - 65 push_back(s)\n";
test_vector_allocations<bool>([](std::vector<bool>& v, int counter){v.push_back(counter%2==0);}, 65);
std::cout << "\n";
std::cout << "std::vector<bool> - 65 reserve(s)\n";
test_vector_allocations<bool>([](std::vector<bool>& v, int counter){v.reserve(counter+1);}, 65);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment