C++之 标准库类型 Vector和String

   本文对于标准库类型string和vector的基本操作学习,比较简单,,,

   KEY:行字符串的获取,string::size_type的使用,vector元素的插入,迭代器的使用

测试代码:

#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
void testString(){
	string strLine;
	cout << "input string(line):";
	//获取输入流一行的数据,key:不忽略换行符,即换行符也会被判定为输入字符
	getline(cin, strLine);
	cout << "The InputString is:" << strLine << endl;

	string str1;
	cout << "input sting:";
	//输入不接受空格
	cin >> str1;
	cout << "The InputString is:" << str1 <<endl;
	cout << "The First char is:" << str1.at(0) << endl;//==str1[0]
	//字符串长度 ,size_type的使用
	string::size_type len = str1.size();
	cout << "Size is:" << len << endl;
	//字符串相加
	string strA = "hello";
	string strB = "World";
	string strC = strA + strB;
	string strD = strA + "ZFL";//+ 操作符左右操作数必须至少有一个string类型
	cout << "hello + World =" << strC << endl;
	cout << "strA+ZFL=" << strD << endl;
}

void testVector(){
	//vector 初始化
	vector<int> v1(5,10);//v1包含5个元素,每个元素初始化为10
	for (vector<int>::size_type i = 0; i != v1.size(); ++i){
		cout << v1[i]<<" ";
	}
	cout << endl;

	//vector插入元素
	vector<string> vStr;
	string str;
	int count = 0;
	cout << "Input the string(5个):";
	while (count != 5 && cin >> str){
		vStr.push_back(str);
		count++;
	}
	//vector元素遍历
	cout << "The Vector String is:";
	for (vector<string>::iterator itr = vStr.begin(); itr != vStr.end(); ++itr){//如果只是访问元素,不修改其值,最好使用vector<string>::const_iterator
		cout << *itr<<" ";
	}
	cout << endl;
	


}
int main(){
	//testString();
	testVector();
	return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值