- #1
- 4,616
- 37
C++ container class help
Hi, I'm working on a templated container class called "bag" and running into some trouble. This my header file, bagTemplate.h
And this is my template file, bag.template:
Here is my driver:
When I run this, "test 1" prints, but "test 2" does not. It must be something simple I'm missing, as usual. I am not getting any error messages.
Any help is appreciated. I'm using VS C++ 6 at the moment. Will be trying it in VS C++ .NET 2003 when I get home.
tanx!
Hi, I'm working on a templated container class called "bag" and running into some trouble. This my header file, bagTemplate.h
Code:
#ifndef BAGTEMPLATE_H
#define BAGTEMPLATE_H
template <typename T>
class bag {
public:
bag(int num=10); // construct a bag to hold num elements
~bag( ); // destructor
int size(); //returns current size
int count(const bag<T> & target) const;//counts # items of certain value in bag
void insert (const bag<T> & new_item); //add one item to the bag, double cap if cap exceeded
private:
int used; // size, or number of elements currently stored in the bag
int capacity; // the maximum capacity of the bag
bag <T> * container; // internal storage array of pointers to items
};
#include "Bag.template"
#endif
Code:
#include <iostream>
#include <stdlib.h>
using namespace std;
// constructor builds a bag with the ability to hold
// capacity items; the bag is initially empty
template <typename T>
bag<T> :: bag(int num)
{
capacity = num;
used = 0;
container = new bag<T> [num];
}
// destructor destroys the bag by recycling the memory it used
template <typename T>
bag<T> :: ~bag( )
{
delete [ ] container;
}
template <typename T>
int bag<T>::size()
{
return used;
}
template <typename T>
int bag<T>::count(const bag<T> & target) const
{
int ct = 0;
for (int i = 0; i < used; i++)
{
if (target == container[i])
c++;
}
return ct;
}
template <typename T>
void bag<T>::insert (const bag<T> & new_item)
{
if (used == capacity)
capacity = capacity * 2;
container[used ++] = new_item;
}
Code:
#include "bagTemplate.h"
#include <iostream>
using namespace std;
int main()
{
cout << "test 1";
bag<int> b;
cout << "test 2";
return 0;
}
Any help is appreciated. I'm using VS C++ 6 at the moment. Will be trying it in VS C++ .NET 2003 when I get home.
tanx!
Last edited: