std::reverse() function of STL in header file algorithm
void reverse(BidirectionalIterator first, BidirectionalIterator last); 翻转
BidirectionalIterator is an iterator that can be used to access any
elements of a container in both forward and backward direction.
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
// Reversing directly from beginning to end
cout << "\nReverse full array:\n";
int a[] = {4, 5, 6, 7};
std::reverse(std::begin(a), std::end(a));
// Print the array
std::cout << a[0] << a[1] << a[2] << a[3] << '\n';
vector <int> v ;
// Inserting elements in vector
for (int i = 0; i < 8; i++)
v.push_back(i+10);
cout << "Reverse only from index 5 to 7 in array:\n";
// Reversing elements from index 5 to index 7
reverse(v.begin() + 5, v.begin() + 8);
// Displaying elements of vector
vector <int> :: iterator it;
for (it = v.begin(); it != v.end(); it++)
cout << (*it) << " ";
return 0;
}
container
set容器
set是用红黑树的平衡二叉索引树的数据结构来实现的,插入时,它会自动调节二叉树排列,把元素放到适合的位置,确保每个子树根节点的键值大于左子树所有的值、小于右子树所有的值,插入重复数据时会忽略。set迭代器采用中序遍历,检索效率高于vector、deque、list,并且会将元素按照升序的序列遍历。set容器中的数值,一经更改,set会根据新值旋转二叉树,以保证平衡,构建set就是为了快速检索(python中的set一旦建立就是一个常量,不能改的)。
自定义比较函数,insert的时候,set会使用默认的比较函数(升序),很多情况下需要自己编写比较函数。
1、如果元素不是结构体,可以编写比较函数,下面这个例子是用降序排列的
#include<iostream>
#include<set>
using namespace std;
struct Comp
{
//重载()
bool operator()(const int &a, const int &b)
{
return a > b;
}
};
int main()
{
set<int,Comp> v;
v.insert(1);
v.insert(3);
v.insert(5);
v.insert(2);
v.insert(4);
v.insert(3);
for(set<int,Comp>::iterator it = v.begin(); it != v.end(); ++it)
cout << *it << " ";
cout << endl;
for(set<int,Comp>::reverse_iterator rit = v.rbegin(); rit != v.rend(); ++rit)
cout << *rit << " ";
cout << endl;
return 0;
}
2、元素本身就是结构体,直接把比较函数写在结构体内部,下面的例子依然降序:
#include<iostream>
#include<set>
#include<string>
using namespace std;
struct Info
{
string name;
double score;
//重载 <
bool operator < (const Info &a) const
{
return a.score < score;
}
};
int main()
{
set<Info> s;
Info info;
info.name = "abc";
info.score = 123.3;
s.insert(info);
info.name = "EDF";
info.score = -23.53;
s.insert(info);
info.name = "xyz";
info.score = 73.3;
s.insert(info);
for(set<Info>::iterator it = s.begin(); it != s.end(); ++it)
{
cout << (*it).name << ":" << (*it).score << endl;
}
cout << endl;
for(set<Info>::reverse_iterator rit = s.rbegin(); rit != s.rend(); ++rit)
{
cout << (*rit).name << ":" << (*rit).score << endl;
}
cout << endl;
return 0;
}
来源:CSDN
作者:每天快乐学习
链接:https://blog.csdn.net/qq_43008718/article/details/104634493