本文介绍了如何将一个向量插入到一个集合中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我真的很困惑这个程序中的do-while循环如何工作,特别是向量的插入操作到一个
I am really confused how the do-while loop in this program works especially the insert operation of a vector into a set
s.insert(v)
。有没有人可以解释这个循环中发生了什么?
. Do anyone can explain what happens in this loop?
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort
#include <vector>
#include <set>
using namespace std;
int main () {
int myints[] = {0,1,2,3,4,5,6,7,8,9};
int N = 2;
set<vector<int>> s;
do {
vector<int> v;
for (int i = 0; i < N; i++)
v.push_back(myints[i]);
s.insert(v);
} while ( std::next_permutation(myints,myints+10) );
cout << "number of permutations = " << s.size() << endl;
for(auto c: s){
for (auto i: c)
cout << i << " ";
cout << endl;
}
return 0;
}
推荐答案
do {
vector<int> v; // declares a vector of ints
// this loop copies the values of the myints array
// into v (note that the call to next_permutation will rearrange
// the values in myints at the end of each iteration)
for (int i = 0; i < N; i++)
v.push_back(myints[i]);
// inserts the vector v into the set s; as a set keeps its elements
// in an ordered sequence, the insert function has to compare the new
// element (v) with the elements already stored in the set. This comparison
// is performed by the compare function specified in the sets
// template parameters, and as no such parameter is specified, the
// operation< member function of vector<int> is used, which compares two
// vectors according to their lexicographical order. (Perhaps this is
// the part you didn't understand)
s.insert(v);
// calls std::next_permutations, which rearranges the values in
// the myints array; once the original permutation (0, ...9) has been reached,
// next_permutation will return false and the loop ends
} while ( std::next_permutation(myints,myints+10) );
[第2修订]
[2nd AMENDMENT]
// loop over all elements of set s and assign each one in turn to a variable c
// (note: the auto keyword lets c assume the type that is the element type of
// set s, which is vector<int>)
for(auto c: s){
// so now we have in c one of the vector<int> elements stored in s; in
// the inner loop, we walk over all elements of that vector<int> and each
// is in turn assigned to variable i
for (auto i: c)
// we output that element i and a space
cout << i << " ";
// after the inner loop has output all elements of c, we terminate
// the output line
cout << endl;
}
我希望能清楚说明嵌套循环的作用。
I hope that makes it clear what the nested loops do.
do {
vector<int> v; // create a new empty vector called v
for (int i = 0; i < N; i++) // start a loop of N iterations
v.push_back(myints[i]); // add the integer at myints[i] to the vector v
s.insert(v); // on completion of the inner loop, add the vector v to the set s
} while ( std::next_permutation(myints,myints+10) ); // repeat until this expression is false
</int>
这篇关于如何将一个向量插入到一个集合中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!