So I always seem to encounter this error. I usually find some odd hackish fix for it but this time I'm having too much trouble. I'm basically trying to make a program which corrects words the user types in (similar to that of any modern phone). The function I'm posting below is an attempt to make a vector of vectors. I am associating every letter with it's neighbor keys. For example...
If the user types in the letter 'A', I want a vector with the value 'A' to hold every letter that the 'A' key touches (Q, W, S, and Z). Every time I compile I get a subscript error. Any help would be appreciated.
vector< vector<string> > letterNeighbors; // VECTOR OF VECTORS
ifstream fin("iPhone_keyboard.txt"); // IPHONE KEYBOARD LIST
while ( fin ) // WHILE THE CONSOLE CAN TAKE INPUT
{
char templateLetter; // FIRST LETTER
string neighborLetter; // NEIGHBORING LETTERS
fin >> templateLetter; // GETS THE FIRST CHARACTER OF THE LINE (TEMPLATE)
getline(fin, neighborLetter); // GETS THE STRING OF CHARACTERS NEXT TO IT (NEIGHBORS)
int neighborSize = neighborLetter.size(); // USED TO REFERENCE NUMBER OF ITERATIONS FOR LOOP
int i = 0;
while ( i < neighborSize )
{
letterNeighbors.resize( 123, vector<string> (neighborSize) ); // RESIZES VECTOR
letterNeighbors[templateLetter][i] = neighborLetter.substr(i); // MAKES A VECTOR WITH THE TEMPLATE LETTER AND GRADUALLY ADDS NEIGHBORS
i++;
}
}
It works when I make the vector that large but it takes a longer time to run through the program. Any idea why it needs to be such a high number / how I can make it lower?
I knew that the default vector size was 0, I just thought that one of the reasons to use vectors was that they could resize themselves based on input. Even if a vector starts with a size of 0, when I add values it should automatically change it's size. Is that not correct? I would assume I could only get a "Subscript out of range" error if I specified the vector size and then tried to assign values outside of that range.
If v is a vector, v[i] has undefined behavior if i is out of range (i.e. if i >= v.size()). Accessing v[i] does not create that element (or any element) if that element does not already exist.
If you want to append a new element x to v, you can execute v.push_back(x), which will increase the size of v by one, and put a copy of x into the newly created element.
I guess I could solve the problem by including a push_back statement in the loop which would automatically add one value to the vector and then have it replaced immediately afterwards. Either way I am sticking with a resize I have found that works. It isn't the most efficient way but it works. Thanks.
After you have executed the first of these statements, letterNeighbors will have exactly 123 elements, each of which will be a vector. So when you execute the second statement, if the value of templateLetter is >= 123, the result will be a subscript out of range.