-
Vector of Vectors
How do you traverse through double vectors.
Code:
for(int l = 0; l < myWordsInLetter->size(); l++)
{
for(int m = 0; m < myWordsInLetter->at(l).size(); m++)
{
cout << myWordsInLetter->at(l).at(m);
}
cout << " ";
}
where myWordsInLetter is a vector<vector<string> >
-
Just like that, I suppose. Except if myWordsInLetter is a vector<vector<string> >, you wouldn't ever use ->, but always .
-
It gives me an
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Aborted
when I run it and it is a pointer to that vector
-
Wait here is the problem how do I do this right
Code:
ifstream ifstr(myInputFile.c_str());
if(!ifstr)
{
cerr << "Cannot open: " << myConversionTableFile << "." << endl;
exit(ERROR);
}
string tempstr;
int i = 0;
while(ifstr >> tempstr)
{
for(int k = 0; k < tempstr.size(); k++)
{
myWordsInLetter->at(i).push_back(tempstr);
}
i++;
}
-
Code:
myWordsInLetter->push_back(vector<string>())
Do that before the inner loop.
-
I normally use iterators...
Code:
int main() {
typedef std::vector<std::string> vs;
typedef std::vector<vs> vvs;
vvs *myWordsInLetter;
// Fill point pointer to instance
for ( vvs::iterator outer_iter=myWordsInLetter->begin(); outer_iter!=myWordsInLetter->end(); outer_iter++ ) {
for ( vs::iterator inner_iter=outer_iter->begin(); inner_iter!=outer_iter->end(); inner_iter++ ) {
// do whatever you want with inner iter
std::cout<< *inner_iter << "\n";
}
}
return 0;
}
Well, the outer vector needs to be pushed back too. So using ->at(i) is trying to access memory that's not there. So you're going to have to probably make a temp vector<string> which is filled in the inner for loop, then outside of that you .push_back( temp_vector ).
-
Yes, and this syntax is so much longer and it's so much more unsafe, because dereferencing an invalid iterator is undefined, while using .at is defined.