以下向 c++ 向量添加元素的方法有什么区别

What's the difference between the following ways of adding elements to a c++ vector

本文关键字:方法 什么 区别 元素 添加 c++ 向量      更新时间:2023-10-16

snippet1:以下摘要打印出0 1,但返回一个空的向量。

vector<int> trial() {
    vector<int> ret;
    ret.reserve(2);
    ret[0] = 0;
    ret[1] = 1;
    cout << ret[0] << " " << ret[1] << "n";
    return ret;
}

摘要2:以下摘要打印出0 1并返回向量包含{0,1}。

vector<int> trial() {
    vector<int> ret;
    ret.push_back(0);
    ret.push_back(1);
    cout << ret[0] << " " << ret[1] << "n";
    return ret;
}

为什么摘要1不像摘要2一样工作。如果我要保留内存并向向量添加值。

reserve()不更改向量大小,您想要的是 resize() it。

相关文章: