c++primer 练习 p99 3.4.1 迭代器 大写 cbegin 随机函数

来源:互联网 发布:直销软件定制 编辑:程序博客网 时间:2024/06/04 19:58
// p101_342.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include<iostream>
#include<string>
#include<vector>
#include<ctime>//生成随机数需要
#include<cstdlib>//生成随机数需要
using namespace std;
int main()
{
/*
//3.21
vector<int> v1{ 10 };
//auto it = v1.cbegin();
cout << "v1元素个数是:" << v1.size() << endl;
if (v1.cbegin() != v1.cend())//奇怪,这里前面为什么不能加auto??????  只有定义的时候前面才加类型;此外,这里只输出,不更改,所以用cbegin,cend不能不加c
{
for (auto it = v1.cbegin(); it != v1.cend(); ++it)
cout << *it << " ";//这里用空格分开比回车更好
}
else
cout << "empty!" << endl;
*/




/*
//3.22   这个程序怎么测试呢???
vector<string> text;//不是sring  而是vector<string>因为你这里采取的是对容器的一系列操作,这是个容器
string s;//这是text里面的每一句话,用getline(cin,s)把它放到容器vector<string> text中,然后再对容器进行操作,回车也读进来了,后面检测到空(这里是回车),就是一段
char  ch = 'n';
while (getline(cin, s))
text.push_back(s);
for (auto it = text.begin(); it != text.end() && !it->empty(); ++it)//1.it++????2.empty()????这是找出那一段,是一段一段的测
{
for (auto it2 = it->begin(); it2 != it->end(); it2++)//这是对这一段里面找到的那个s的词,逐词的循环,?????为什么不用it.begin()
*it2 = toupper(*it2);
cout << *it << endl; //这是输出当前的字符串。而不是输入当前的每一个词
//为什么不能之间cout<<toupper(*it)<<endl??因为toupper()是对每一个字母操作的,而*it是一个字符串,*it2才是一个字母
}
*/


//3.23


vector<int> v1;
//练习随机生成数字
srand((unsigned)time(NULL));//生成随机种子
for (int i = 0; i < 10; i++)
{
v1.push_back(rand() % 1000);//每次循环生成一个1000以内的随机数添加都v1中
}
for (auto it = v1.cbegin(); it != v1.cend(); it++)//原来的数只输出不改变用cbegin(),cend(),后面的改变了就用begin(),end()
{
cout << *it << " ";
}
cout << endl;
for (auto it = v1.begin(); it != v1.end(); it++)
{
*it = 2 * *it;
cout << *it << " ";
    }
cout << endl;
    system("pause");
    return 0;
}