C++中的一些技巧小结(一)
1.如何通过vector的数组名来打印数组元素,需要用到<<重载
# include <iostream>
# include <vector>
# include <string>
using namespace std;
template < typename T >
ostream & operator << ( ostream & out, vector< T> & _vec)
{
if ( _vec. empty ( ) )
return out;
vector< T> :: const_iterator it = _vec. begin ( ) ;
for ( ; it != _vec. end ( ) ; ++ it)
{
out << * it<< " " ;
}
return out;
}
int main ( )
{
vector< int > vec ( 10 , 1 ) ;
cout << vec << endl;
return 0 ;
}
2.string 向char char*、char []转化
2.1 char转string 这个最常用,string本身是一个数组,里面存放的是char类型
# include <iostream>
# include <string>
using namespace std;
inline string CharToString ( char & temp)
{
char t = temp;
string s ( 1 , t) ;
return s;
}
int main ( )
{
string s = "tgj hss" ;
for ( int i = 0 ; i < s. size ( ) ; i++ )
{
string result = CharToString ( s[ i] ) ;
cout << result << endl;
}
}
2.2 string转char 直接提取下表,即可
2.3 char*转string 可以直接赋值
string s;
char *p="tgj hss";
s=p;
2.4 string转char*,有三种方法:data(),c_str(),copy(),其中最常用的是c_str()
string str = "tgj hss" ;
const char * p = str. data ( ) ;
string str = "tgj hss" ;
const char * p = str. c_str ( ) ;
string str= "hss" ;
char p[ 50 ] ;
str. copy ( p, 5 , 0 ) ;
* ( p+ 5 ) = ‘\0 ’;
2.5 char []转string 可以直接赋值
2.6 string转char[]
string pp = "tgj hss" ;
char p[ 8 ] ;
int i;
for ( i= 0 ; i< pp. length ( ) ; i++ )
p[ i] = pp[ i] ;
p[ i] = '\0' ;
printf ( "%s\n" , p) ;
cout<< p;
3.字符串的切割函数
std:: vector< std:: string> split ( std:: string src, std:: string condition)
{
std:: vector< std:: string> coll;
int begin = 0 , end = 0 ;
while ( begin < src. length ( ) )
{
end = src. find ( condition. c_str ( ) , begin) ;
if ( end == - 1 )
end = src. length ( ) ;
coll. push_back ( src. substr ( begin, end - begin) ) ;
begin = end + condition. length ( ) ;
}
return coll;
}
4.循环查找字符串中符合条件的索引
# include <iostream>
# include <string>
# include <vector>
using namespace std;
vector < int > FindStringCondition ( string src, string condition)
{
vector< int > index_;
int index_c= 0 ;
while ( ( index_c = src. find ( condition, index_c) ) < src. length ( ) )
{
index_. push_back ( index_c) ;
index_c++ ;
}
return index_;
}
int main ( )
{
string s = "tgj hss tgj hss tgj hss hss hss" ;
vector< int > result = FindStringCondition ( s, "hss" ) ;
return 0 ;
}