题解分享
题解分享简介
vector插入 - 题解
```
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> vec;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
vec.push_back(a);
}
int x, y;
cin >> x;
cin >> y;
vec.insert(vec.begin() + x - 1, y);
for (const auto& elem : vec) {
cout << elem << "\n";
}
cout << endl;
return 0;
}
```
查看全文
0
0
1
2
vector插入 - 题解
```
/*
std::vector 的 insert 方法需要一个迭代器作为插入位置,而不是直接使用索引。
例如,arr.insert(arr.begin() + x, y) 可以在索引 x 的位置插入值 y。
你不能直接对 vector<int> 的某个元素(如 arr[x])调用 insert 方法,
因为 arr[x] 是一个 int 类型,而不是一个容器。
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for ( int i = 0; i < n; i++ ) {
cin >> arr[i];
//cout << arr[i] << endl;
}
int x,y;
cin >> x >> y;
//确保 x 的值在合法范围内。
//如果 x 等于 n,应该允许在 vector 的末尾插入元素。
arr.insert(arr.begin() + x - 1, y);
for ( size_t i = 0; i < arr.size(); i++ ) {
//cin >> arr[i];
cout << arr[i] << endl;
}
return 0;
}
```
查看全文
0
0
0
5
vector插入 - 题解
```
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
vector<int> a;
int n, t, pos;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> t;
a.push_back(t);
}
cin >> pos;
cin >> t;
a.insert(a.begin() + pos - 1, t);
for (int i = 0; i < a.size(); i++) {
cout << a[i] << endl;
}
return 0;
}
```
查看全文
0
0
0
3
vector插入 - 题解
```
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m, x, y;
cin >> n;
vector<int> arr;
for (int i = 0; i < n; i++)
{
cin >> m;
arr.push_back(m);
}
cin >> x >> y;
arr.insert(arr.begin() + x - 1, y);
for (auto & ele : arr)
{
cout << ele << '\n';
}
return 0;
}
```
查看全文
0
0
0
3
vector插入 - 题解
```
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n,a,b,c;
cin>>n;
vector<int> arr;
for(int i=0;i<n;i++)
{
cin>>a;
arr.push_back(a);
}
cin>>b>>c;
arr.insert(arr.begin()+b-1,c);
for(const auto&it:arr)
{
cout<<it<<'\n';
}
return 0;
}
```
查看全文
0
0
0
1
vector插入 - 题解
include
include
using namespace std;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
```
vector<int> arr;
int n, num, pos, val;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> num;
arr.push_back(num);
}
cin >> pos;
cin >> val;
arr.insert(arr.begin() + pos - 1, val);
vector<int> ::iterator it;
for (it = arr.begin(); it != arr.end(); it++)
{
cout << *it << endl;
}
return 0;
```
}
查看全文
0
0
0
2



