vector pta
时间: 2025-01-11 12:46:12 浏览: 48
### 关于Vector PTA编程教程或常见问题
#### Vector简介
`std::vector` 是 C++ 标准模板库 (STL) 中的一种动态数组容器,能够自动调整大小并提供随机访问特性。这使得 `vector` 成为了处理可变长度数组的理想选择[^1]。
#### 常见PTA题目解析
##### 题目一:向量基本操作
编写一段代码实现对给定整数序列的操作,包括初始化、插入元素到指定位置以及删除特定索引处的元素等功能。
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec;
// 初始化
int n;
cin >> n;
for(int i = 0; i < n; ++i){
int temp;
cin >> temp;
vec.push_back(temp);
}
// 插入元素
int pos, value;
cin >> pos >> value;
if(pos >= 0 && pos <= vec.size()){
vec.insert(vec.begin()+pos,value);
}else{
cout << "Invalid position" << endl;
}
// 删除元素
cin >> pos;
if(pos >= 0 && pos < vec.size()){
vec.erase(vec.begin()+pos);
}else{
cout << "Invalid position" << endl;
}
// 输出结果
for(auto& elem : vec){
cout << elem << ' ';
}
}
```
##### 题目二:最大连续子段和
对于一个由正负整数组成的一维数组,求其任意非空连续子区间内所有元素之和的最大值。
```cpp
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll maxSubArraySum(vector<ll>& nums) {
ll currMax=nums[0], globalMax=nums[0];
for(ll i=1;i<nums.size();i++){
currMax=max(nums[i],currMax+nums[i]);
globalMax=max(globalMax,currMax);
}
return globalMax;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t,n,x;
cin>>t;
while(t--){
cin>>n;
vector<ll>v(n);
for(int i=0;i<n;++i){cin>>v[i];}
cout<<maxSubArraySum(v)<<endl;
}
return 0;
}
```
#### 使用注意事项
当使用 `std::vector` 进行开发时需要注意以下几点:
- 动态分配内存可能会带来性能开销,在高频调用场景下应考虑预估容量以减少重定位次数;
- 访问越界会引发未定义行为,务必确保索引合法有效;
- 对象销毁顺序遵循先进先出原则,即最后加入的对象最先被释放;
阅读全文
相关推荐


















