C++ primer复习(三、字符串、向量和数组)

3.1、命名空间的using声明

可以提前拿出一个命名空间,这样可以写程序更方便。
如:using

#include <iostream>
#include <windows.h>
using namespace std;//声明std命名空间
int main()
{
    
       
    cout<<"成功"<<endl;
    system("pause");
    return 0;
}

3.2、string标准库

1、初始化:

#include <iostream>
#include <windows.h>
#include <string>
using namespace std
int main()
{
    
       
    string a;//默认初始化
    string a1(a);//a1是a的副本
    string a2 = a2;//等价上面
    string a4(5,'c');//由5个c组成
    system("pause");
    return 0;
}

string(刷题)常用的操作:

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main()
{
    
       
    string a = "a123";
    a.empty();//看a是不是空
    a.size();//看a的长度
    system("pause");
    return 0;
}

看一个string骚操作

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main()
{
    
       
    string a;
    cin>>a;//我输入的是"    我喜欢你   "
    cout<<a;//输出的是”我喜欢你“
    system("pause");
    return 0;
}

ps:a.size()返回的类型是size_type类型(无符号整型数),用int接受可能会发生错误,这里建议用auto b = a.size();
字符串运算:

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main()
{
    
       
    string a = "今天天气真好,";
    string b = "我可以爱你吗?";
    cout<<a+b;//字符串直接组合,前面的必须是字符串,"a" + b这样就不行。
    cout<<endl;
    if(a > b) cout<<"a大";//进行比较看第一个字符的ascll码,哪个大就是哪个大,第一个一样比较第二个,以此类推。
    else cout<<"b大";
    system("pause");
    return 0;
}

判断字符串存不存在数字字母啊用的标准库:cctype
for each的用法:

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main()
{
    
       
    string a = "我需要你";
    for(auto ai : a){
    
    
        cout<<ai;
    }
    system("pause");
    return 0;
}

3.3、标准库vector

这是一个类模板,是用来存数据的。
这些函数我真的不喜欢一个个枚举,没什么注意的地方,leetcode常用这个数据结构。链接

3.4、迭代器

用来从当前字符,移动到下一个字符,不使用下标。
string和vector都支持迭代器的(我感觉刷题用这个比下标快)

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main()
{
    
       
    string a = "someone";
    if(a.begin() != a.end()){
    
    //a.begin()指向第一个元素s,a.bagin()指向最后一个元素e后面的位置
        auto it = a.begin();
        cout<< *it++;//先进行的输出,再进行的迭代器++,也就是指向下一个位置的操作
        cout<< *it;//迭代器是一个指针
    }
    auto *it1 = a.cbegin();
    auto *it2 = a.cend();
    //加不加c里面内容一样,都是第一个和最后一个下一个位置,只不过类型就算常量迭代器。
    system("pause");
    return 0;
}

ps:vector的迭代器会因为push_back()等操作失效。
迭代器加减法都是迭代器移动几个位置。加就是向后移动,减是向前移动。

扫描二维码关注公众号,回复: 12947571 查看本文章

3.5、数组

emm初始化啥的,别人写的不错(懒,链接
数组的指针其实就是指向数组第一个存储空间,比如string nums[]={“1”,“2”}指针就是指向1存储的地址。
c风格和string的转换:

#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
int main()
{
    
       
    string a = "someone";
    const char *str=a.c_str();
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45743162/article/details/115117772
今日推荐