C++ - 未获得控制台的预期输出

C++ - Not Getting Expected Output to Console

本文关键字:输出 控制台 C++      更新时间:2023-10-16

我是个白痴,我想知道为什么这段代码不打印,"hello"? 如果我注释掉 vector.push_back((,它似乎打印...

#include <iostream>
#include <vector>
using namespace std;
struct point {
  int x,y;
  point(int x, int y) : x(x), y(y) {}
};
int main() {
  point coord(4,4);
  vector<vector<point>> v;
  v[0].push_back(coord);
  cout << "hello" << endl;
  return 0;
}

你的向量大小为 0,里面绝对没有任何东西。因此,当你告诉一个不存在的向量用一些数据推回去时,周围的记忆就会发生奇怪的事情。在这种情况下(如果我错了,请纠正我(,您最终会跳过/覆盖包含调用cout <<指令的区域。

#include <iostream>
#include <vector>
using namespace std;
struct point {
    int x,y;
    point(int x, int y) : x(x), y(y) {}
};
int main() {
    point coord(4,4);
    vector<vector<point>> v;
    v.push_back(vector<point>()); // need this one
    v[0].push_back(coord);
    cout << "hello" << endl;
    return 0;
}