C++:string erase函數與reverse函數

erase函數的原型:
iterator erase ( iterator position );

string& erase ( size_t pos = 0, size_t n = npos );

iterator erase ( iterator first, iterator last );

解釋一下,嘿嘿,他和上面是一一對應的
erase(position);刪除position處的一個字符(position是個string類型的迭代器)

erase(pos,n); 刪除從pos開始的n個字符,比如erase(0,1)就是刪除第一個字符

erase(first,last);刪除從first到last之間的字符(first和last都是迭代器)

 #include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str ("I Love YX who are very fat!!!");
  string::iterator it;

  // 用法(1)
  it=str.begin()+6;
  str.erase (it);
  cout << str << endl;


  // 用法(2)
  str.erase (13,8);
  cout << str << endl;

  // 用法(3)
  str.erase (str.begin()+3, str.end()-4);
  cout << str << endl;
  return 0;
}

output

I LoveYX whoy fat!!!
I Love YX whoy fat!!!
I Lt!!!

reverse()函數將左閉右開區間內的元素全部逆序;
reverse_copy()會將(sourceBeg,sourceEnd,destBeg)中的源區間[sourceBeg,sourceEnd)內的元素複製到"以destBeg起始的目標區間",並在複製過程中顛倒順序;


#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int a[50];
	int b[50]; 
	for(int i=0;i<10;i++)
	{
		a[i]=i;
		cout<<a[i]<<" ";
	}
	cout<<endl;
	
	reverse(a,a+10);         //第二個參數是數組最後一個元素的下一個地址 
	for(int i=0;i<10;i++)
		cout<<a[i]<<" ";
		cout<<endl;
		
	reverse(a,a+5);
	for(int i=0;i<10;i++)
		cout<<a[i]<<" ";
	cout<<endl;
	
	reverse_copy(a,a+10,b); //倒序放入b數組中 
	for(int i=0;i<10;i++)
		cout<<b[i]<<" ";
	return 0;
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章