Segmentation fault(vector)


Well, I want to do a vector of strings ordered alphabetical while I am writing the data, but when I put the second string it says Segmentation Fault :'(
Can anyone help me?

Code:
------------------------------------------------------------------------------


#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;



int main()
{
int n = 0;
vector<string> v(n);
string e;
while(cin>>e){
bool nomespetit = false;
if(n != 0){
for(int i = 0; i < n; ++i){
if(e <= v[i]){
++n;
for(int j = n-1; j > i; --j){
v[j] = v[j-1];
}
v[i] = e;
i = n-1;
nomespetit = true;
}
}
if(nomespetit == false){
++n;
v.push_back(e);
}
}
else {
++n;
v.push_back(e);
}
}
for(int r = 0; r < v.size(); ++r){
cout<<v[r]<<endl;
}
}
First of all, please, use code tags.

http://www.cplusplus.com/forum/articles/42672/
Last edited on
1
2
3
4
++n;
for(int j = n-1; j > i; --j){
	v[j] = v[j-1];
}
You are incrementing n before entering a loop that uses n as the size of the vector. So, if before the increment n = v.size(), during the first iteration j = v.size() + 1 - 1 = v.size(), so the assignment does v[v.size()] = v[v.size()-1], which is illegal.
Don't use n. You don't need it. Just use v.size() to get the size of the vector.
I suspect you have an index to v[] that is out of bounds. Since it happens on the second word, it should be easy to find using a debugger.

BTW, I had a hard time trying to follow your program. I strongly recommend using functions to perform operations. It makes your program easier to follow and also easier to debug.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Last edited on
Topic archived. No new replies allowed.