Iterator failure while moving over equal_range in Boost MultiIndex container - c++

I'm making some mistake with my iterators, but I can't see it yet.
I have a Boost MultiIndex container, HostContainer hmap, whose elements are boost::shared_ptr to members of class Host. All the indices work on member functions of class Host. The third index is by Host::getHousehold(), where the household member variable is an int.
Below, I'm trying to iterate over the range of Hosts matching a particular household (int hhold2) and load the corresponding private member variable Host::id into an array. I'm getting an "Assertion failed: (px != 0), function operator->, file /Applications/boost_1_42_0/boost/smart_ptr/shared_ptr.hpp, line 418" error in runtime when the household size is 2. (I can't yet tell if it happens anytime the household size is 2, or if other conditions must be met.)
typedef multi_index_container<
boost::shared_ptr< Host >,
indexed_by<
hashed_unique< const_mem_fun<Host,int,&Host::getID> >, // 0 - ID index
ordered_non_unique< const_mem_fun<Host,int,&Host::getAgeInY> >, // 1 - Age index
ordered_non_unique< const_mem_fun<Host,int,&Host::getHousehold> > // 2 - Household index
> // end indexed_by
> HostContainer;
typedef HostContainer::nth_index<2>::type HostsByHH;
// inside main()
int numFamily = hmap.get<2>().count( hhold2 );
int familyIDs[ numFamily ];
for ( int f = 0; f < numFamily; f++ ) {
familyIDs[ f ] = 0;
}
int indID = 0;
int f = 0;
std::pair< HostsByHH::iterator, HostsByHH::iterator > pit = hmap.get<2>().equal_range( hhold2 );
cout << "\tNeed to update households of " << numFamily << " family members (including self) of host ID " << hid2 << endl;
while ( pit.first != pit.second ) {
cout << "Pointing at new family member still in hhold " << (*(pit.first))->getHousehold() << "; " ;
indID = (*(pit.first) )->getID();
familyIDs[ f ] = indID;
pit.first++;
f++;
}
What could make this code fail? The above snippet only runs when numFamily > 1. (Other suggestions and criticisms are welcome too.) Thank you in advance.
I replaced the while() loop with
for ( HostsByHH::iterator fit = pit.first; fit != pit.second; fit++ ) {
cout << "Pointing at new family member still in hhold " << (*fit)->getHousehold() << "; " ;
indID = (*fit )->getID();
cout << "id=" << indID << endl;
familyIDs[ f ] = indID;
f++;
}
This seems to work.
I don't quite understand how this is a fix or why the earlier error only occurred with households of size 2. Any insight would be very welcome.

int numFamily = hmap.get<2>().count( hhold2 );
int familyIDs[ numFamily ];
How can this possibly work? This shouldn't even compile: you can't define an array with a variable number of elements, numFamily had to be a compile time constant or else you have to define familyIDs as
int *familyIDs= new int[ numFamily ];

Related

C++: basic_string::_M_construct null not valid error for Graph BFS algorithm

This is a standard BFS algorithm for graphs using templates. The algorithm works well for all basic data types except for string. I know it is caused when a null value is passed to std::string(), but I can't figure out exactly why there should be a null string in the first place in the code.
#include <bits/stdc++.h>
using namespace std;
template < typename T >
class Graph {
unordered_map < T, list < T >> adjList;
public:
void addEdge(T u, T v, bool birdir = true) {
adjList[u].push_back(v);
if (birdir)
adjList[v].push_back(u);
}
void printG() {
for (auto i: adjList) {
cout << i.first << "->";
for (auto nodes: i.second) {
cout << nodes << ",";
}
cout << endl;
}
}
void BFS(T src) {
queue < T > Q;
unordered_map < T, bool > visited;
Q.push(src);
//Q.push(nullptr);
visited[src] = true;
while (!Q.empty()) {
T f = Q.front();
Q.pop();
cout << f << " -- ";
for (auto neighbor: adjList[f]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
Q.push(neighbor);
}
}
}
}
};
int main() {
Graph < string > * g = new Graph < string > ();
g - > addEdge("0", "1", false);
g - > addEdge("1", "3");
//g->printG();
cout << endl;
g - > BFS(0);
}
The problem here is how you call BFS. You use
g - > BFS(0);
which tries to construct a std::string from 0. 0 is the null pointer constant and since std::string has an overload that takes a const char*, the compiler calls that constructor. That is not valid to do though since the pointer cannot be a null pointer. This causes the exception to you encounter. You'll need to change code to
g - > BFS("");
or even simpler
g - > BFS();
Graph<std::string>::BFS is a member function that takes a std::string. When you call g->BFS(0);, the 0 is used to construct the std::string argument, and calls the constructor that takes a const char*. This calls std::string::string(nullptr).
To avoid 0 being interpreted as a null pointer in your code in gcc, use -Wzero-as-null-pointer-constant. You probably meant g->BFS("0") (The string "0")

