Given an array of strings, I am writing a class to separated them into different groups according to their length, i.e. the ones of same length goes to the same group. The number of groups and the size of each group are unknown.
My idea is following: I use a private data member std::vector<std::vector<std::int> > m_groups, with the intention that the outer vector maintains the groups, and the inner vector tracks all the indices of strings belong to one group.
The problem is, once I push strings into the vector, some of my data members are corrupted. Could anyone please have a look?
Here is the simplified code:
class A {
public:
A(std::string words[], int num, int c1[], int m, int c2[], int n);
~A();
void print_state();
private:
int *m_var;
int m_Nvar;
std::vector<std::vector<std::int> > m_doms;
std::vector<std::vector<std::int> > m_groups;
std::vector<std::string> > m_words;
int *m_cst1;
int *m_cst2;
int m_Ncst;
};
in the constructor:
CwordSolver::CwordSolver(std::string words[], int num,
int c1[], int m, int c2[], int n) {
...
// we are only interested, the words of length smaller than m_max_len
// put m_max_len number of empty vectors (groups) in the group vector
for (int i = 0; i < m_max_len; i++)
{
m_groups.push_back(std::vector<int>());
}
// go through every words and copy words of interest to m_words
// push the index of the word to the group it belongs to (by its length)
for (int i = 0, k = 0; i < num; i++, k++)
{
int len = words[i].length();
if (len > m_max_len)
continue;
m_words.push_back(words[i]);
m_groups[len].push_back(k);
}
// you can ignore this part: link the group to another structure
for (int i = 0; i < m_Nvar; i++)
{
m_doms.push_back(m_groups[m_cst1[i]]);
}
...
}
...
I compiled the code and run. The data in the end of array m_cst2 gets corrupted. This seems connected to the use of std::vector. Someone (comingstorm) in the thread (Two-Dimensional vector in C++ – inefficient with dynamic-sized sub vectors?) provided an interesting clue: the outer std::vector stores an array of fixed-size std::vector datastructures in its heap allocation.. Is that the answer? Not sure though. So, post this and ask for suggestions.
PS: if you have a better idea to do this task, please do tell me ... if you need more information, please post.
I appreciate your time.
Aucun commentaire:
Enregistrer un commentaire