| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
C/C++: Searching for unique items in a struct
Hi!
In C/C++, am trying to put only the unique names from one struct into another struct that will have only the unique names (no duplicates). For example, I have a list of cars that has only one piece of info: the make of the car. Here's an example list of cars: Code:
Toyota Jaguar Toyota Nissan Chevrolet Ford Jaguar Nissan Toyota Toyota As you can see, there can be more than one instance of the make of the car in this list. Now, I want to fill a new struct with a unique list of the cars and the number of instances of each car maker. Therefore, I have a struct that is like this: Code:
struct
{
char make[16];
int numberofcars;
} cars[30];
So, after processing the list and filling the struct, I want the struct to have these values: Code:
cars[0].make = "Toyota" cars[0].numberofcars = 4 cars[1].make = "Jaguar" cars[1].numberofcars = 2 cars[2].make = "Nissan" cars[2].numberofcars = 2 cars[3].make = "Chevrolet" cars[3].numberofcars = 1 cars[4].make = "Ford" cars[4].numberofcars = 1 . . . cars[29].make = ... cars[29].numberofcars = ... Is there an easy way to do this using "while loops", "for loops" and "if statements"? I know how to do string comparisons and copy strings into the struct, but the logic I have tried is not working. :-) Oh, and sorting would be nice, but isn't required for my purposes. Thanks, bobert |
|
#2
|
|||
|
|||
|
Someone else gave me a hint on another website and it's working now. This is what he said:
Lets assume you have another variable: carCount that actually tracks the number of cars in use. Then you could write something like the following (note: I am reading from cin; you can easily replace that with your input stream). Code:
struct CarStruct
{
char make[16];
int numberofcars;
};
CarStruct cars[30];
int findCar(const CarStruct *arrayOfCars, int carCount, string nameOfCar);
int insertCar(const CarStruct *arrayOfCars, int &carCount, string nameOfCar);
string nameOfCar;
while (cin >> nameOfCar)
{
// will search the list from beginning for carCount entries for named car.
// returns -1 if not found, index of car if found
int carNdx = findCar(cars, carCount, nameOfCar);
if (carNdx < 0)
{
// adds new entry by incrementing carCount, setting name and zeroing
// number of that make of car. Returns index of newly added car
carNdx = insertCar(cars, carCount, nameOfCar);
}
cars[carNdx].numberOfCars++;
}
bobert |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > C/C++: Searching for unique items in a struct |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|