Hi. I have a vector of pointers. When I try to return v[i] from the following function and then try to output the values to the console, the program crashes.
However, once I do this:Code:Huff* findMinimum(vector<Huff*>& v) { int i, minCo=v[0]->count; char minCh=v[0]->ch; for(i=1; i<v.size(); i++) { if(v[i]->count < minCo) { minCo=v[i]->count; minCh=v[i]->ch; } } return v[i]; }
The program will output the values fine? Isn't v[i] a pointer? I'm baffled. Thanks, SteveCode:Huff* findMinimum(vector<Huff*>& v) { int i, minCo=v[0]->count; char minCh=v[0]->ch; Huff* h3; for(i=1; i<v.size(); i++) { if(v[i]->count < minCo) { minCo=v[i]->count; minCh=v[i]->ch; h3=v[i]; } } return h3; }
Code:#include<iostream> #include<string> #include<vector> #include<fstream> #include<stack> using namespace std; struct Huff; Huff* findMinimum(vector<Huff*>& v); struct Huff { Huff(); int count; char ch; Huff* left; Huff* right; Huff* parent; }; int main(int argc, char* argv[]) { if(argc<2) { cout<<"Not enough arguments were provided."<<endl; return -1; } ifstream myFile(argv[1], ios::in); if(!myFile.is_open()) { cout<<"Unknown file specified."<<endl; return -1; } char cz; int i; vector<Huff*> values; while(myFile.get(cz)) { if(cz < 'a' || cz > 'z') continue; for(i=0; i<values.size(); i++) { if(values[i]->ch == cz) { values[i]->count++; break; } } if(values.size()==i) { Huff* h = new Huff; h->ch=cz; h->count=1; values.push_back(h); } } for(i=0; i<values.size(); i++) cout<<values[i]->ch<<values[i]->count<<endl; Huff* h2; h2=findMinimum(values); cout<<h2->ch<<endl; cout<<h2->count<<endl; return 0; } Huff::Huff() : ch(0), count(0) { } Huff* findMinimum(vector<Huff*>& v) { int i, minCo=v[0]->count; char minCh=v[0]->ch; Huff* h3; for(i=1; i<v.size(); i++) { if(v[i]->count < minCo) { minCo=v[i]->count; minCh=v[i]->ch; h3=v[i]; } } return h3; }



LinkBack URL
About LinkBacks


