How to create a vector of structs in C++

3 Answers

0 votes
#include <iostream> 
#include <vector> 
  
struct Book { 
    std::string name;
    float price; 
}; 
    
int main() 
{ 
    std::vector<Book> v = { {"c++", 37}, 
                            {"java", 32}, 
                            {"c", 41}, 
                            {"php", 29},
                            {"python", 35} }; 
                   
    for (const auto &b : v) {
        std::cout << b.name << " " << b.price << "\n";
    }
} 
  
  
  
  
/*
run:
  
c++ 37
java 32
c 41
php 29
python 35
  
*/

 



answered May 11, 2021 by avibootz
edited Feb 5, 2023 by avibootz
0 votes
#include <iostream>
#include <vector>

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> ve;
    
    ve.push_back({3, 8, 1});
    ve.push_back({9, 0, 6});
    
    for (int i = 0; i < ve.size(); i++)
        std::cout << ve[i] << "\n";
}



/*
run:

3 8 1
9 0 6

*/


 



answered Feb 5, 2023 by avibootz
0 votes
#include <iostream>
#include <vector>

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> ve;
    
    ve.push_back({3, 8, 1});
    ve.push_back({9, 0, 6});
    
    for (Vertex& v : ve)
        std::cout << v << "\n";
}



/*
run:

3 8 1
9 0 6

*/


 



answered Feb 5, 2023 by avibootz
...