I am trying to write a code in c++ while hashing. For that I am trying to push strings in a vector of vectors. But it is showing a segmentation fault.
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,ind,inr;
cin >> n;
int j=0;
vector<string> a;
vector<vector <string>> v(n);
for(int i=0;i<n;i++)
{
v.push_back(a);
}
for(int i=0;i<n;i++)
{
int m;
string name;
cin>>m;
cin>>name;
ind=m%2039;
v[ind][j]=name;
j=0;
cout<<name<<endl;
}
}
For starters neither of sub-vectors of the vector v
has elements.
In this declaration
vector<vector <string>> v(n);
there is declared a vector with n empty sub-vectors.
Then in this loop
for(int i=0;i<n;i++)
{
v.push_back(a);
}
you are appending one more n empty sub-vectors to the vector v
. As a result the vector v
has 2 * n empty sub-vectors.
In this statement
ind=m%2039;
there is used a magic number 2039
. The result of the expression
m%2039
can be greater than or equal to 2 * n.
So in this statement
v[ind][j]=name;
using the both indices (especially for empty sub-vectors of the vector v) results in undefined behavior.
Instead of a vector of sub-vectors you could use ths standard container std::map declared for example like
std::map<unsigned int, std::vector<std::string>> m;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.