gpt4 book ai didi

c++ - 计算合并后剩下多少个不同的 vector

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:26 29 4
gpt4 key购买 nike

在这个问题中我只使用了 std::vector 并且每个 vector 都没有重复地排序。现在我想合并具有相同数字的 vector 。所以 2 3 可以与 3 4 5 并集,但不能与 4 5 或 1 5 并集。

例子:

如果我有以下 vector ...

1
1
2 3 4
5
1 5
2
4 7

合并后我应该只剩下 2 个 vector :

1 5
2 3 4 7

代码:

vector<int> a,b,c,d,e,f,g;
vector<vector<int>> myList;

a.push_back(1);
b.push_back(1);
c.push_back(2);
c.push_back(3);
c.push_back(4);
d.push_back(5);
e.push_back(1);
e.push_back(5);
f.push_back(2);
g.push_back(4);
g.push_back(7);

myList.push_back(a);
myList.push_back(b);
myList.push_back(c);
myList.push_back(d);
myList.push_back(e);
myList.push_back(f);
myList.push_back(g);

//this should print out the vectors in my above example
for (int i =0; i<myList.size(); i++) {
for (int j=0; j<myList[i].size(); j++) {
cout<<myList[i][j]<<" ";
}
cout<<endl;
}

我尝试使用 set_union 和 set_intersection 来实现我的目标,但它没有按预期工作。我怀疑问题出在我没有正确更改的 vector 大小上。请帮忙。谢谢!

编辑:

这是有问题的代码,最初我对 union 有问题,但现在它自动运行..现在我想我主要不确定如何使用 set_intersection 来找出是否有交集

vector<int>::iterator myIt;
vector<int> myTemp;
vector<int> myTemp2;
vector<int> myResult(20);
vector<int> myResult2(20);


while (!myList.empty()) {

myTemp2 = myList.back();
myList.pop_back();


myIt = set_intersection(myTemp.begin(), myTemp.end(),
myTemp2.begin(), myTemp2.end(), myResult.begin());

//this is checking whether there is intersection but it doesn't work
if (myResult.size()) {

myIt = set_union(myTemp.begin(), myTemp.end(),
myTemp2.begin(), myTemp2.end(), myResult2.begin());

myTemp = myResult2;

}


}

cout<<"after union: "<<endl;

for (auto it = myResult2.begin(); it != myResult2.end() ; it++) {
cout<<*it<< " ";
}

最佳答案

如果我对您的理解正确,不仅是您的代码而且您的方法都大错特错。您正在尝试解决连接组件/不相交集类型问题,但您的方法例如只返回一个 vectorint是……?它需要返回一个 vectorvector<int>肯定是。

以下代码是我能想到的最接近您的代码的代码。它应该离开 result与你想要的输出。

vector< vector<int> > result;

for(int i = 0; i < myList.size(); i++)
{

bool match = false;
int matchFirst = -1;

for(int j = 0; j < result.size(); j++)
{

vector<int> myResult;
vector<int> myResult2;

set_intersection(myList[i].begin(), myList[i].end(),
result[j].begin(), result[j].end(),
back_inserter(myResult));

if (myResult.size())
{
set_union(myList[i].begin(), myList[i].end(),
result[j].begin(), result[j].end(), back_inserter(myResult2));

if(match)
{
vector<int> myResult3;
set_union(myResult2.begin(), myResult2.end(),
result[matchFirst].begin(), result[matchFirst].end(), back_inserter(myResult3));
result.erase(result.begin() + j, result.begin() + j + 1);
result[matchFirst] = myResult3;
j--;
}
else
{
matchFirst = j;
result[j] = myResult2;
match = true;
}

}

}

if(!match)
{
result.push_back(myList[i]);
}
}

编辑:修复了一个错误。

关于c++ - 计算合并后剩下多少个不同的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15937594/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com