您的位置:首页 > 其它

STL vector find and sort vector的查找和排序

2014-12-16 15:17 453 查看
STL vector find and sort vector 的查找和排序

这两者都需要头文件 algorithm

如果需要对 STL 中的 vector 进行排序和查找方法如下:

// iterator_back_inserter.cpp
// compile with: /EHsc
#include <iterator>
#include <vector>
#include <iostream>
#include <algorithm>

bool Comp(const int &a,const int &b)
{
return a > b ;
}

void main( )
{
using namespace std;
int i;

vector<int> vec;
for(i=0;i<3;++i)
{
vec.push_back(5-i);
}

vector<int>::iterator vIter;//see annotation above
cout << "The initial vector vec is: ( ";
for ( vIter = vec.begin ( ) ; vIter != vec.end ( ); vIter++)
cout << *vIter << " ";
cout << ")." << endl;

// Insertions can be done with template function
back_insert_iterator<vector<int>> backiter(vec);//see annotation above
*backiter = 30;
backiter++;
*backiter = 40;

// Alternatively, insertions can be done with the
// back_insert_iterator member function
back_inserter ( vec ) = 500;
back_inserter ( vec ) = 600;

cout << "After the insertions, the vector vec is: ( ";
for ( vIter = vec.begin ( ) ; vIter != vec.end ( ); vIter++ )
cout << *vIter << " ";
cout << ")." << endl;

//using default compare
sort(vec.begin(),vec.end());
cout << "After sort, the vector vec is: ( ";
for ( vIter = vec.begin ( ) ; vIter != vec.end ( ); vIter++ )
cout << *vIter << " ";
cout << ")." << endl;
//add customized specified compare function to compare
sort(vec.begin(),vec.end(),Comp);
cout << "After sort, the vector vec is: ( ";
for ( vIter = vec.begin ( ) ; vIter != vec.end ( ); vIter++ )
cout << *vIter << " ";
cout << ")." << endl;

vector<int>::iterator result = find( vec.begin( ), vec.end( ), 40 ); //查找
if ( result == vec.end( ) ) //没找到
cout << "No" << endl;
else //找到
cout << "Yes" << endl;

vec.clear();

system("pause");
}


其中比较也可以用运算符重载来实现,参见博客

摘自别人博客,对 vector 使用有如下建议,认为很有道理:

需要说明的是,虽然这个通用的find方法也是可以用在map,set等上面的,但是效率会比容器内部的find方法慢很多,所以,除非容器实在是没有提供find方法,否则还是建议不要用公共的这一种。

另外,作为题外话,我们需要注意一下vector的删除(erase)操作。由于vector需要能以下标方式取数据,所以必须时刻保证连续的存储空间,对应于实现上,即,当删除vector中间的一个成员时,这个成员后面的所有成员,会以原顺序向前全部拷贝过来。有兴趣的朋友,可以用这个例子测试一下。

这里起码告诉了我们两件事:

1.vector中一个成员被删除,会导致后面的成员进行copy和析构操作。

2.vector不适合做有大量插入删除操作的容器,因为拷贝内存本身浪费很大
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