gpt4 book ai didi

c++ - 子集 vector

转载 作者:行者123 更新时间:2023-11-28 07:21:56 26 4
gpt4 key购买 nike

我有下一个程序。我应该如何在 main 中使用迭代器以显示总和为 0 的子集?
我的程序应该打印:
2 -2
5 -5

# include < iostream >
# include < vector >

using namespace std;

vector < vector < int > > test(vector <int> data)
{
vector <int> a;
vector < vector < int > > ret;
vector <int> :: iterator it1;
vector <int> :: iterator it2;
int i=0;
for(it1 = data.begin(); it1!= data.end(); it1++,i++)
{
for(it2 = data.begin() + i; it2!= data.end(); it2++ )
{
if( *it1 + *it2 == 0)
{
cout<<*it1<<" "<<*it2<<"\n";
a.push_back(*it1);
a.push_back(*it2);
ret.push_back(a);
a.clear();
}
}
}
return ret;
}
int main()
{
vector < int > data;
data.push_back(2);
data.push_back(5);
data.push_back(-3);
data.push_back(-2);
data.push_back(-5);
vector <vector <int > > v=test(data);
//how to continue printing the subsets

}

最佳答案

std::vector<std::vector<int> >::iterator it=v.begin(), end=v.end();
for ( it!= end, ++it) {
std::copy(it->begin(),it->end(),std::ostream_iterator<int>(std::cout, " "));
}

或者使用c++11

 for(const auto& i:v)
{
for(const auto& j:i)
std::cout<<j<< " ";
std::cout<<std::endl;
}

关于c++ - 子集 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19320092/

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