关于创建Name_class类、vector存两类数据及构造函数初始化列表的咨询
Hey there! Let's break down your questions step by step, nice and clear.
That line Name_value(std::string n, int v) :name(n), value(v) { } is what's called a constructor initializer list in C++. It's the most efficient (and sometimes mandatory) way to initialize class member variables. Let's unpack it:
Name_value(std::string n, int v): This is the constructor signature—it takes astd::stringand anintas inputs to create aName_valueobject.:name(n), value(v): This is the initializer list. Right after the colon, we list each member variable we want to initialize, paired with the value we want to give it (separated by commas):name(n): This directly initializes the class membernameusing the input parametern. Think of it as setting the value ofnamethe moment it's created, rather than creating it empty then assigning a value later.value(v): Same logic here—we initialize theintmembervaluewith the inputvas soon as it exists.
{ }: The empty function body means all initialization work is already done in the initializer list; no extra assignment steps are needed here.
To put it in perspective, here's the less efficient alternative using in-body assignment:
Name_value(std::string n, int v) { name = n; // name was already default-initialized, now we overwrite it value = v; // same for value }
The initializer list skips that default initialization step, making it faster. Plus, for certain members like const variables or references, you can't use in-body assignment—you have to use the initializer list.
Name_class & Storing Two Data Types in a Single Vector Your existing Name_value class already does the heavy lifting of wrapping two data types (std::string and int) into one object. Let's rename it to Name_class and show how to use a std::vector to store multiple instances of it:
#include "std_library_facilities.h" void error(std::string b) { throw std::runtime_error(b); } class Name_class { public: std::string name; int value; // We'll keep using the initializer list for efficiency Name_class(std::string n, int v) : name(n), value(v) { } }; int main() { // Create a vector that holds Name_class objects std::vector<Name_class> name_collection; // Add objects to the vector (emplace_back constructs them directly in the vector) name_collection.emplace_back("Alice", 28); name_collection.emplace_back("Bob", 32); name_collection.emplace_back("Charlie", 25); // Loop through and print the stored data for (const auto& item : name_collection) { std::cout << "Name: " << item.name << ", Value: " << item.value << "\n"; } return 0; }
By storing Name_class objects in the vector, you're effectively storing pairs of string and int values in a single container. Each Name_class instance bundles the two data types together, so the vector only needs to handle one type of object.
内容的提问来源于stack exchange,提问作者x blade

