@Moritz
2019-01-25T05:12:58.000000Z
字数 2359
阅读 495
C++primer练习 C++ 编程 所有文稿
Read a sequence of words from cin and store the values a vector. After you’ve read all the words, process the vector and change each word to uppercase. Print the transformed elements, eight words to a line.
#include <iostream>#include <vector>using namespace std;int main(){vector<string> v;string t;char c;int i=0,u='A'-'a';while(cin>>t) //怎么停止输入?{v.push_back(t);i++;if(i>2) break;}for(auto &c:v){for(i=0;c[i]!='\0';i++) //不能用*(c+i)的形式,不能创建引用的指针{if (c[i]>='a'&&c[i]<='z') c[i]+=u;}}for(auto c:v)cout<<c<<endl;return 0;}
Better Version
for (auto &str : v)//把全部字符改为大写{for (auto &c : str)//嵌套范围for代替下标遍历{c = toupper(c);//string函数}}
List three ways to define a vector and give it ten elements, each with the value 42. Indicate whether there is a preferred way to do so and why
vector<int> v1(10,42);vector<int> v2={42,42,42,42,42,42,42,42,42,42};vector<int> v3(10);for(auto &i:v3)i=42;
Read a set of integers into a vector. Print the sum of each pair of adjacent elements. Change your program so that it prints the sum of the first and last elements, followed by the sum of the second and second-tolast, and so on.
#include <iostream>#include <vector>using namespace std;int main(){vector<int> v;int n,i,t;cin>>n;for(i=0;i<n;i++) {cin>>t;v.push_back(t);}for(i=0;i<n-1;) {cout<<v[i]<<" "<<v[i+1]<<endl;i+=2;}cout<<endl;for(i=0;i<n/2;i++) cout<<v[i]+v[n-1-i]<<endl;return 0;}
2019.1.23
iaWrite three different versions of a program to print the elements of ia. In all three programs write all the types directly. That is, do not use a type alias, auto, or decltype to simplify the code.
#include <iostream>using namespace std;int ia[3][4]= {0,1,2,3,4,5,6,7,8,9,0,11};
use a range for
ia中的元素是含有四个整型数元素的数组,所以row是含有四个整型数元素的数组的引用(别名),在第二层for语句中可以直接使用row别名。
for(int (&row)[4]:ia){for(int col:row)cout<<col<<'\t';cout<<endl;}
use an ordinary for loop with subscripts
注意类型名是size_t。
for(size_t i=0; i<3; i++){for(size_t j=0; j<4; j++)cout<<ia[i][j]<<'\t';cout<<endl;}
use an ordinary for loop with pointers
row和col都是指针类型,int (*row)[4]=ia,把ia首元素(即含有四个整型数元素的数组)地址赋给row;第二层循环中,col是指向整型的指针,*row解引用得到一个数组(名),并把该数组首元素地址赋给col。
注意输出col的时候要加上*,代表访问col所指地址的值。
for(int (*row)[4]=ia; row!=ia+3; row++){for(int *col=*row; col!=*row+4; col++)cout<<*col<<'\t';cout<<endl;}
若不加上*,输出的是col本身(即地址)
/*0x28fed0 0x28fed4 0x28fed8 0x28fedc0x28fee0 0x28fee4 0x28fee8 0x28feec0x28fef0 0x28fef4 0x28fef8 0x28fefcProcess returned 0 (0x0) execution time : 0.265 sPress any key to continue.*/
2019.1.25
