-1

Here is the 2d vector [[1,3],[2,6],[8,10],[15,18]] I want to delete the 2nd row which is [2,6] I tried following to erase the 1st row

matrix[1].erase(intervals[1].begin(),intervals[1].end());

after erasing the row when I printed the matrix, I got [[1,3],[],[8,10],[15,18]] I wanted to remove the brackets also, how to do that?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
saurin
  • 3
  • 1
  • 1
  • 4

2 Answers2

1

To delete a "row" in a vector of vectors is easy.

For example

#include <vector>
#include <iterator>

//...

matrix.erase( std::next( std::begin( matrix ) ) );

Here is a demonstration program

#include <iostream>
#include <vector>
#include <iterator>

int main()
{
    std::vector<std::vector<int>> matrix =
    {
        { 1, 3 }, { 2, 6 }, { 8, 10 }, { 15, 18 }
    };

    for (const auto &row : matrix)
    {
        bool first = true;
        std::cout << '[';

        for (const auto &item : row)
        {
            if (!first)
            {
                std::cout << ", ";
            }
            else
            {
                first = false;
            }

            std::cout << item;
        }
        std::cout << "]\n";
    }

    std::cout << '\n';

    matrix.erase( std::next( std::begin( matrix ) ) );

    for (const auto &row : matrix)
    {
        bool first = true;
        std::cout << '[';

        for (const auto &item : row)
        {
            if (!first)
            {
                std::cout << ", ";
            }
            else
            {
                first = false;
            }

            std::cout << item;
        }
        std::cout << "]\n";
    }

    std::cout << '\n';
}

The program output is

[1, 3]
[2, 6]
[8, 10]
[15, 18]

[1, 3]
[8, 10]
[15, 18]

To remove the i-th "row" you can use the expression std::next( std::begin( matrix ), i ) shown in the statement below

matrix.erase( std::next( std::begin( matrix ), i ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

From what you showed, I believe the correct code would be

matrix.erase( matrix.begin()+1 );