簡體   English   中英

c++ 二維向量(矩陣)如何刪除第n行?

[英]c++ 2D vector(matrix) how to delete the nth row?

這是 2d 向量 [[1,3],[2,6],[8,10],[15,18]] 我想刪除第二行,即 [2,6] 我試圖按照以下方式擦除第一行

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

在打印矩陣時擦除行后,我得到 [[1,3],[],[8,10],[15,18]] 我也想刪除括號,該怎么做?

刪除向量向量中的“行”很容易。

例如

#include <vector>
#include <iterator>

//...

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

這是一個演示程序

#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';
}

程序 output 是

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

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

從您展示的內容來看,我相信正確的代碼是

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM