跳到主内容
C++
文章阅读

C++使用vector,以及优化技巧

2025/12/1671 次阅读2 分钟

基本使用


#include <iostream>
#include <ostream>
#include <vector>
//
// Created by ldd on 2024/1/28.
//
struct Vertex {
    float x,y,z;
};
std::ostream& operator<<(std::ostream& stream,const Vertex& vertex) {
    stream << vertex.x << ", " << vertex.y << ", " << vertex.z;
    return stream;
}
int main() {
    std::vector<Vertex> vertices;
    vertices.push_back({1,2,3});
    vertices.push_back({4,5,6});
    for (Vertex& vertex : vertices) {
        std::cout << vertex << std::endl;
    }
    //移除下标为0的数据
    vertices.erase(vertices.begin());
    //清理所有数据
    vertices.clear();
}

优化

  • 使用 vertices.reserve(3);来初始化分配内存空间

  • 使用emplace_back()函数来放置元素,例: vertices.emplace_back(Vertex({1,2,3}));

返回顶部