How to remove a k-row in two dimensional array c++?

1 Answer

  • Cubbi
    Lv 7
    10 years ago
    Favorite Answer

    Arrays have fixed size, thus nothing can actually be removed from an array, once it has been created.

    Values of the array elements can be overwritten, though. For example, in an NxM array, k-row can be swapped with the N-1 row, and the rest of the program will pretend the array has dimensions N-1 x M, although that would also change the order of the rows. Or you could swap the k row with the k+1 row, and the k+1 row with the k+2 row, etc until the end of the array.

    Or, much better, you could switch to C++ and let the language do the work for you with a single call to the built-in erase() function. For example:

    #include <iostream>

    #include <vector>

    #include <iostream>

    #include <iterator>

    #include <algorithm>

    typedef std::vector< std::vector<int> > matrix_t;

    // helper function to output this matrix, will need a modern compiler

    std::ostream& operator<<(std::ostream& os, matrix_t m)


         for_each(m.begin(), m.end(), [&](const std::vector<int>& r){

             copy(r.begin(), r.end(), std::ostream_iterator<int> (os, " "));

             os << '\n'; });

         return os;


    int main()


         // create matrix (this line needs a modern compiler)

         matrix_t v = {{1,2,3,4}, {5,6,7,8}, {11,12,13,14}};

         // show what it looks like now

         std::cout << " before removal, the matrix is \n" << v << '\n';

         // remove the middle row

         v.erase(v.begin()+1); // this line will compile on ANY compiler!

         // show what it looks like now

         std::cout << " after removal, the matrix is \n" << v << '\n';


    test run:

    ~ $ g++ -g -Wall -Wextra -pedantic -std=c++0x -o test

    ~ $ ./test

    before removal, the matrix is

    1 2 3 4

    5 6 7 8

    11 12 13 14

    after removal, the matrix is

    1 2 3 4

    11 12 13 14

    • Commenter avatarLogin to reply the answers
Still have questions? Get your answers by asking now.