Memory management for 2 "interconnected" C++ classes - c++

I have a class Branch and a class Tree. The declaration of the classes looks like:
class Branch{
private:
map<string, double> properties;
vector<Branch *> parent;
vector<Branch *> children;
int hierarchy;
public:
...
}
class Tree{
private:
/* Tree is a vector of pointers to branches. */
vector<Branch*> tree_branches;
map<int,int> Hierarchy_distribution;
public:
...
}
1) If I understood well, the fact that the only attributes of Tree class are a vector and a map, makes it unnecessary to declare a destructor, a copy-assignement operator and a copy constructor, because the memory is managed "inside" the vector and map templates.
2) I use this classes from a python code (I used cython to interface between C++ an python) and all the operations I make are performed through a tree object. I thought that because the branches I "use" are contained in a tree object (with a good memory management) I didn't need to declare a destructor, a copy constructor,and a copy assignment operator for the branch class. However I'm experiencing some problems and I think I have a memory leak.
Can someone confirm me if this could be causing a memory leak? If it is would stocking the int hierarchy inside a vector<int> avoid declaring a destructor and company?
EDIT
The branches who are stocked in the tree are created inside a method of the Tree class. It looks like:
Tree::addBranch(){
Branch* branch2insert=new Branch();
tree_branches.push_back(branch2insert);
}
As a local variable, is branch2insert destructed at the end of the scope? Do I need to write delete branch2insert;? Does someone have an idea of where do the Branch object at which I point to lives?
I still don't get why I need to ensure memory management when I never allocate ressources except inside the Tree class methods...
This whole thing is getting very messy in my head
EDIT 2:EXAMPLE
branch.h
#ifndef BRANCH_H_
#define BRANCH_H_
#include <memory>
#include <string>
#include <vector>
#include <map>
using namespace std;
class Branch{
private:
vector<Branch*> parent;
vector<Branch*> children;
public:
Branch();
bool hasParent();
bool hasParent(Branch* test);
void addParent(Branch* p);
void removeParent();
Branch* getParent();
bool hasChildren();
bool hasChild(Branch*test);
void addChild(Branch*ch);
void removeChild(Branch*ch);
void removeChildren();
void removeDescendants();
vector<Branch*> getBrothers();
};
#endif
tree.h
#ifndef TREE_H_
#define TREE_H_
#include <vector>
#include <map>
#include"branch.h"
using namespace std;
class Tree{
private:
vector<Branch*> tree_branches;
public:
Tree();
int getNumberOfBranches();
Branch* getBranch(int branch_index); /* Returns branch at index. */
int getIndex(Branch* branch); /* Returns the index of branch. */
int getLastDescendantIndex(int ancestor_index); /* Returns index of the last descendant of branch at ancestor index. */
int getParentIndex(int child_index); /* Returns index of the parent of branch at child_index. */
vector<int> getBrothersIndex(int branch_index); /* Returns indexes of the brothers of branch at branch_index. */
void addBranch(int parent_index); /* Adds branch without initializing its properties. */
void removeBranch(int branch_index); /* Removes branch at branch_index and all its descendants. */
};
#endif
branch.cpp
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <sstream>
#include <map>
#include <stdio.h>
using namespace std;
#include "branch.h"
Branch::Branch():parent(vector<Branch*>()),children(vector<Branch*>())
{
}
bool Branch::hasParent(){
if(parent.size()==0)
return false;
else
return true;
}
bool Branch::hasParent(Branch* test){
bool ret = false;
for(vector<Branch*>::iterator it=parent.begin();it!=parent.end();it++){//traversing parent vector
if((*it)==test){//if test belong to parent vector
ret = true;
break;
}
}
return ret;
}
void Branch::addParent(Branch* mom){
if(parent.size()==0){//if a branch hasn't a parent, multiple parents aren't allowed in a tree-network
if(hasParent(mom)==false){//double checking if mom isn't already a parent
parent.push_back(mom);//adding mom to parent vector
}
else{
cout << "Branch::addParent Error: trying to add a parent twice.\n";
}
}
else{
cout << "Branch::addParent Error: trying to add a parent to a branch that already has one.\n";
}
}
void Branch::removeParent(){
if(this->hasParent()==true){//if this branch has a parent
vector<Branch*>::iterator it=parent.begin();
parent.erase(it);//erase it (it is the first and only element of the vector)
}
else{
cout << "Removing the trunk.\n";
}
}
Branch* Branch::getParent(){
return parent[0];
}
bool Branch::hasChildren(){
if(children.size()==0)
return false;
else
return true;
}
bool Branch::hasChild(Branch* test){
bool ret = false;
for(vector<Branch*>::iterator it=children.begin();it!=children.end();it++){
if((*it)==test){
ret = true;
break;
}
}
return ret;
}
void Branch::addChild(Branch* ch){
if(hasChild(ch)==false){
children.push_back(ch);
ch->addParent(this); // PARENTHOOD LINK ESTABLISHED IN ADD CHILD. ONLY
// NEEDED ONCE.
}
else{
cout << "Branch::addChild Error: trying to add a child but the child has been already added.\n";
}
}
void Branch::removeChild(Branch* ch){
if(hasChild(ch)==true){
for(vector<Branch*>::iterator it=children.begin();it!=children.end();it++){
if((*it)==ch){
children.erase(it);
break;
}
}
}
else{
cout << "Branch::removeChild Error: trying to remove a child that doesn't exist.\n";
}
}
void Branch::removeChildren(){
if(this->hasChildren()==true){
children.erase(children.begin(),children.end());
}
else{
cout << "Branch::removeChildren Error: trying to remove all the children of a branch but tha branch hasn't any.\n";
}
}
void Branch::removeDescendants(){
if (this!=NULL){
if(this->hasChildren()==true){
for(vector<Branch*>::iterator it=children.begin();it!=children.end();it++){
(*it)->removeDescendants();
}
removeChildren();
}
for(vector<Branch*>::iterator it=children.begin();it!=children.end();it++){
(*it)->removeParent();
}
}
}
vector<Branch*> Branch::getBrothers(){
vector<Branch*> brothers;
vector<Branch*> potential_brothers;
if (parent.size()!=0){
potential_brothers=parent[0]->children;
for (vector<Branch*>::iterator it=potential_brothers.begin();it!=potential_brothers.end();it++){
if ((*it)!=this){
brothers.push_back((*it));
}
}
}
return brothers;
}
tree.cpp
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
#include "tree.h"
Tree::Tree():tree_branches(vector<Branch*>()){
Branch* trunk=new Branch();
tree_branches.push_back(trunk);
}
int Tree::getNumberOfBranches(){
int number_of_branches=tree_branches.size(); //retrieving size of vector
return number_of_branches;
}
Branch* Tree::getBranch(int index){
unsigned int u_index=index;
return tree_branches.at(u_index); // returning branch at index of the tree vector
}
int Tree::getIndex(Branch* branch){
int index=0;
for(vector<Branch*>::iterator it=tree_branches.begin();it!=tree_branches.end();it++){
if((*it)==branch){
return index;
}
index++;
}
cout << "Tree::getIndex Error: trying to get the index of a branch we can't find. Returning 0.\n";
return 0;
}
int Tree::getLastDescendantIndex(int ancestor_index){
if(tree_branches.at(ancestor_index)->hasChildren()==false){// if it is a leaf
return ancestor_index;
}
if(ancestor_index==0){// if it is the trunk
int N=tree_branches.size();
int last_descendant_index=N-1;
return last_descendant_index;
}
vector<int> brothers_indexes=Tree::getBrothersIndex(ancestor_index);
for(vector<int>::iterator it=brothers_indexes.begin();it!=brothers_indexes.end();it++){
int brother_index=(*it);
if(brother_index>ancestor_index){
int last_descendant_index=brother_index-1;
cout << "The last descendant of" << ancestor_index << " is "<<last_descendant_index<<"\n";
return last_descendant_index;
}
}
int parent_index=Tree::getParentIndex(ancestor_index);
Tree::getLastDescendantIndex(parent_index);
}
int Tree::getParentIndex(int child_index){
if(child_index==0){ //if considered branch is the trunk
cout << "Tree::getParentIndex: the trunk hasn't a parent. Returning -1.\n";
return -1;
}
unsigned int u_child_index=child_index;
Branch* parent=tree_branches.at(u_child_index)->getParent(); //retrieving the parent of the considered branch
int parent_index=Tree::getIndex(parent);
return parent_index; //returning parent index
}
vector<int> Tree::getBrothersIndex(int branch_index){
vector<int> brothers_index;
Branch* this_branch=Tree::getBranch(branch_index);//retrieving the branch from the index
vector<Branch*> brothers=this_branch->getBrothers();//retrieving branch's brothers
for(vector<Branch*>::iterator it=brothers.begin();it!=brothers.end();it++){ //traversing a vector containing the brothers of the consideered branch
int this_index=Tree::getIndex(*it); //retrieving index of a brother
brothers_index.push_back(this_index); //stocking the index in a vector
}
return brothers_index; //returning the vector containing the index of all brothers
}
void Tree::addBranch(int parent_index){
unsigned int u_parent_index=parent_index;
Branch* mom=tree_branches.at(u_parent_index);//getting futur parent
Branch* branch2insert=new Branch();//creation of branch to insert
mom->addChild(branch2insert);//setting family relationship
vector<Branch*>::iterator begin=tree_branches.begin();//creating iterators to manipulate vector elements
unsigned int inserting_position=u_parent_index+1;//initializing inserting_position
tree_branches.insert(begin+inserting_position,branch2insert);//inserting new branch
}
void Tree::removeBranch(int branch_index){
int N=tree_branches.size();
unsigned int u_branch_index=branch_index;
Branch* branch2remove=tree_branches.at(u_branch_index);
branch2remove->removeParent(); //removing parenthood link, if branch2remove is the trunk nothing will be done
if(branch_index!=0){//removing childhood link between parent and branch_index
Branch* branch2removeParent=branch2remove->getParent();
branch2removeParent->removeChild(branch2remove);
}
int last_descendant_index=Tree::getLastDescendantIndex(branch_index);
cout<<"The branch to remove is "<<branch_index<<", its last descendant index is "<<last_descendant_index<<", the size of the tree is "<<N<<".\n";
branch2remove->removeDescendants();//removing family links for all descendents
if(last_descendant_index==N-1){
vector<Branch*>::iterator begin=tree_branches.begin();
tree_branches.erase(tree_branches.begin()+u_branch_index,tree_branches.end());
}
else{
vector<Branch*>::iterator begin=tree_branches.begin();
unsigned int u_last_descendant_index=last_descendant_index;
tree_branches.erase(tree_branches.begin()+u_branch_index,tree_branches.begin()+u_last_descendant_index+1);//removing the considered branch and its descendents from the tree vector
}
}
test.cpp
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <typeinfo>
#include <vector>
#include <map>
#include <string>
#include "tree.h"
using namespace std;
int main(){
Tree tree;
tree=Tree();
for(int i=0;i<5;i++){
int N=tree.getNumberOfBranches();
for(int j=0;j<N;j++){
tree.addBranch(j);
tree.addBranch(j);
}
}
tree.removeBranch(21);
tree.removeBranch(30);
tree.removeBranch(50);
return 0;
}
to compile:
g++ -Wall -pedantic -c

