【问题标题】:c++ 2D vector(matrix) how to delete the nth row? [duplicate]c++ 2D向量(矩阵)如何删除第n行? [复制]
【发布时间】:2021-12-30 19:49:39
【问题描述】:

这里是二维向量 [[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]] 我也想去掉括号,怎么做?

【问题讨论】:

  • 间隔是多少?

标签: c++ vector iterator erase


【解决方案1】:

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

例如

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

程序输出是

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

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

要删除第 i 个“行”,您可以使用下面语句中显示的表达式 std::next( std::begin( matrix ), i )

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

【讨论】:

    【解决方案2】:

    从你展示的内容来看,我相信正确的代码是

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

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多