Reputation: 101
When I try to execute a program that calls my method I get a segmentation fault (core dumped) but I just cannot see the error. Have I made some kind of noob mistake?
#include<map>
#include<vector>
//#include<iostream>
//#include<algorithm>
using namespace std;
template <class T>
class Record{
public:
T item;
int total;
};
template <class T>
class Counter{
public:
map<T, int> m;
void printSummary(){
typename map<T, int>::const_iterator itr;
vector< Record<T> > printlist;
int i = 0;
for( itr = m.begin(); itr != m.end(); ++itr ){
printlist[i].item = (*itr).first;
printlist[i].total = (*itr).second;
i++;
}
Upvotes: 0
Views: 66
Reputation: 2163
You can access
printlist[i]
only if the vector has enough elements. You could use another map to get a container with random access.
Upvotes: 0
Reputation: 121961
printlist
is an empty vector
when the following lines are executed:
printlist[i].item = (*itr).first;
printlist[i].total = (*itr).second;
which results in out of bounds access, causing undefined behaviour and in this case a segmentation fault.
Either use push_back()
or create the vector
with the required number of elements and leave the for
loop as is:
vector< Record<T> > printlist(m.size());
Upvotes: 1