c++入门基础

一、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;
}

二、c++提升

三、c++进阶

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值