How to create a map with custom class/comparator as key

I have a class named ItemType. It has two members - both double, named m_t and m_f. Two items of type ItemType are considered to be equal if these two members differ from each other within respective tolerance levels. With this logic, the comparator function is so defined as well. However, when I insert objects of this type as key into a map, only one key is produced in the map, even though at least three such keys should be present:
#include <iostream>
#include <string>
#include <map>
#include <cmath>
#include <vector>
using namespace std;
class ItemKey
{
public:
ItemKey(double t, double f)
{
m_t = t;
m_f = f;
}
double m_t;
double m_f;
double m_tEpsilon = 3;
double m_fEpsilon = 0.1;
bool operator<(const ItemKey& itemKey) const
{
int s_cmp = (abs(itemKey.m_f - m_f) > m_fEpsilon);
if (s_cmp == 0)
{
return (abs(itemKey.m_t - m_t) > m_tEpsilon);
}
return s_cmp < 0;
}
};
int main()
{
// The pairs are the respective values of m_t and m_f.
vector<pair<double, double>> pairs;
// These two should belong in one bucket -> (109.9, 9.0), because m_f differs by 0.09 and m_t differs by just 1
pairs.emplace_back(109.9, 9.0);
pairs.emplace_back(110.9, 9.09);
// This one is separate from above two beause even though m_t is in range, m_f is beyong tolerance level
pairs.emplace_back(109.5, 10.0);
// Same for this as well, here both m_t and m_f are beyong tolerance of any of the two categories found above
pairs.emplace_back(119.9, 19.0);
// This one matches the second bucket - (109.5, 10.0)
pairs.emplace_back(109.9, 10.05);
// And this one too.
pairs.emplace_back(111.9, 9.87);
map<ItemKey, size_t> itemMap;
for (const auto& item: pairs)
{
ItemKey key(item.first, item.second);
auto iter = itemMap.find(key);
if (iter == itemMap.end())
{
itemMap[key] = 1;
}
else
{
itemMap[iter->first] = itemMap[iter->first] + 1;
}
}
// The map should have three keys - (109.9, 9.0) -> count 2, (109.5, 10.0) -> count 3 and (119.9, 19.0) -> count 1
cout << itemMap.size();
}
However, the map seems to have only 1 key. How do I make it work as expected?
Why isn't your version working?
You did well to create your own comparison function. To answer your question, you have an error in your operator<() function such that only returns true if m_f is outside of tolerance and m_t is within tolerance, which I'm guessing is not what you desired. Let's take a look.
int s_cmp = (abs(itemKey.m_f - m_f) > m_fEpsilon);
The above line basically is checking whether this->m_f and itemKey.m_f are within tolerance of eachother (meaning equal to each other). That is probably what was intended. Then you say
if (s_cmp == 0)
{
return (abs(itemKey.m_t - m_t) > m_tEpsilon);
}
If s_cmp is true, then it will have the value of 1, and it will have a value of 0 for false (meaning that they are not within tolerance of each other). Then you return true if the m_t value is within tolerance. Up to this point, you return true if m_f is not equal (according to tolerance) and if m_t is equal (according to tolerance). Then your last line of code
return s_cmp < 0;
will return true always since a boolean converted to an integer cannot ever be negative.
How to get it working?
#include <iostream>
#include <string>
#include <map>
#include <cmath>
#include <vector>
struct ItemKey
{
double m_t;
double m_f;
static constexpr double t_eps = 3;
static constexpr double f_eps = 0.1;
ItemKey(double t, double f) : m_t(t), m_f(f) {}
bool operator<(const ItemKey& other) const
{
// Here it is assumed that f_eps and t_eps are positive
// We also ignore overflow, underflow, and NaN
// This is written for readability, and assumed the compiler will be
// able to optimize it.
auto fuzzy_less_than = [] (double a, double b, double eps) {
return a < b - eps;
};
bool f_is_less_than = fuzzy_less_than(this->m_f, other.m_f, f_eps);
bool f_is_greater_than = fuzzy_less_than(other.m_f, this->m_f, f_eps);
bool f_is_equal = !f_is_less_than && !f_is_greater_than;
bool t_is_less_than = fuzzy_less_than(this->m_t, other.m_t, t_eps);
return f_is_less_than || (f_is_equal && t_is_less_than);
}
};
int main()
{
using namespace std;
// The pairs are the respective values of m_t and m_f.
vector<pair<double, double>> pairs;
// These two should belong in one bucket
// -> (109.9, 9.0), because m_f differs by 0.09 and m_t differs by just 1
pairs.emplace_back(109.9, 9.0);
pairs.emplace_back(110.9, 9.09);
// This one is separate from above two beause even though m_t is in range,
// m_f is beyong tolerance level
pairs.emplace_back(109.5, 10.0);
// Same for this as well, here both m_t and m_f are beyong tolerance of any
// of the two categories found above
pairs.emplace_back(119.9, 19.0);
// This one matches the second bucket - (109.5, 10.0)
pairs.emplace_back(109.9, 10.05);
// And this one too.
pairs.emplace_back(111.9, 9.87);
map<ItemKey, size_t> itemMap;
for (const auto& item: pairs)
{
ItemKey key(item.first, item.second);
auto iter = itemMap.find(key);
if (iter == itemMap.end())
{
itemMap[key] = 1;
}
else
{
itemMap[iter->first] = itemMap[iter->first] + 1;
}
}
// The map should have three keys
// - (109.9, 9.0) -> count 2
// - (109.5, 10.0) -> count 3
// - (119.9, 19.0) -> count 1
cout << itemMap.size();
cout << "itemMap contents:" << endl;
for (auto& item : itemMap) {
cout << " (" << item.first << ", " << ")" << endl;
}
return 0;
}
There are a few things I changed above. I have a few suggestions also unrelated to the programming mistake:
Do not store boolean values into integer variables.
There's a reason that C++ introduced the bool type.
Write your code to be readable and in a way that the compiler
can easily optimize. You may notice I used a lambda expression
and multiple booleans. Smart compilers will inline the calls to
that lambda expression since it is only used within the local scope.
Also smart compilers can simplify boolean logic and make it
performant for me.
The m_tEpsilon and m_fEpsilon are probably not good to be
changable variables of the class. In fact, it may be bad if one
object has a different epsilon than another one. If that were the
case, which do you use when you do the < operator? For this
reason, I set them as static const variables in the class.
For constructors, it is better to initialize your variables in the
initializer list rather than in the body of the constructor. That
is unless you are doing dynamic resource allocation, then you would
want to do it in the constructor and make sure to clean it up if
you end up throwing an exception (preferrably using the RAII
pattern). I'm starting to get too far off topic :)
Even though class and struct are basically identical except for
the default protection level (class is private by default and
struct is public by default). It is convention to have it as a
struct if you want direct access to the member variables. Although,
in this case, I would probably set your class as immutable. To do
that, set the m_t and m_f as private variables and have a getter
m() and f(). It might be a bad idea to modify an ItemKey
instance in a map after it has been inserted.
Potential problems with this approach
One of the problems you have with your approach here is that it will be dependent on the order in which you add elements. Consider the following pairs to be added: (3.0, 10.0) (5.0, 10.0) (7.0, 10.0). If we add them in that order, we will get (3.0, 10.0) (7.0, 10.0), since (5.0, 10.0) was deemed to be equal to (3.0, 10.0). But what if we were to have inserted (5.0, 10.0) first, then the other two? Well then the list would only have one element, (5.0, 10.0), since bother of the others would be considered equal to this one.
Instead, I would like to suggest that you use std::multiset instead, of course this will depend on your application. Consider these tests:
void simple_test_map() {
std::map<ItemKey, size_t> counter1;
counter1[{3.0, 10.0}] += 1;
counter1[{5.0, 10.0}] += 1;
counter1[{7.0, 10.0}] += 1;
for (auto &itempair : counter1) {
std::cout << "simple_test_map()::counter1: ("
<< itempair.first.m_t << ", "
<< itempair.first.m_f << ") - "
<< itempair.second << "\n";
}
std::cout << std::endl;
std::map<ItemKey, size_t> counter2;
counter2[{5.0, 10.0}] += 1;
counter2[{3.0, 10.0}] += 1;
counter2[{7.0, 10.0}] += 1;
for (auto &itempair : counter2) {
std::cout << "simple_test_map()::counter2: ("
<< itempair.first.m_t << ", "
<< itempair.first.m_f << ") - "
<< itempair.second << "\n";
}
std::cout << std::endl;
}
This outputs:
simple_test_map()::counter1: (3, 10) - 2
simple_test_map()::counter1: (7, 10) - 1
simple_test_map()::counter2: (5, 10) - 3
And for the multiset variant:
void simple_test_multiset() {
std::multiset<ItemKey> counter1 {{3.0, 10.0}, {5.0, 10.0}, {7.0, 10.0}};
for (auto &item : counter1) {
std::cout << "simple_test_multiset()::counter1: ("
<< item.m_t << ", "
<< item.m_f << ")\n";
}
std::cout << std::endl;
std::multiset<ItemKey> counter2 {{5.0, 10.0}, {3.0, 10.0}, {7.0, 10.0}};
for (auto &item : counter2) {
std::cout << "simple_test_multiset()::counter2: ("
<< item.m_t << ", "
<< item.m_f << ")\n";
}
std::cout << std::endl;
std::cout << "simple_test_multiset()::counter2.size() = "
<< counter2.size() << std::endl;
for (auto &item : counter1) {
std::cout << "simple_test_multiset()::counter2.count({"
<< item.m_t << ", "
<< item.m_f << "}) = "
<< counter1.count(item) << std::endl;
}
std::cout << std::endl;
}
This outputs
simple_test_multiset()::counter1: (3, 10)
simple_test_multiset()::counter1: (5, 10)
simple_test_multiset()::counter1: (7, 10)
simple_test_multiset()::counter2: (5, 10)
simple_test_multiset()::counter2: (3, 10)
simple_test_multiset()::counter2: (7, 10)
simple_test_multiset()::counter2.count({3, 10}) = 2
simple_test_multiset()::counter2.count({5, 10}) = 3
simple_test_multiset()::counter2.count({7, 10}) = 2
simple_test_multiset()::counter2.size() = 3
Note that count() here returns the number of elements within the multiset that are considered equal to the ItemKey passed in. This may be advantageous for situations where you want to ask "how many of my points are within my tolerance of a new point?"
Good luck!