1) If I understood well, the fact that the only attributes of Tree class are a vector and a map, makes it unnecessary to declare a destructor, a copy-assignement operator and a copy constructor, because the memory is managed "inside" the vector and map templates.
You are wrong here, as the memory which is managed inside the vector is only the storage for the addresses of branches(Branch *). When you insert some branch you call something like tree_branches.push_back(new Branch), don't you? Thus, you will need to call the corresponding delete somehow, otherwise the default destructor of the tree won't take care of calling the destructors of the Branches.
A quick fix for your code could be switching from Branch * to shared_ptr<Branch>. In such way, when the tree_branches vector is destroyed, the shared_ptr's will also be destroyed and when the latest shared_ptr to any Branchis destroyed, also the pointed Branch will be.
would stocking the int hierarchy inside a vector avoid declaring a destructor and company?
It would change jack squat, as the Branches default destructors still would not be called, and so the destructors of the Branches members would never be called.

Finnally there isn't a memory leak. Thanks #Yunnosch for mentionning Valgrind, I wasn't aware this kind of tool existed.
#Davide I accepted your answer since it provided an alternative to what I've done, even if apparently there aren't problems with the management of the memory in my code.
The code I posted has a problem in function Tree::getLastDescendantIndex.

Related

Pointer to Pointer to Structure (Priority Queue)

