一、c++基础
1. vector容器
- 遍历
#include<vector>
vector<int>id;
int main()
{
for(int i = 0; i <= 30; i++)
{
id.push_back(i);
}
/*循环遍历*/
for(int i = 0; i < id.size(); i++)
{
cout<<id[i]<<endl;
}
/*迭代器遍历*/
for(vector<int>::iterator it = id.begin(); it!=id.end(); it++)
{
cout<<*it<<endl;
}
return 0
}
- 删除指定元素
#include<vector>
vector<int>id;
int main()
{
......
......
/*错误示例*/
for(vector<int>::iterator it = id.begin(); it!=id.end(); it++)
{
if(*it = 10)
{
id.erase(it);
it--;
}
}
/*正确示例*/
for(vector<int>::iterator it = id.begin(); it!=id.end();)
{
if(*it = 10)
{
id.erase(it);
}
else
{
it++;
}
}
return 0
}
这里for循环中不使用it++的原因为,erase()方法调用后,会时迭代器指针指向下一个元素,这样显然不能达到遍历的目的,甚至可能导致访问非法内存。当然,也可以再调用erase()方法后iter--,来时迭代器指向上一个元素来避免是这种问题,但显然效率没有第二种高。
2. char* 、char []、string之间的转换
#include <iostream>
#include<string>
#include<cstring>
using namespace std;
const char* buf;
char ch[20];
string msg;
int main()
{
/******* char*转char[] ***************/
buf = "Hello World!";
strncpy(ch,buf,strlen(buf)+1); //此处记得+1,表示加上\0
cout<<ch<<endl;
/******* char[]转char* ***************/
strcpy(ch,"Hello World!");
//ch = "Hello World!"; //数组不可以直接赋值,要在声明时赋值
buf = ch;
cout<<buf<<endl;
/******* char*转string **************/
buf = "Hello World!";
msg = buf;
cout<<msg<<endl;
/******* char[]转string *************/
strcpy(ch,"Hello World!!");
msg = ch; //直接赋值实现
string msg(ch,strlen(ch)); //构造函数实现
cout<<msg<<endl;
/******* string转char* **************/
msg = "Hello World!";
buf = msg.c_str();
cout<<buf<<endl;
/******* string转char[] *******************/
msg = "Hello World!";
strncpy(ch,msg.c_str(),msg.length()+1); //此处记得+1,表示加上\0
cout<<ch<<endl;
return 0;
}