Home > Software engineering >  Iterating the creation of objects in C
Iterating the creation of objects in C

Time:03-19

I want to be able to create N skyscrapers. Using an inputdata string, I would like to give them coordinate values of their X and Y positions. My main function I used "i" to demonstrate that I am trying to create as many skyscrapers as I can using the input data. Essentially, I would like to create N/3 skyscrapers and assign the input to coordinates for each.

#include <iostream>
#include <vector>
#include <string>
#include <math.h>

using namespace std;  
vector<int> inputData = {1, 4, 10, 3, 5, 7, 9, 10, 4, 11, 3, 2, 14, 5, 5}; 
int N = inputData.size();

class Buildings{
    public: 
        int yCoordinateLow; 
        int yCoordinateHigh; 
        int xCoordinateLeft; 
        int xCoordinateRight;

}; 

int main(){ 
    for(int i=0; i<N; i=i 3){
        Buildings skyscraper; 
        skyscraper.xCoordianteLeft = inputData.at(i); 
        skyscraper.yCoordianteLow = 0;
        skyscraper.yCoordinateHigh = inputData.at(i 1); 
        skyscraper.xCoordinateRight = inputData.at(i 2); 
    }
    return 0;
}

CodePudding user response:

Jeff Atwood once said: use the best tools money can buy. And those aren't even expensive: Visual Studio community edition is free. Such a proper IDE will tell you that the skyscraper is unused except for the assignments.

Visual Studio tooltip

Since you probably want to do something with those skyscrapers later, you should store them somewhere, e.g. in another vector.

int main() {
    vector<Buildings> skyscrapers;
    for (int i = 0; i < N; i = i   3) {
        Buildings skyscraper{};
        skyscraper.xCoordinateLeft = inputData.at(i);
        skyscraper.yCoordinateLow = 0;
        skyscraper.yCoordinateHigh = inputData.at(i   1);
        skyscraper.xCoordinateRight = inputData.at(i   2);
        skyscrapers.push_back(skyscraper);
    }
    return 0;
}

Other than that, I'd say the loop works fine as long as there are N*3 coordinates in the original vector.

If you e.g. implement a game, you would probably not hard code the skyscraper coordinates in a vector but rather read that data from a file, potentially per level.

Instead of doing all the error-prone coding, maybe you want to initialize the skyscrapers immediately

vector<Buildings> skyscrapers = {{1,0,4,10}, {3,0,5,7}, {9,0,10,4}, {11,0,3,4}, {14,0,5,5}};
  • Related