Obtaining smallest key in a std::map

I need to get the smallest element in a std::map. I'm aware that there is plenty of documentation available; however, I can't seem to get any to work.
I have two maps, bid and ask, both of which are properties of the Book class. Each is a map of queues. Each of these queues hold Order objects (which have various properties like price, volume, etc.). I have a member function update which obtains the best bid, best ask, and the spread:
void update(void)
{
unsigned long long highest_bid, lowest_ask = 0;
for (std::map<unsigned long long, queue<Order>>::iterator it = this->bid.begin(); it != this->bid.end(); ++it)
{
highest_bid = it->first;
}
// best ask code here
this->bestBid = highest_bid;
this->bestAsk = lowest_ask;
this->spread = labs(this->bestAsk - this->bestBid);
}
Where the ask code is, I've tried the following:
lowest_ask = this->ask.begin()->first;
This compiles, but when I debug it throws an assertion failure (which I've read up on other questions here and can't seem to understand):
Expression: map/set iterator not dereferencable
I've tried reverse iteration:
for(std::map<unsigned long long, queue<Order>>::reverse_iterator rit = this->ask.rbegin(); rit != this->ask.rend(); ++rit)
{
lowest_ask = rit->first;
}
Which compiles and debugs fine, but lowest_ask is always 0, which is wrong. When I step through it in the debugger it doesn't stop until it reaches zero.
I've tried swapping the iterators around:
for(std::map<unsigned long long, queue<Order>>::reverse_iterator rit = this->ask.rend(); rit != this->ask.rbegin(); ++rit)
{
lowest_ask = rit->first;
}
This compiled fine, but once again threw the debug assertion failure.
I could continue on and on on what I've tried, but this question is already over-complicated. I just don't understand why I can't just do what I did at the start (lowest_ask = this->ask.begin()->first).
Thank you very much in advance.
Iterating through the map and always assigning the same variable seems like needlessly hard work.
If you need to access the first item in the map (or the last item in the map) then begin() (or rbegin()) is all you need.
std::map <int, int> themap;
themap[4] = 1;
themap[2] = 2;
themap[1] = 3;
themap[6] = 4;
themap[5] = 5;
themap[7] = 6;
if (!themap.empty())
{
std::cout << "item[" << themap.begin()->first << "] = " << themap.begin()->second << std::endl;
std::cout << "item[" << themap.rbegin()->first << "] = " << themap.rbegin()->second << std::endl;
}
the only time you need to be careful with begin and rbegin is when your map is empty
I think you may just need to check that your containers are not empty so that begin() and rbegin() return something meaningful (defined).
Try this:
void update(void)
{
if(bid.empty() || ask.empty())
return;
// best ask code here
this->bestBid = bid.rbegin()->first;
this->bestAsk = ask.begin()->first;
this->spread = labs(this->bestAsk - this->bestBid);
}
This is not "complicated"; it simply takes some standard debugging measures
#include <map>
#include <iostream>
#include <algorithm>
#include <random>
#include <string>
#include <queue>
namespace mock {
using Order = std::string;
struct Book {
using key_type = unsigned long long;
using order_queue_type = std::queue<Order>;
using property_type = std::map<key_type, order_queue_type>;
property_type bids, asks;
void diagnose(const property_type& prop) {
for (auto it = prop.cbegin(); it != prop.cend(); ++it) {
std::clog << "\t" << it->first << '\n';
}
}
void diagnose() {
std::clog << "bids:" << '\n';
diagnose(bids);
std::clog << "asks:" << '\n';
diagnose(asks);
}
Book() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<key_type> ba_dist(0, 1000);
std::uniform_int_distribution<std::size_t> len_dist(0, 10);
auto prop_gen = [&] (property_type& prop) {
auto count = len_dist(gen);
for (std::size_t i = 0; i < count; ++i) {
auto val = ba_dist(gen);
auto pair = prop.emplace(val, order_queue_type());
if (!pair.second) {
std::clog << val << " already present" << '\n';
}
}
};
prop_gen(bids);
prop_gen(asks);
}
};
}
int main() {
mock::Book book;
book.diagnose();
}
Instead of the generator in my Book ctor, use your init routines, of course, and your Order type.

