# 简介
向量 vector
是可以改变其大小的线性序列容器,像数组一样,向量使用连续的空间存储元素,这表明向量可以像数组一样通过下标来访问其元素,但不同于数组的是,向量的大小可以动态变化。
| |
| #include <iostream> |
| #include <vector> |
| #include <cstdio> |
| |
| using namespace std; |
| |
| vector<int> myVector; |
| |
| int main() |
| { |
| for (int i = 0; i < 5; ++i) |
| { |
| myVector.push_back(i); |
| } |
| myVector.insert(myVector.begin(), 3, 15); |
| myVector.pop_back(); |
| for (int i = 0; i < myVector.size(); ++i) |
| { |
| printf("%d ", myVector[i]); |
| } |
| printf("\n"); |
| printf("the 5th element of myVector:%d\n", myVector[4]); |
| printf("the size of myVector:%d\n", myVector.size()); |
| myVector.erase(myVector.begin() + 5, myVector.end()); |
| vector<int>::iterator it; |
| for (it = myVector.begin(); it != myVector.end(); it++) |
| { |
| printf("%d ", *it); |
| } |
| printf("\n"); |
| myVector.clear(); |
| return 0; |
| } |
| 15 15 15 0 1 2 3 |
| the 5th element of myVector:1 |
| the size of myVector:7 |
| 15 15 15 0 1 |
# 向量的应用
# 完数与盈数
一个数如果恰好等于它的各因子 (该数本身除外) 之和,如: 6=3+2+1
。则称其为 “完数”;若因子之和大于该数,则称其为 “盈数”。 求出 2
到 60
之间所有 “完数” 和 “盈数”。
| #include <iostream> |
| #include <vector> |
| #include <cstdio> |
| |
| using namespace std; |
| |
| vector<int> numberE; |
| vector<int> numberG; |
| |
| int Sum(int x) |
| { |
| int sum = 0; |
| for (int i = 1; i < x; ++i) |
| { |
| if (x % i == 0) |
| { |
| sum += i; |
| } |
| } |
| return sum; |
| } |
| |
| int main() |
| { |
| for (int i = 2; i <= 60; ++i) |
| { |
| if (i == Sum(i)) |
| { |
| numberE.push_back(i); |
| } |
| else if (i < Sum(i)) |
| { |
| numberG.push_back(i); |
| } |
| } |
| printf("E:"); |
| for (int i = 0; i < numberE.size(); ++i) |
| { |
| printf("%d ", numberE[i]); |
| } |
| printf("\n"); |
| printf("G:"); |
| for (int i = 0; i < numberG.size(); ++i) |
| { |
| printf("%d ", numberG[i]); |
| } |
| printf("\n"); |
| return 0; |
| } |
| E:6 28 |
| G:12 18 20 24 30 36 40 42 48 54 56 60 |