以下向 c++ 向量添加元素的方法有什么区别
What's the difference between the following ways of adding elements to a c++ vector
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。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在 c++ 中拥有一组结构的正确方法是什么?
- 通过JNI传递数据数组的最快方法是什么
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 在C++中包含原型文件的正确方法是什么?
- 在 OpenCV C++ 中估计基本矩阵之前对相应点进行归一化的正确方法是什么?
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?