Insert into boost::BIMAP using BOOST::associative property map ... failed

With reference to my previously asked question about boost::bimaps and boost associative property maps interface here, I want to use Put and Get helper functions for my bimap.
With reference to a sample code given here, I tried to add the following and i get a long compile error for assertion failed ... Here is the code :
#include <boost/bimap.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/bimap/property_map/set_support.hpp>
#include <iostream>
using namespace boost;
int main()
{
typedef int vertex_descriptor_t;
typedef boost::bimaps::bimap< vertex_descriptor_t, size_t > vd_idx_bimap_t;
typedef boost::associative_property_map<vd_idx_bimap_t::left_map> asso_vd_idx_bimap_t;
// define bimap
vd_idx_bimap_t my_bimap;
asso_vd_idx_bimap_t my_asso_bimap(my_bimap.left);
typedef typename vd_idx_bimap_t::value_type value_type;
my_bimap.insert( value_type( 1, 100 ) );
// print bimap
for(auto t = my_bimap.left.begin(); t != my_bimap.left.end(); ++t)
std::cout << t->first << " " << t->second << "\n";
int z = 1;
std::cout << "value = " << get ( my_bimap.left, z ) << std::endl; // prints correctly value = 100
// ERROR here .
boost::put( my_asso_bimap, 2, 19 );
}
It gives error as: ( a long list. but i have just put a snippet )
cannot convert âboost::bimaps::detail::non_mutable_data_unique_map_view_access<Derived, Tag, BimapType>::operator[](const CompatibleKey&)::BIMAP_STATIC_ERROR__OPERATOR_BRACKET_IS_NOT_SUPPORTED360::assert_arg<long unsigned int>()â (type âmpl_::failed************ (boost::bimaps::detai
There is also one error which gives me error at line number 364 of the file (property_map.hpp) in boost
put(const put_get_helper<Reference, PropertyMap>& pa, K k, const V& v)
{
static_cast<const PropertyMap&>(pa)[k] = v;
}
I understand the error that associative map cannot mutate the data as it references to the left map view . but How do I use put and get helper functions ?
I can use GET (my_bimap.left, z ) functions, but I am not able to use PUT function. I wanted to use associative property map for get and put functions to operate on actual bimap so that i dont have to use insert( value_type() )...
I hope I am clear enough for my problem. Please suggest.
In general you cannot update bimap entries via iterators:
The relations stored in the Bimap will not be in most cases modifiable directly by iterators because both sides are used as keys of key-based sets. When a bimap left view iterator is dereferenced the return type is signature-compatible with a std::pair< const A, const B >.
So there's your answer. Likewise, you couldn't
my_bimap.left[2] = 19;
http://www.boost.org/doc/libs/release/libs/bimap/doc/html/boost_bimap/the_tutorial/differences_with_standard_maps.html#boost_bimap.the_tutorial.differences_with_standard_maps.iterator__value_type
Now, reading a bit more on there leads me to "suspect" the following solution:
typedef bm::bimap< vertex_descriptor_t, bm::list_of<size_t> > vd_idx_bimap_t;
Disclaimer: I don't know about the semantics that this changes (?) but it at least appears to support writable references. The below sample prints
1 100
value = 100
1 100
2 42
See it Live On Coliru
Full Listing
#include <boost/bimap.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/bimap/property_map/set_support.hpp>
#include <boost/bimap/list_of.hpp>
#include <iostream>
using namespace boost;
int main()
{
typedef int vertex_descriptor_t;
namespace bm = boost::bimaps;
typedef bm::bimap< vertex_descriptor_t, bm::list_of<size_t> > vd_idx_bimap_t;
typedef boost::associative_property_map<vd_idx_bimap_t::left_map> asso_vd_idx_bimap_t;
// define bimap
vd_idx_bimap_t my_bimap;
asso_vd_idx_bimap_t my_asso_bimap(my_bimap.left);
typedef typename vd_idx_bimap_t::value_type value_type;
my_bimap.insert( value_type( 1, 100 ) );
// print bimap
for(auto t = my_bimap.left.begin(); t != my_bimap.left.end(); ++t)
std::cout << t->first << " " << t->second << "\n";
int z = 1;
std::cout << "value = " << get ( my_bimap.left, z ) << std::endl; // prints correctly value = 100
boost::put( my_asso_bimap, 2, 42 );
for(auto t = my_bimap.left.begin(); t != my_bimap.left.end(); ++t)
std::cout << t->first << " " << t->second << "\n";
}

C++ class specialiation when dealing with STL containers

I'd like a function to return the size in bytes of an object for fundamental types. I'd also like it to return the total size in bytes of an STL container. (I know this is not necessarily the size of the object in memory, and that's okay).
To this end, I've coded a memorysize namespace with a bytes function such that memorysize::bytes(double x) = 8 (on most compilers).
I've specialized it to correctly handle std::vector<double> types, but I don't want to code a different function for each class of the form std::vector<ANYTHING>, so how do I change the template to correctly handle this case?
Here's the working code:
#include <iostream>
#include <vector>
// return the size of bytes of an object (sort of...)
namespace memorysize
{
/// general object
template <class T>
size_t bytes(const T & object)
{
return sizeof(T);
}
/// specialization for a vector of doubles
template <>
size_t bytes<std::vector<double> >(const std::vector<double> & object)
{
return sizeof(std::vector<double>) + object.capacity() * bytes(object[0]);
}
/// specialization for a vector of anything???
}
int main(int argc, char ** argv)
{
// make sure it works for general objects
double x = 1.;
std::cout << "double x\n";
std::cout << "bytes(x) = " << memorysize::bytes(x) << "\n\n";
int y = 1;
std::cout << "int y\n";
std::cout << "bytes(y) = " << memorysize::bytes(y) << "\n\n";
// make sure it works for vectors of doubles
std::vector<double> doubleVec(10, 1.);
std::cout << "std::vector<double> doubleVec(10, 1.)\n";
std::cout << "bytes(doubleVec) = " << memorysize::bytes(doubleVec) << "\n\n";
// would like a new definition to make this work as expected
std::vector<int> intVec(10, 1);
std::cout << "std::vector<int> intVec(10, 1)\n";
std::cout << "bytes(intVec) = " << memorysize::bytes(intVec) << "\n\n";
return 0;
}
How do I change the template specification to allow for the more general std::vector<ANYTHING> case?
Thanks!
Modified your code accordingly:
/// specialization for a vector of anything
template < typename Anything >
size_t bytes(const std::vector< Anything > & object)
{
return sizeof(std::vector< Anything >) + object.capacity() * bytes( object[0] );
}
Note that now you have a problem if invoking bytes with an empty vector.
Edit: Scratch that. If I remember your previous question correctly, then if you get a vector of strings then you would like to take into account the size taken by each string. So instead you should do
/// specialization for a vector of anything
template < typename Anything >
size_t bytes(const std::vector< Anything > & object)
{
size_t result = sizeof(std::vector< Anything >);
foreach elem in object
result += bytes( elem );
result += ( object.capacity() - object.size() ) * sizeof( Anything ).
return result;
}