Storing Multiple Names in an Array in C : Traditional Arrays vs. std::vector
When working with C and the need arises to store multiple names, two primary options arise: using a traditional array or leveraging the std::vector from the Standard Template Library (STL).
Using a Traditional Array
If you know the maximum number of names you want to store and this number will not change, a fixed-size array is a suitable choice. This approach offers simplicity and performance benefits but incurs the responsibility of managing the array size. Here's an example:
Example using a traditional array:
#include iostream #include string int main() { const int MAX_NAMES 5; // Define the maximum number of names std::string names[MAX_NAMES]; // Declare an array of strings // Input names for(int i 0; iUsing std::vector
For a more flexible solution that can grow or shrink in size during runtime, the std::vector is the preferred choice. This dynamic container allows you to manage the size of the collection without worrying about over- or under-flowing manually allocated fixed-size arrays. Here's a practical example:
Example using std::vector:
#include iostream #include string #include vector int main() { std::vector names; // Declare a vector of strings std::string name; char choice; // Input names until the user decides to stop do { std::cout Enter a name (y/Y to continue): ; std::getline(std::cin, name); names.push_back(name); // Add the name to the vector std::cout Choice (y/Y): ; std::cin choice; std::cin.ignore(); // Ignore the newline character left in the input buffer } while (choice 'y' || choice 'Y'); // Output names std::cout Stored names:; for(const auto n : names) { std::coutSummary
Select a fixed-size array if the number of names is known and constant, offering simplicity and performance. On the other hand, opt for std::vector for a dynamic solution that can adapt to changing sizes.
Implementing std::vector in C
If you prefer a predefined set of names stored in a std::vector, you can use the following code:
#include iostream #include string #include vector int main() { std::vector names; // Storing names. names.push_back(Rony); names.push_back(Tony); names.push_back(James); names.push_back(Sagar); names.push_back(Pankaj); // To access the stored names. auto it (); // Iterator. while(it ! names.end()) { std::coutThe output will be:
Rony Tony James Sagar PankajThis method offers a simple and efficient way to store and access multiple names without managing the array size manually. Whether you choose a traditional array or std::vector, the flexibility and adaptability of C ensure that you can meet your needs effectively.