C++去除嵌套列表中重复元素的方法
How to remove duplicates elements in nested list in c++
我正在尝试用 C++ 解决一个 np-complete 问题。我可以在 Python 中解决这个问题,但是 运行 时间相对较慢,所以这就是我切换到 C++ 的原因。在问题的一部分中,我需要从列表中清除重复的元素。
我有一个列表,在 C++ 中类型是 list >。我的列表包含重复元素,例如:
如果我发送以下列表作为输入:
[ [1,2,3] , [2,3,4] , [2,3,4] , [4,5,6] ]
我应该得到 [ [1,2,3] , [2,3,4] , [4,5,6] ]
作为该方法的结果。
那么,我怎样才能让我的嵌套列表只包含独特的元素?在 C++ 中是否有任何有效的方法或内置函数而不是使用嵌套循环?
std::unique
工作正常:(其中 input
是您的嵌套列表)
auto it = std::unique(begin(input), end(input));
input.erase(it, end(input));
我知道这个解决方案不合理,但我建议使用 set<list<int>>
:
#include <iostream>
#include <list>
#include <set>
using namespace std;
template<class Type>
void showContentContainer(Type& input)
{
for(auto itemSet : input)
{
for(auto iteratorList=itemSet.begin(); iteratorList!=itemSet.end(); ++iteratorList)
{
cout<<*iteratorList<<", ";
}
cout<<endl;
}
return;
}
void solve()
{
list<list<int>> listOfLists={{1, 2, 3}, {2, 3, 4}, {2, 3, 4}, {4, 5, 6}};
set<list<int>> setOfLists;
for(auto iterator=listOfLists.begin(); iterator!=listOfLists.end(); ++iterator)
{
setOfLists.insert(*iterator);
}
cout<<"Before, listOfLists <- "<<endl;
showContentContainer(listOfLists);
listOfLists.clear();
for(auto item : setOfLists)
{
listOfLists.push_back(item);
}
cout<<endl<<"After, listOfLists <- "<<endl;
showContentContainer(listOfLists);
cout<<endl;
return;
}
int main()
{
solve();
return 0;
}
结果如下:
Before, listOfLists <-
1, 2, 3,
2, 3, 4,
2, 3, 4,
4, 5, 6,
After, listOfLists <-
1, 2, 3,
2, 3, 4,
4, 5, 6,
我正在尝试用 C++ 解决一个 np-complete 问题。我可以在 Python 中解决这个问题,但是 运行 时间相对较慢,所以这就是我切换到 C++ 的原因。在问题的一部分中,我需要从列表中清除重复的元素。
我有一个列表,在 C++ 中类型是 list >。我的列表包含重复元素,例如:
如果我发送以下列表作为输入:
[ [1,2,3] , [2,3,4] , [2,3,4] , [4,5,6] ]
我应该得到 [ [1,2,3] , [2,3,4] , [4,5,6] ]
作为该方法的结果。
那么,我怎样才能让我的嵌套列表只包含独特的元素?在 C++ 中是否有任何有效的方法或内置函数而不是使用嵌套循环?
std::unique
工作正常:(其中 input
是您的嵌套列表)
auto it = std::unique(begin(input), end(input));
input.erase(it, end(input));
我知道这个解决方案不合理,但我建议使用 set<list<int>>
:
#include <iostream>
#include <list>
#include <set>
using namespace std;
template<class Type>
void showContentContainer(Type& input)
{
for(auto itemSet : input)
{
for(auto iteratorList=itemSet.begin(); iteratorList!=itemSet.end(); ++iteratorList)
{
cout<<*iteratorList<<", ";
}
cout<<endl;
}
return;
}
void solve()
{
list<list<int>> listOfLists={{1, 2, 3}, {2, 3, 4}, {2, 3, 4}, {4, 5, 6}};
set<list<int>> setOfLists;
for(auto iterator=listOfLists.begin(); iterator!=listOfLists.end(); ++iterator)
{
setOfLists.insert(*iterator);
}
cout<<"Before, listOfLists <- "<<endl;
showContentContainer(listOfLists);
listOfLists.clear();
for(auto item : setOfLists)
{
listOfLists.push_back(item);
}
cout<<endl<<"After, listOfLists <- "<<endl;
showContentContainer(listOfLists);
cout<<endl;
return;
}
int main()
{
solve();
return 0;
}
结果如下:
Before, listOfLists <-
1, 2, 3,
2, 3, 4,
2, 3, 4,
4, 5, 6,
After, listOfLists <-
1, 2, 3,
2, 3, 4,
4, 5, 6,