Subject: segmentation fault with vector |
Author:
dottv
|
[
Next Thread |
Previous Thread |
Next Message |
Previous Message
]
Date Posted: 03:38:52 10/22/02 Tue
Hi all ,
I meet a problem when I use 2-d vector, that is "vector",
SpVector is link-like sparse vector. When I run the program, it comes
"segmentation fault" error, I think it's memory allocation problem,
when I change the j-loop from 50 to 5, it's ok, but the content stored
in "candidates" is not the same what it should be. I can't find out
the problem, hopefully you can give me some clue or good solution
the such a question.
Thanks
------------------------------------------------------------------
#include
#include
#include
class Node {
public:
Node* next;
float value;
int index;
Node(int i, float h, Node* t);
ostream& printTo(ostream& os) const;
};
Node::Node(int i, float h, Node* t) {
index = i;
value = h;
next = t;
};
ostream& Node::printTo(ostream& os) const {
return os << "<" << index << ", " << value << ">";
}
ostream& operator<< (ostream &os, const Node& v) {
return v.printTo(os);
}
class SpVector {
private:
int numNodes;
Node* firstNode;
Node* lastNode;
public:
SpVector ();
SpVector(Node* f, Node * l, int n);
~SpVector ();
Node& operator[](int n);
void addNode(int index, float value);
ostream& printTo(ostream& os) const;
};
ostream& operator<< (ostream &os, const SpVector& v) {
return v.printTo(os);
}
SpVector::SpVector(Node* f, Node * l, int n) {
numNodes=n;
firstNode = f;
lastNode= l;
};
SpVector::SpVector () {
numNodes = 0;
firstNode = lastNode = NULL;
}
SpVector::~SpVector () {
Node *prevEltPtr, *eltPtr;
eltPtr = firstNode;
numNodes = 0;
firstNode=lastNode= NULL;
while (eltPtr != NULL) {
prevEltPtr = eltPtr;
eltPtr = eltPtr->next;
delete prevEltPtr;
};
};
void SpVector::addNode(int index, float value){
Node* e;
Node* newPtr = new Node(index, value, NULL);
if (value != 0.0 ) {
this->numNodes++;
if (this->firstNode == NULL){
this->firstNode = newPtr;
this->lastNode = newPtr;
}else{
e=this->lastNode;
e->next = newPtr;
this->lastNode = newPtr;
}
}
}
ostream& SpVector::printTo(ostream& os) const {
if (numNodes == 0)
return (os << "empty vector");
else {
os << "{" ;
Node* eltPtr = firstNode;
while (eltPtr != NULL) {
os << *eltPtr;
eltPtr = eltPtr->next;
if (eltPtr != NULL) os << ", ";
};
os << "}" << endl;
return os;
}
}
main(){
vector candidates;
candidates.reserve(20);
for(int i=0; i<20; i++){
SpVector sv;
for(int j=0; j<50; j++){
sv.addNode( j, j+1);
}
candidates.push_back(sv);
}
vector::iterator it;
for(it=candidates.begin(); it!=candidates.end(); ++it){
cout << *it << endl;
}
}
[
Next Thread |
Previous Thread |
Next Message |
Previous Message
]
| |