从 2D 向量 C++ 中删除一个元素

sno*_*oze 7 c++ vector

我有一个二维不对称向量。

vector< vector<int> > Test
Run Code Online (Sandbox Code Playgroud)

其中测试 =

         2 4 6 5 7 
         6 5 7 9 10
         5 9 10
         9 10
Run Code Online (Sandbox Code Playgroud)

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

但是,它不起作用

这是我正在尝试的代码

Test[i].erase(Test[i].begin()+j);
Run Code Online (Sandbox Code Playgroud)

其中 i = 行,j 为列。

我的代码是:

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);
                        }
                }
        }
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 3

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出是

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

2 4 6 5 7 
9 10 
Run Code Online (Sandbox Code Playgroud)