I'm a beginner (in C++, I'm coming from C (6 months experience)) and I'm trying to create a priority queue, but something is not working.
When I start the program and compile it, there are no errors. But there is nothing printed on the screen and the program crashes.
So here is the code:
PriorityQueue.h
using namespace std;
class PriorityQueue{
private:
struct pqentry_t{
string value;
float priority;
};
pqentry_t **_pqentry;
int _size;
int _next;
public:
PriorityQueue();
~PriorityQueue();
void insert(string value, float priority);
void printQueue();
};
PriorityQueue.cpp
#include <iostream>
#include <string>
#include "PriorityQueue.h"
#define SIZE 8
using namespace std;
PriorityQueue::PriorityQueue(){
_size = SIZE;
_next = 0;
_pqentry = new pqentry_t*[_size];
}
PriorityQueue::~PriorityQueue(){
delete[] _pqentry;
}
void PriorityQueue::insert(string value, float priority){
_pqentry[_next]->value = value; // this is probably not working
_pqentry[_next]->priority = priority;
_next++;
}
void PriorityQueue::printQueue(){
for (int i = 0; i < _next; i++){
cout << "Value: " << _pqentry[i]->value << endl
<< "Priority: " << _pqentry[i]->priority << endl;
}
cout << endl;
}
main.cpp
#include <iostream>
#include <string>
#include "PriorityQueue.h"
using namespace std;
int main()
{
PriorityQueue pq;
pq.insert("Banana", 23);
pq.printQueue();
}
I think, I know where the error is, in the PriorityQueue.cpp, here:
_pqentry[_next]->value = value;
_pqentry[_next]->priority = priority;
But I don't know what's wrong and I can't fix it. The compiler says there are no errors.
I hope, you can help me. Thanks in advance!
You did allocate the _pqentry member but you need to allocate each entry of this array as well, for example:
_pqentry[_next] = new pqentry_t;
before writing to it.
And do not forget to delete those :)
It looks like you are creating an array of pointers to pqentry_t in your constructor, but your insert method is expecting it to be an array of _pqentry structures themselves. You are not allocating space for the pqentry_t elements themselves and so when you try to dereference them in your insert method, the program crashes.
Try changing the definition of _pqentry in the class to pqentry_t *_pqentry and the allocation in the constructor to new pqentry_t[size]. This will allow your insert and printQueue methods to access the entries of _pqentry as they are written.

When base class wants to access member of an inherited class

this is my situation:
I am writing a data structure in C++ which consists of Nodes and Edges.
Nodes are connected to other nodes by means of edges.
I have different types of nodes, such as text nodes, or int nodes.
Text nodes are connected to text nodes and int nodes are connected to int nodes.
I am using inheritance to implement the different types of nodes because it makes sense:
fundamentally, all nodes are connected to other nodes so Node is the base class,
and TxtNode, IntNode are inherited classes which share the fundamental property of a node.
However, this gives me problems when I try to fetch a connected inherited node from an inherited node, because the fetching function (function which retrieves a specific node connected to the calling node) is defined in the base class Node. For example, calling this fetch function from TextNode returns me the base version of the TextNode, which lacks extra information.
I am not sure what would be the sensible coding practice to do here.
I chose to code it this way because it didn't seem to make sense that I must define a different connection fetch function for all different types of nodes.
Please let me know if there is any more information I can disclose.
Here is my code, I am trying to print an inherited node's partner but it will result in printing the base node.
Node.cpp
#include "Node.h"
#include "Edge.h"
#include "common.h"
#include <vector>
#include <cassert>
#include <cstddef>
#include <stdint.h>
#include <iostream>
Node::Node() {
id = (intptr_t)this;
edges.clear();
}
int Node::connect(Node* dst) {
// establish link between calling node
// and dst node, first linkage will
// edge between each other, links after
// increments strength. returns number of
// links
// fetch edge connecting this node and
// dst node
Edge* edge = findDstEdge(dst);
// if the branch isn't established yet,
// then make connection
if (edge==NULL) {
establishConnection(dst, 1);
return 0;
} else {
edge->strengthenConnection();
return 1;
}
}
Edge* Node::findDstEdge(Node* dst) {
// fetches edge corresponding
// to destination node
// walk through vector of edges to find
// edge connecting to dst
vector<Edge*>::iterator iter = edges.begin();
while(iter!=edges.end()) {
Edge* e = *iter;
Node* partner = e->getPartner(this);
if (partner->getID() == dst->getID())
return e;
iter++;
}
// not found
return NULL;
}
void Node::establishConnection(Node* dst, int str) {
// low level node addition
// establish a new edge between
// nodes which don't know each other
Edge* e = new Edge(this, dst, str);
this->manuallyConnect(e);
dst->manuallyConnect(e);
}
void Node::manuallyConnect(Edge* e) {
edges.push_back(e);
}
ostream& operator<<(ostream& stream,Node n) {
vector<Edge*>::iterator iter = n.edges.begin();
while(iter!=n.edges.end()) {
Edge* e = *iter;
stream << *e << endl;
iter++;
}
return stream;
}
Node.h
#ifndef _NODE_H_
#define _NODE_H_
#include "common.h"
#include <vector>
#include <string>
#include <stdint.h>
class Edge;
using namespace std;
class Node {
protected:
vector<Edge*> edges;
intptr_t id;
public:
Node();
// manipulation
void establishConnection(Node* dst,
int str);
int connect(Node* dst);
Edge* findDstEdge(Node* dst);
// fetchers
intptr_t getID() {return id;}
vector<Edge*> getEdges() {return edges;}
void manuallyConnect(Edge* e);
friend ostream& operator<<(ostream& stream, Node n);
};
#endif
TxtNode.cpp
#include "TxtNode.h"
#include "Edge.h"
#include "common.h"
#include <iostream>
TxtNode::TxtNode(char c): Node() {
_c = c;
}
ostream& operator<<(ostream& stream, TxtNode tn) {
// print out character of this TxtNode
stream << "char: " << tn._c << endl;
stream << "id: " << tn.id << endl;
// print out all connections and its
// strength
vector<Edge*>::iterator iter = tn.edges.begin();
while(iter!=tn.edges.end()) {
Edge* e = *iter;
stream << *e << endl;
iter++;
}
return stream;
}
Edge.cpp
#include "Edge.h"
#include "Node.h"
#include "common.h"
#include <cassert>
#include <iostream>
using namespace std;
Edge::Edge(Node* a, Node* b, int str) {
node_a = a;
node_b = b;
strength = str;
}
void Edge::strengthenConnection() {
strength++;
}
Node* Edge::getPartner(Node* src) {
uint src_ID = src->getID();
if (node_a->getID() == src_ID)
return node_b;
else if (node_b->getID() == src_ID)
return node_a;
assert(false);
}
ostream& operator<<(ostream& stream, Edge e) {
stream << "strength: "
<< e.strength
<< endl;
stream << "node_a: "
<< e.node_a->getID()
<< endl;
stream << "node_b: "
<< e.node_b->getID()
<< endl;
return stream;
}
Currently I just have the code to print the ID which is an intptr_t,
because I found out that I can't access inherited class's member from base class.
I am inclined to access the inherited class's member from base class because the edge class deals with base node class.
The classes code would've been a nice to have.
From what you are telling you don't declare the fetch function virtual.
Here's a very quick example on how virtual / non virtual functions work
class baseNode {
public:
int fetch() { printf "fetched from base";};
}
class intNode : public baseNode {
public:
int fetch() { printf "fetched from derived int";};
}
class txtNode : public baseNode {
public:
int fetch() { printf "fetched from derived txt";};
}
The following code
baseNode * ptr = new intNode();
ptr->fetch();
Will print "fetched from base"
But if you declare the fetch function virtual :
class baseNode {
public:
virtual int fetch() { printf " fetched from base";};
}
Then the same code will print "fetched from derived int".
You write
“ Text nodes are connected to text nodes and int nodes are connected to int nodes.
Then you can very simply define Node_ as a class template:
template< class Value >
struct Node_
{
vector<Node_*> connected_nodes;
Value value;
};
In other words, use compile time polymorphism, not dynamic polymorphism, in order to have the relevant type information available at compile time.
That said, do have a look at Boost.Graph and see if it doesn't suit your needs.

