c++ - 段错误错误 C++

标签 c++ memory vector

我正在编写一个简单的程序,交替使用两个 vector 并将它们 push_backs 到第三个 vector 中,但是我遇到了段错误(核心已转储)。我做了一些研究,似乎我正在访问不存在或我不应该访问的内存。我知道这是一个简单的修复,但我是 C++ 的新手,所以我们将不胜感激。

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;
    }
}

最佳答案

据我所知,您在这里有两个问题:

  1. 您使用了 temp1temp2在你的条件下,你没有初始化它们,那是一个 UB。尝试 int temp1 = 0; int temp2 = 0; .
  2. 函数alternate你正在用你的两个输入 vector 的总和来初始化你的返回 vector ,就像这样 vector<int> c(n + m); , 然后你使用 push_back添加这些输入的元素。这样你就会有n+m返回 vector 开头的零,然后是输入的元素。我很确定你不想要这个。你不需要为你的 vector 提供默认大小,只需使用 push_back或者,如果您坚持使用默认大小,则将值分配给 vector 的索引。

关于c++ - 段错误错误 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49807695/

相关文章:

c++ - 对象指针随机指向 0x00000

java - 是否有人仍在使用 Vector(而不是 Collections.synchronizedList(List list)/CopyOnWriteArrayList)?

c++ - IEEE 754/IEC 559

c++ - 使用结构作为私有(private)成员在链接列表类中定义 ListNode

c++ - 为什么我的 UniquePtr 实现会重复释放?

c++ - 模板化函数在返回值时崩溃

c++ - 使用 vector 进行 gsl 线性拟合

c++ - 为什么 int 指针的 const vector 中的取消引用元素是可变的?

c++ - 将类型转换/更改为指向类型的指针 (SDL_Rect)

iOS、iPhone、iPad : is slow loading a good strategy to avoid memory crashes?