简体   繁体   中英

(C++) How to make a for loop that creates certain number of class's object

How does one make a for loop that creates a certain number of class objects with names that add in numerical order.

example struct:

struct Point{
    int x, y;

    Point(int inputx, int inputy){
        x = inputx;
        y = inputy;
        }

    };

How would I implement a for loop to create Point Point1(x,y), Point Point2(x,y), Point Point3(x,y), etc.

You can't create variables names like that using a loop.

Perhaps a std::map<int, Point> will work for your needs.

std::map<int, Point> pointsMap;
for (int i = 0; i < N; ++i )
{
   pointsMap[i+1] = Point{...}:
}

Then, can use pointMap[n] to access the items from the map.

If you want to use a string as the key of the map, you can construct the keys in the loop using i .

std::map<std::string, Point> pointsMap;
for (int i = 0; i < N; ++i )
{
   std::string key = "Point" + std::to_string(i+1);
   pointsMap[key] = Point{...}:
}

Then, can use pointMap[key] to access the items from the map.

Symbol names are compile-time entities not present in the compiled run-time code, so generating a symbol name at run-time makes no sense. Instead you would use an array or container class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM