How to initialize and print a vector of objects in C++

1 Answer

0 votes
#include <iostream>
#include <iomanip>
#include <vector>

class Example {
public:
    Example(int _x, int _y, int _z) {
        x = _x;
        y = _y;
        z = _z;
    }
    void Print() const {
        std::cout << std::setw(3) << x << std::setw(3) << y << std::setw(3) << z << "\n";
    }

private:
    int x, y, z;
};

int main() {
    std::vector<Example> vecobjects = {
        Example( 3,  9,  0),
        Example( 1,  7, 32),
        Example( 7,  6,  4),
        Example( 0, 15, 11),
        Example(12, 16, 99)
    };

    for (int i = 1; i < vecobjects.size(); i++ ) {
        vecobjects[i].Print();
    }
}


/*
run:

  1  7 32
  7  6  4
  0 15 11
 12 16 99

*/

 



answered Oct 8, 2024 by avibootz

Related questions

1 answer 121 views
2 answers 175 views
1 answer 182 views
2 answers 197 views
2 answers 184 views
...