Im writing a simple program that alternates two vectors and push_backs's them into a 3rd vector however i get a segmentation fault error (core dumped). I did some research and it seems to be I'm accessing memory that either isn't there or I'm not supposed to. I know this a simple fix but I'm pretty new to C++ so anything would be appreciated.
vector<int> alternate(vector<int> a, vector<int> b)
{
int n = a.size();
int m = b.size();
vector<int> c(n + m);
int i;
for(i = 0; i < a.size() and i < b.size (); i++)
{
c.push_back(a[i]);
c.push_back(b[i]);
}
return c;
}
int main () {
vector<int> a,b,c;
int temp1;
int temp2;
while (temp1 != -1) {
cin >> temp1;
if(temp1 == -1) {
break;
}
a.push_back(temp1);
}
while (temp2 != -1) {
cin >> temp2;
if(temp2 == -1) {
break;
}
b.push_back(temp2);
}
c = alternate(a,b);
int i;
for(i = 0; i < c.size(); i++) {
cout << c[i] << endl;
}
}
As far as I can see you have a two problems here:
temp1
and temp2
in you conditions and you didn't initialize them, that's a UB. Try int temp1 = 0; int temp2 = 0;
int temp1 = 0; int temp2 = 0;
. alternate
you are initializing your returning vector with the sum of your two input vectors like this vector<int> c(n + m);
, then you use push_back
to add elements of these inputs. this way you will have n+m
zeros at start of your returning vector then elements of your input. I'm pretty sure you don't want this. you don't need to give default size to you vector, just use push_back
or if you insist on using default size then assign values to indexes of your vector. There are a few problems with your code, some of which are mentioned above. The most important problems are the following:
Other lesser problems are the following:
After all that, the result should look something like the following:
#include <iostream>
#include <vector>
using namespace std;
vector<int> alternate(const vector<int>& a, const vector<int>& b)
{
const auto n = a.size();
const auto m = b.size();
const auto N = max(n, m);
vector<int> c;
c.reserve(n+m);
for(size_t i = 0; i < N; ++i)
{
if (i < n) c.push_back(a[i]);
if (i < m) c.push_back(b[i]);
}
return c;
}
int main () {
vector<int> a,b,c;
while (true) {
int temp;
cin >> temp;
if(temp == -1) {
break;
}
a.push_back(temp);
}
while (true) {
int temp;
cin >> temp;
if(temp == -1) {
break;
}
b.push_back(temp);
}
c = alternate(a,b);
for (auto val : c) {
cout << val << endl;
}
}
正如两个答案所指出的,未初始化的变量以及使我的“ c”向量太大是罪魁祸首
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.