c++ - 将元素添加到向量
问题描述
我需要使用合并排序对 2 个向量(A 和 B)进行排序,并将排序后的元素放入第三个向量(R)中。
在 A (1,3,5) 和 B 为 (2,4,6) 中的 3 个元素的测试中,我的代码运行正常,直到我必须插入第 4 个元素。此时我的代码因向量下标超出范围错误而崩溃。
这是我第一次使用向量,但我认为该push_back()
函数会调整向量的大小。我的预感是目标向量 (R) 只能容纳 3 个元素,所以当我插入第 4 个元素时,我的代码会崩溃。我需要做些什么来调整 R 的大小吗?
using namespace std;
#include <iostream>
#include <vector>
// combine two sorted lists A and B into R
// displays comparison every time it is done
void combine(vector<int> A, vector<int> B, vector<int>& R)
{
int ia = 1;
int ib = 1;
int ir = 1;
while (!A.empty() && !B.empty()) {
if (A[ia] < B[ib]) {
R.push_back(A[ia]);
ia++;
ir++;
}
else {
R.push_back(B[ib]);
ib++;
ir++;
}
}
if (!A.empty()) {
for (int i = ia; i < A.size(); i++) {
R.push_back(A[i]);
}
}
else if (!B.empty()) {
for (int i = ib; i < B.size(); i++) {
R.push_back(B[i]);
}
}
cout << "comparison" << endl;
// be careful -- R comes in as an empty vector
}
int main()
{
vector<int> L1;
vector<int> L2;
vector<int> L3;
int N; // how many elements in each of L1 and L2
int e; // for each element
cout << "How many elements in each list?" << endl;
cin >> N;
cout << "List1" << endl;
for (int i = 1; i <= N; i++)
{
cout << "element :"; cin >> e; L1.push_back(e);
}
cout << "List2" << endl;
for (int i = 1; i <= N; i++)
{
cout << "element :"; cin >> e; L2.push_back(e);
}
combine(L1, L2, L3);
cout << "The result is: ";
for (int i = 0; i < N * 2; i++)
{
cout << L3[i];
} cout << endl;
}// end of main
解决方案
向量 A 和 B 始终不为空,除非 pop_front
就像喜欢一样,
if(A.at(0) < B.at(0)) {
C.push_back(A.at(0));
A.pop_front();
}
或者,循环直到 A 和 B 的大小
int ia = 0;
int ib = 0;
while(ia < A.size() && ib < B.size())
{
if(A.at(ia) < B.at(ib))
{
C.push_back(A.at(ia));
ia++;
}
// ...
}
推荐阅读
- networkx - networkx ego_graph 适用于 geopandas 系列加速
- javascript - How can I reverse date time to ajax date time
- python - 对具有相同值计数的行进行排序
- javascript - Vue.JS 数据属性未定义
- excel - 将 3 dim 从 excel 读入 ilog
- vba - 检查Sharepoint中是否存在文件并保存
- azure - 从 Azure Databricks 写入 Azure Blob 存储时出现重复的 Blob 创建事件
- gatsby - 我想使用 gatsbyjs 在 mdx 文件中使用图像,但它显示 2 个图像而不是一个
- vba - 从 Outlook 昵称中提取 SMTP 地址
- javascript - 主选项卡需要仅使用 html、css 和 javascript 嵌套的子选项卡