How to get the length of a specific row of a two dimensional vector (also last element)

Viewed 59

I have been doing some CP practice and I've came over some small problems.

When I want to make a dynamic two dimensional vector (in this case a 3 rowed two dimensional vector). I have trouble finding the length of a specific row (and the last element).


int Pweightboost = 0;
int Tempweightboost = 0;

int main(void)
{
    string input;
    vector<char> input_noSpace;
    vector<vector<int>> numbers;
    getline(cin, input);

    int numPosCount = 0;
    
    for (int i = 0; i < input.length(); i++)
    {
        if (input[i] != ' ')
        {
            
            if (n == '+' || '-' || '%'){
                
                input_noSpace.push_back(input[i]);

            }
            else if (n == '*' || '/'){
                Tempweightboost += 1;
                numbers[2][numCount]++;
            }
            else if (n == '('){
                Pweightboost += 1;
                input_noSpace.push_back(input[i]);
            }   
            else if (n == ')'){
                Pweightboost -= 1;
                input_noSpace.push_back(input[i]);
            } else {

                numbers[0][numCount] = input[i]; //shows the variable in row 1
                numbers[1][numCount] = posInInput; //show the position of the variable in the input in row 2 
                numbers[2][numCount] = Tempweightboost + Pweightboost; //show the weight of the variable in row 3
                Tempweightboost = 0;
                input_noSpace.push_back(input[i]);
                numPosCount++;
            }
            
        }
        
        }
        
    
}

Not necessary to know what I'm trying to do , cause I havent finished yet

Just want to know if I can get the last element (and the length) of a specific row of my numbers multidimensional vector

help would be appreciated.

2 Answers

Remember that your 2D vector is vector of vectors, so if you want to get length of first vector in your vector (in your case row) you can do it like this:

numbers[0].size()

Same for the last element:

numbers[0].back() 

You might want to consider accessing a row using std::vector::at() as it is a bit safer with its bound check.

numbers.at(2).size()

Related