在 C++ 编程中使用容器能更加方便的实现数据结构设计。下面将介绍几种常用容器的使用:
vector容器(类似于数组而又有链表的一些属性,相对来说比数组要方便插入和弹出的操作)
#include <vector>//包含头文件
using namespace std;
vector<myrect> mybluerect;//定义一个类型为 myrect 的名字为 mybluerect 的容器。这个类型可以是自己定义的类型,也可以是C++自带的类型。可以将 mybluerect 改写成 mybluerect[2] 这样子来定义一个容器数组。
mybluerect.clear();//清空容器中的元素
mybluerect.push_back(framerect_blue);//往容器里面填入一个相同类型的值
遍历容器对象,有两种方法:
方法一:
for (int i= 0; i< mybluerect.size(); i++)
{
mybluerect[i]++;//遍历容器元素,对容器元素值进行操作
}
方法二:
vector<myrect> ::iterator itor;//容器迭代器
itor = mybluerect.begin();
while (itor != mybluerect.end())
{
itor++;
}
对于一些情况下,用队列容器来存储数据会更加方便,其跟定义一般的容器很是类似。
#include "queue"//先进先出队列
using namespace std;
queue<ImgObj> myimgqueue;//图像队列
myimgqueue.push(img);//将帧文件对象放入队列中
如果需要排序容器中自定义类成员的某一项,可以进行如下操作(其中Player为自定义类,integral为需要排序的对象):
//升序排列
class CompLess
{
public:
bool operator ()(const Player& pstItem1, const Player &pstItem2)
{
return pstItem1.integral < pstItem2.integral;
}
};
//降序排列
class CompGreater
{
public:
bool operator ()(const Player& pstItem1, const Player &pstItem2)
{
return pstItem1.integral > pstItem2.integral;
}
};
调用如下(注意包含排序相关的头文件algorithm):
sort(thegroup[i].mygroup.female.begin(), thegroup[i].mygroup.female.end(), CompGreater());//降序排列女队员成绩
容器合并
vector<int> dateset,dateset1, dateset2;
dateset1.push_back(4);
dateset1.push_back(1);
dateset1.push_back(14);
dateset1.push_back(24);
dateset2.push_back(213);
dateset2.push_back(123);
dateset2.push_back(124);
dateset2.push_back(111);
dateset.insert(dateset.end(), dateset1.begin(), dateset1.end());//将dateset1的数据压入dateset中
dateset.insert(dateset.end(), dateset2.begin(), dateset2.end());//将dateset2的数据压入dateset中
array容器(基本上等同于数组,增加了方便操作的一些函数)
示例代码如下:
#include <array>
using namespace std;
void main()
{
array<int, 5> arr;
arr[0] = 1;
arr[1] = 2;
}
forward_list容器(单向链表容器)
示例代码如下:#include <forward_list>
using namespace std;
void main()
{
forward_list<int> mForwardList;//单向链表
mForwardList.push_front(123);//在第一个元素之前插入一个元素
mForwardList.push_front(321);//在第一个元素之前插入一个元素
mForwardList.push_front(222);//在第一个元素之前插入一个元素
mForwardList.pop_front();//弹出第一个元素
}
数组链表,也就是数组中的元素是一个个的链表,示例代码如下:#include <forward_list>
#include <array>
using namespace std;
void main()
{
array<forward_list<int>, 5> arr;
arr[0].push_front(123);//在第一个元素之前插入一个元素
arr[0].push_front(321);//在第一个元素之前插入一个元素
arr[1].push_front(222);//在第一个元素之前插入一个元素
arr[0].pop_front();//弹出第一个元素
}
链表整合,示例代码如下:
#include <forward_list>
#include <array>
using namespace std;
void main()
{
array<forward_list<int>, 5> arr;
arr[0].push_front(123);//在第一个元素之前插入一个元素
arr[0].push_front(321);//在第一个元素之前插入一个元素
arr[1].push_front(222);//在第一个元素之前插入一个元素
arr[1].push_front(234);//在第一个元素之前插入一个元素
arr[1].splice_after(arr[1].before_begin(), arr[0], arr[0].before_begin(), arr[0].end());//链表合并
}
链表遍历,示例代码如下:
if (!arr[i].empty())
{
uchar grayvalue = rand() % 256;
for (auto &value : arr[i])
{
img.at<unsigned char>(value.y, value.x) = grayvalue;
}
}