从 2D 向量 c++ 中删除元素 [英] Erasing an element from 2D vector c++

查看:29
本文介绍了从 2D 向量 c++ 中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不对称的二维向量.

I have a unsymmetrical vector in 2D.

vector< vector<int> > Test

其中测试 =

         2 4 6 5 7 
         6 5 7 9 10
         5 9 10
         9 10

我正在阅读第 1 行,如果其他行中存在该元素的任何元素,则将其删除.例如..阅读第 1 行后,我必须从其他行中删除 6、5 和 7.

I am reading the row 1 and if any element of this is present in other rows then delete it. for eaxmple.. After reading row 1, i have to remove 6, 5, and 7 from other rows.

然而,它不起作用

这是我正在尝试的代码

Test[i].erase(Test[i].begin()+j);

其中 i = 行,j 是列.

where i = row and j is col.

我的代码是:

for (i =0; i < Test.size();i++)
        {
        for (j=0; j < Test[i].size();j++)
                {
                // removed repeated element
                if (i >0)
                        {
                        Test[i].erase(Test[i].begin() +j);
                        }
                }
        }

推荐答案

也许它不是很好,但它有效

Maybe it is nor very nice but it works

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

int main() 
{
    std::vector<std::vector<int>> v =
    {
        { 2, 4, 6, 5, 7 }, 
        { 6, 5, 7, 9, 10 },
        { 5, 9, 10 },
        { 9, 10 }
    };

    for ( const auto &row : v )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }

    std::cout << std::endl;

    if ( !v.empty() )
    {
        for ( auto it = std::next( v.begin() ); it != v.end(); ++it )
        {
            auto is_present = [&]( int x )
            {
                return std::find_if( v.begin(), it,
                    [x]( const std::vector<int> &v1 )
                    {
                        return std::find( v1.begin(), v1.end(), x ) != v1.end();
                    } ) != it; 
            };

            it->erase( std::remove_if( it->begin(), it->end(), is_present ), 
                       it->end() );
        }
    }


    for ( const auto &row : v )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }

    return 0;
}

输出是

2 4 6 5 7 
6 5 7 9 10 
5 9 10 
9 10 

2 4 6 5 7 
9 10 

这篇关于从 2D 向量 c++ 中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