C++ 回忆录2

来源:互联网 发布:杭州朝乾网络 编辑:程序博客网 时间:2024/04/25 14:25

1. 每次使用cin,cout时候总要这样写:std::cin,,,,其实可以在使用using 关键字.

using std::cin;

using std::cout;

using std::endl;

这样每次使用这些时候就可以直接使用了.

也有一个是

using namespace std;

这样这个命名空间下的都可以直接使用.


注意在类的声明的,一般不加using,因为如果加上的话,在编译时候可能出现重复使用using 的问题.


2.string 的使用

#include <string>

using std::string

constructor:

string str1;

string str2("abcd-direct initialize");

string str3(str2);

string str4=str3;//copy initrilize;


str4=str2;//注意,这个赋值过程,他会清掉str4原来的内容,然后计算新的内存空间一容纳st r2.

operation:

empty();

size();//return string::size_type; //是一中unsigned 类型,可能是unsingne int,or unsigned long, 取决于不同的机器,目的是保证正确的返回长度

string str="abcdedf";

for (string::size_type index=0;index!=str.size();index++)

{

       str[index]='a'; //此时也可以改变该index下的字符 

}


//C++ 由于存在inline 函数, 而且string 可以动态的变化,所以一般都不写成


string::size_type length=str.size();

for (string::size_type index=0;index <length;index++)

{

       str[index]='a'; //此时也可以改变该index下的字符 

}


读取

string str;

while(cin>>str)  //读的是从第一个不是空格,到下一个空格为止. 比如如果输入 "      abc    cdef" //那么读到的只是"abc"

{

 cout<<str;

}

//如果想整行读可以使用getline

while(getline(cin,str))  //getline 返回的是cin 对象.所以可以被判断. 这样如果输入"     abcd    efm..." 然后换行,则读到的是"     abcd    efm..."

{

 cout<<str<<end;

}


////////////////////////////

3.vector 的使用

vector<int> inttList;

vector<int> intList2(5); //5 个0

vector <int>intList3(5,2)//5 个2

vector <string>strList(5,"a"); 5 a


vector<int>intList(5);

vector<int>::size_type  length=intList.size();// 必须写成:vector<int>::size_type, 而不能是vector::size_type ,因为vector is just a template,vector<int> 这才是一中类型.

for(vector <int>size_type index=0;index!=intlist.size();i++) //vector 是动态的,所以也是直接跟调用size 方法.

{

  cout<<intList[index];

}

//也可以用iterator,iterator 其实就是一个指针.

vector<int>::iterator start=intList.begin();

for(;start!=intList.end();start++)

{

 cout<<*start<<end;//由于是指针所以需要解引用.

}

要想加上新的元素,可以调用push_back()

intList.push_back(5); //5就被加到最后了.


///

4.bitset 的使用,未想.




原创粉丝点击