C++ Linked Lists with struct

I'm new in C++ and I have something to do with a linked list, and I don't know why it doesn't work, need help from a prof :O)
Here's my .h
#ifndef UnCube_H
#define UnCube_H
using namespace std;
class ACube{
public:
ACube();
struct Thecube;
private:
void PrintList();
};
#endif
My ACube.cpp
#include <iostream>
#include "ACube.h"
ACube::ACube(){
};
struct Thecube{
int base;
int cube;
Thecube * next ;
};
void ACube::PrintList(){
};
and finally my main.cpp
#include <cstdlib>
#include <iostream>
#include "ACube.h"
using namespace std;
int main()
{
ACube * temp;
temp = (ACube*)malloc(sizeof(ACube));
for (int inc=1; inc <=20 ; inc++){
temp->ACube->nombrebase = inc;
temp->cube = inc*inc*inc;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Everything was working fine, but when I add these lines :
temp->ACube->nombrebase = inc;
temp->cube = inc*inc*inc;
I add error saying :
'class ACube' has no member named 'TheCube'
'class ACube' has no member named 'cube'
Can someone help me because I want to create my list and fill the cube with number.
Other thing I want to use THIS. in the print,
Maybe someone can teach me what's wrong and how to do it !
Thanks for any help
You don't need to have a struct inside your class.
#ifndef UnCube_H
#define UnCube_H
using namespace std;
class ACube{
public:
ACube();
int base;
int cube;
ACube * next ;
private:
void PrintList();
};
#endif
ACube.cpp
#include <iostream>
#include "ACube.h"
ACube::ACube(){
};
void ACube::PrintList(){
};
Also, this string is wrong:
temp->ACube->nombrebase = inc;
it should be just:
temp->base = inc;
Last but not least, this code doesn't create a linked list, because you don't do anything with the ACube::next pointer.
There are so many horrible problems in your code, I suggest you should learn more C++ knowledge before writing linked list.
1. What is nombrebase?
I think nobody can answer.
2. You must allocate C++ class by new key word instead of malloc.
new invokes not only allocation but also class constructor, while malloc allocates only.
3. Thecube should been defined inside ACube
Since the code in your main() refers the member cube in class Thecube, main() must know what it is.
4. The member next in class ACube is a pointer which points to what?
What does a pointer point to without initilization? You should initial it in constructor, and destroy it in destructor.
5. temp->ACube
ACube is a class type, you can access member object, but not a type.
6. Never using namespace into a header file
It would make the client of header file has name collision.
The following is the corrected code. Just no compile error and runtime error, but this is NOT linked list:
ACube.h
#ifndef UnCube_H
#define UnCube_H
class ACube{
public:
struct Thecube
{
int base;
int cube;
Thecube * next;
};
ACube();
~ACube();
Thecube *next;
private:
void PrintList();
};
#endif
ACube.cpp
ACube::ACube()
: next(new Thecube)
{
}
ACube::~ACube()
{
delete next;
}
void ACube::PrintList(){
}
main.cpp
#include <cstdlib>
#include <iostream>
#include "ACube.h"
using namespace std;
int main()
{
ACube * temp;
temp = new ACube;
for (int inc = 1; inc <= 20; inc++)
{
temp->next->base = inc; // <-- This is not linked list, you shall modify.
temp->next->cube = inc*inc*inc; // <-- This is not linked list, you shall modify.
}
system("PAUSE");
return EXIT_SUCCESS;
}

I am stuck with creating an output member function

I am stuck on the output member function of the class. I have no idea how to create it and just simply couting it does not seem to work. also any other advice would be great. thanks in advance
here's the code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class StringSet
{
public:
StringSet(vector<string> str);
void add(string s);
void remove(int i);
void clear();
int length();
void output(ostream& outs);
private:
vector<string> strarr;
};
StringSet::StringSet(vector<string> str)
{
for(int k =0;k<str.size();k++)
{
strarr.push_back(str[k]);
}
}
void StringSet::add(string s)
{
strarr.push_back(s);
}
void StringSet::remove(int i)
{
strarr.erase (strarr.begin()+(i-1));
}
void StringSet::clear()
{
strarr.erase(strarr.begin(),strarr.end());
}
int StringSet::length()
{
return strarr.size();
}
void StringSet::output()
{
}
int main()
{
vector<string> vstr;
string s;
for(int i=0;i<10;i++)
{
cout<<"enter a string: ";
cin>>s;
vstr.push_back(s);
}
StringSet* strset=new StringSet(vstr);
strset.length();
strset.add("hello");
strset.remove(3);
strset.empty();
return 0;
}
Ok, you should begin by solving some errors in your code:
You use a pointer to StringSet and after that you are trying to access the member-functions with the . operator instead of the ->. Anyway, do you really need to allocated your object dynamically ?
StringSet strset(vstr); // No need to allocated dynamically your object
After that, you are calling an empty() method which does not exist...
Also if you stay on dynamic allocation, don't forget to deallocated your memory :
StringSet* strset = new StringSet(vstr);
// ...
delete strset; // <- Important
Finally, I think that your function output should write in the stream the content of your vector, you can do it that way :
#include <algorithm> // For std::copy
#include <iterator> // std::ostream_iterator
void StringSet::output( ostream& outs )
// ^^^^^^^^^^^^^ don't forget the arguments during the definition
{
std::copy(strarr.begin(), strarr.end(), std::ostream_iterator<string>(outs, "\n"));
}
HERE is a live example of your code fixed.
I would suggest you to understan how class works : http://www.cplusplus.com/doc/tutorial/classes/
If your output function is going to print the state of the StringSet object, you may implement is like this:
#include<iterator> //std::ostream_iterator
#include<algorithm> //std::copy
void StringSet::output(ostream& outs)
{
std::copy(starr.begin(), starr.end(), std::ostream_iterator<string>(outs, "\n"));
}

Weird behaviour with STL containers (construction/destruction and scope)

I was unsure about whether STL containers are entirely copied when passed. First, it worked (so the "fluttershy" element didn't get added, that was good). Then I wanted to track the construction and destruction of entries....
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
using namespace std;
int nextid = 0;
class Entry {
public:
string data;
int myid;
Entry(string in) {
data = in;
myid = nextid;
nextid++;
printf("Entry%02d\n", myid);
}
~Entry() { printf("~Entry%02d\n", myid); }
};
class Meep {
public:
vector<Entry> stuff;
};
void think(Meep m) {
m.stuff.push_back(Entry(string("fluttershy")));
}
int main() {
Meep a;
a.stuff.push_back(Entry(string("applejack")));
think(a);
vector<Entry>::iterator it;
int i = 0;
for (it=a.stuff.begin(); it!=a.stuff.end(); it++) {
printf("a.stuff[%d] = %s\n", i, (*it).data.c_str());
i++;
}
return 0;
}
Produces the following unexpected output( http://ideone.com/FK2Pbp ):
Entry00
~Entry00
Entry01
~Entry00
~Entry01
~Entry00
~Entry01
a.stuff[0] = applejack
~Entry00
That a has only one element is expected, that is not the question. What seriously confuses me is how can one entry be destructed several times ?
What you're seeing is the destruction of temporary instances.
a.stuff.push_back(Entry(string("applejack")));
This line creates a temporary instance which is then copied to another new instance in the container. Then the temporary is destroyed. The instance in the container is destroyed when the entry is removed or the container is destroyed.