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

9 篇文章 0 订阅
3 篇文章 0 订阅

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不适合做有大量插入删除操作的容器,因为拷贝内存本身浪费很大

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值