C++ 编程技巧积累 (Update Continuously)
来源:互联网 发布:zabbix监控nginx 编辑:程序博客网 时间:2024/05/22 17:34
最近写C++或者Python的过程中发现,好多函数的调用形式总是记不清楚,需要搜索或者查官方文档。于是乎希望能进一步熟悉这些函数的使用,这里先一点点的记录C++一些函数的使用,以便以后过来查阅。
1. 如何拼接两个vector
在C++中很多功能不像Python中那么方便,比如说要拼接两个vector,在C++中就需要自己实现。但是vector有一个非常好的函数可以简便的实现该功能,那就是insert函数。查看文档可以知道,该函数有多重重载形式,其中一个就是
void insert (iterator position, InputIterator first, InputIterator last);
看到这里就知道怎么拼接了吧,上代码。
#include <iostream>#include <vector>using namespace std;vector<int> combine(vector<int> &a, vector<int> &b){ vector<int> ta = a; vector<int> tb = b; tb.insert(tb.begin(), ta.begin(), ta.end()); return tb;}int main(){ vector<int> a; vector<int> b; a.push_back(1); a.push_back(2); b.push_back(3); b.push_back(4); vector<int> ans = combine(a, b); for(vector<int>::iterator it=ans.begin(); it!=ans.end(); ++it) { cout << *it << endl; } return 0;}
使用vector的insert方法就能够方便的将两个vector进行拼接了。
2. 反转vector
经常会遇到一些情况,我们希望反转一个vector,但是我们又不愿意自己写一个函数来完成这个,虽然说这个函数本来就很简单,那么<algorithm>中的reverse函数可以帮到你了。首先来看看函数的定义:
template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last);
使用这个函数的时候,我们只需要把vector的首尾iterator传进去即可。
int temp[] = {1, 2, 3};vector<int> v(temp, temp+3);reverse(v.begin(), v.end());
3. 快速输出容器的内容
很多时候想查看容器里的内容,习惯写for循环,但是感觉不方便,而且如果要写iterator的话,总是for循环内一堆长长的内容。现在有一好的办法就是使用copy函数,将指定容器内的内容用iterator的方式输出到ostream_iterator中,这样一个copy函数就能方便的输出container的内容。注意下面代码中的iota函数是C++11特性。
vector<int> container(6); iota(container.begin(), container.end(), 1); random_shuffle(container.begin(), container.end()); copy(container.begin(), container.end(), ostream_iterator<int>(cout, " ")); cout << endl; return 0;
1 0
- C++ 编程技巧积累 (Update Continuously)
- tree related problems (update continuously)
- dp related problems (update continuously)
- matlab 编程小技巧积累
- Android编程小技巧积累
- C技巧积累精萃
- C技巧积累精萃
- C技巧积累精萃
- C技巧积累精萃
- C语言编程积累2
- PHP小小算法(Continuously updated)
- C#编程小技巧(不断积累中)
- Js编程小技巧(不断积累中)
- 技术积累-1( C技巧/GLib数据结构 )
- 小技巧积累 objective-c,持续更新
- Mac技巧(网页积累)
- 程序积累(C)
- 我的嵌入式C编程一点积累
- Web.xml配置详解
- 给大家提供一个C#2.0的网站后台文章上传与前台显示的代码!呵呵!fckeditor大家自己调哦!
- subversion链接visual svn错误
- apk编译/反编译工具baksmali…
- Cocos2d-x开发--使用CCRenderTexture将矩形图片裁剪成圆形显示
- C++ 编程技巧积累 (Update Continuously)
- C指针解析
- Facebook Login for iOS
- jquery限制文本框输入字符长度
- tcp 的ack, seq
- rhel5.x 光盘yum源配置
- Android 不能静态注册的广播
- 解决sqoop1.4.4无法导入oracle的blob字段到hbase的问题
- 学习苏坤winform开发第14讲笔记