vector
标准库类型vector表示对象的集合,能容纳绝大多数类型的对象。
#include <vector>
using std::vector;
定义和初始化
vector<T> v1;
vector<T> v2(v1);
vector<T> v2 = v1;
vector<T> v3(n, val);
vector<T> v4(n);
vector<T> v5{a,b,c... };
vector<T> v5={a,b,c...};
()与{}
用圆括号表示用括号内提供的值来构造vector对象 用花括号表示用括号内提供的值来列表初始化vector对象,初始化尽可能把花括号的值当成是元素初始值
vector<int> v1(10);
vector<int> v2{10};
vector<int> v3(10,1);
vector<int> v2{10,1};
当列表初始化无法执行时,会考虑其他初始化方式
vector<string> v5{"hi"};
vector<string> v6("hi");
vector<string> v7{10};
vector<string> v8{10, "hi"};
vector操作
v.empty()
v.size()
v.push_back(t)
v[n]
v1 = v2
v1 = {a,b,c...}
v1 == v2
v1 != v2
<, <=, >, >=
vector不能用下标的方式添加新元素
习题
3.14
void q3_14(){
int i;
vector<int> v;
while(cin>>i)
v.push_back(i);
}
3.15
void q3_15(){
string s;
vector<string> v;
while(cin>>s)
v.push_back(s);
}
3.17
void q3_17() {
string s;
char c1;
vector<string> v;
while ((cin >> s).get(c1)) {
if (c1 == '\n')
break;
v.push_back(s);
}
for (auto &i : v) {
for(auto &c :i)
c=toupper(c);
}
for (auto &i : v)
cout << i << endl;
}
void q3_17() {
vector<string> vctr;
string s;
decltype(vctr.size()) index = 0;
while (cin >> s){
for (auto& c : s)
c = toupper(c);
vctr.push_back(s);
cout << vctr[index] << endl;
index += 1;
}
}
3.19
vector<int> v(10,42);
vector<int> v{42, 42, 42, 42, 42, 42, 42, 42, 42, 42};
3.20 (网上找了一下怎么跳出cin的那个while循环)
void q3_20(){
int s;
char c1;
vector<int> v;
while ((cin >> s).get(c1)) {
v.push_back(s);
if (c1 == '\n')
break;
}
size_t size = v.size();
for (auto i = 0; i<size - 1; ++i) {
cout << v[i] + v[i + 1]<<" ";
}
cout << endl;
for (auto i = 0; i < size / 2; ++i) {
cout << v[i] + v[size - i - 1] << " ";
}
}
|