samedi 18 avril 2020

Performance comparison between three ways to read and store an array of objects

I'm trying to improve my coding skills in problem-solving using C++. Hence, I'm curious to know which one of the following three suggested examples is faster and better to use, as well as the best way to evaluate the performance.

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5;

struct Car {
    int id, price;
    Car(int _id, int _price) : id(_id), price(_price) {}
};

struct Boat {
    int id, price;
};

struct Motorcycle {
    int id, price;
};

int main() {
    // ------------ section1 ------------
    int n1;
    scanf("%d", &n1);
    vector<Car> cars;
    for (int i = 0; i < n1; i++) {
        int id, price;
        scanf("%d%d", &id, &price);
        cars.emplace_back(id, price);
    }
    // ------------ section2 ------------
    int n2;
    scanf("%d", &n2);
    Boat boats[N];
    for (int i = 0; i < n2; i++) {
        int id, price;
        scanf("%d%d", &id, &price);
        boats[i] = {id, price};
    }
    // ------------ section3 ------------
    int n3;
    scanf("%d", &n3);
    vector<Motorcycle> motorcycles(n3);
    for (auto& motorcycle : motorcycles) {
        scanf("%d%d", &motorcycle.id, &motorcycle.price);
    }
    return 0;
}

However, I believe that the ordinary array is faster than the std::vector.

Aucun commentaire:

Enregistrer un commentaire