c++Primer第三章:字符串,向量,数组

String

tips

  1. 头文件中不包含using声明,可能会导致冲突

string上的操作

初始化

string s1(s2);
string s1(n,'c');
string s1("value");

常见操作

1.s写入输出流os中,返回os
os<<s;

2.is读取字符串到s,以空白字符串分割,返回is
is>>s;

3.从is中读取一行赋给s,返回is,包括空格,以回车结束
getline(is,s);
int main(){
	string line;
	while(getline(cin,line))
		cout<<line<<endl;
	return 0;
}
	非int输入结束
	int value;
	while(cin>>value)
	while(cin>>value)
		if(cin.get()!='\n')

4.<,<=,>,=>,字典序比较,大小写敏感

5.获取字符串长度,size()返回的是无符号整型,
string::size_type len = line.size();
auto len = line.size();

遍历

只遍历不修改

string str("just string");
for(auto c:str)
	cout<<c<<endl;

遍历修改

string str("just string");
for(auto &c:str)
	c = toupper(c);
cout<<str<<endl;

比较

  1. 相同比长度
  2. 不同,返回第一对相异字符的比较结果

注意

  1. 字面值不能直接相加
string s1 = "hello" + ","; Wrong

常见函数

函数Value
isalnum( c )数字
isalpha( c )字母
iscntrl( c )控制字符
isdigit( c )数字
isgraph( c )不是空格但是可打印
islower( c )小写字母
isprint( c )可打印字符
ispunct( c )标点符号
isspace( c )空白
isupper( c )大写字母
isxdigit( c )十六进制
tolower( c )转小写
toupper( c )转大写

Vector

初始化

vector<T> v2(v1);
vector<T> v3(n,val);
vector<T> v4(n);执行默认初始化
vector<T> v5(a,b,c...)
vector<T> v6 = {a,b,c...}
{n}(n)的区别
一个元素为n和n个默认初始化元素

注意

1.当循环体内包含向vector对象添加元素的语句,则不可使用范围for循环,end()无穷无尽

2.使用size_type
vector::size_type

常见函数

函数Value
v.push_back()$1600
手机$12
导管$1

访问修改

for的使用和string一致

迭代器

auto b = v.begin(),e = v.end();
函数Value
*iter返回所指元素的引用
iter->mem等价于(*iter).mem
iter->empty(*iter).empty()
–iter,++iter前进,后退一位
itrer.begin() ; iter.end()可以读写
iter.cbegin() ; iter.cend()只能读取
vector< int >::iterator it可以读写
vector< int >:: const_iterator it只可以读

迭代器遍历

for(auto it = s.begin();it != s,end();++it )
	*it = toupper(*it);

迭代器运算

有正有负,是元素之间的间隔

auto mid = v.begin() + v.size()/2;

数组的指针是迭代器

指针可以进行加法运算

int *beg = begin(ia);
int *last = end(ia);
int *p = beg + n;
auto n = end(ia) - begin(ia); 
while(beg < last)
	beg++;

新旧代码接口

string与char*

const char *str = s.c_str();
char *str1 = (char*)s.c_str();//旧版强制转换 

数组与vector

目前还是vector好

int arr = {1,2,3,4,5};
vector<int> ivec(begin(arr),end(arr));
vectoe<int> ivec1(arr+1,arr+4);

多维数组

多维数组访问除最内层外,其他层全是引用
1.auto修改

int cnt = 0;
int ia[3][4] = {{1},{2},{3}};
for(auto &row : ia)
	for(auto &col : row){
		col = cnt;
		cnt ++;
	}

2.auto访问

for(const auto &row : ia)
	for(auto col : row)
		cout<<col<<endl;

3.指针访问

for(auto p = begin(ia);p != end(ia);++p)
	for(auto q = begin(*p);q != end(*p);++q)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值