primer_C++_3.3 标准库类型vector
/* * 用cin读入一组整数并把他们存入一个vector对象 */ #include <iostream> #include <vector> using namespace std; int main() { cout << "输入一组整数:"; int v2; vector<int> v1; //创建vector对象 // for (int t=0;t!=100;++t) // v1.push_back(t); while (cin >> v2) { v1.push_back(v2); //把v2添加到v1后面 } cout << "输出vector:"; for(auto c:v1) cout << c; return 0; }
#include <iostream> #include <string> #include <vector> using namespace std; int main() { cout << "输入一组字符串:"; string v2; vector<string> v1; //创建vector对象 while (cin >> v2) { v1.push_back(v2); //把v2添加到v1后面 } cout << "输出vector:"; for(auto c:v1) cout << c; return 0; }
#include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> v1; //创建一个空vector对象 string v2; while (cin >> v2){ //输入字符串 v1.push_back(v2); //把v2添加到v1后面 } for (auto &t : v1) //读取vector中的每个元素 for (auto &a : t) //对读取的元素的每个字符串进行操作 a = toupper(a); //对小写字母转成大写 for(auto t:v1 ) //读取v1中的每个元素 cout << t << endl; return 0; }
不合法,ivec为空vector。
vector<int> ivec {0};
ivec[0]=42;
vector<int> v1 {42,42,42,42,42,42,42,42,42,42}; vector<int> v2 (10,42); vector<int> v3 = v2;
#include <iostream> #include <vector> using namespace std; int main() { cout << "输入一组整数:" << endl; vector<int> v1; int a ; while (cin >> a ) v1.push_back(a); if (v1.size() == 1) { //输入一个值时 cout << v1[0]; }else { for (int i = 0; i < v1.size() - 1; ++i) { cout << v1[i] + v1[i + 1]<<endl; } } return 0; }