假设我在 C++ 中有以下结构
struct Fruit
{
std::string name, description;
}
和
struct Fruit Fruits[]
{
{"orange"," Orange is a hybrid of ancient cultivated origin, possibly between pomelo and mandarin. "},
{"apple", " Apple is the pomaceous fruit of the apple tree, species Malus domestica in the rose family. "},
};
我的问题是,如何在 C++ 中访问一个结构的单个成员类型的所有元素,或者在这种情况下如何列出结构 Fruit 中成员类型名称的所有元素?
如有任何帮助,我们将不胜感激。提前致谢。
最佳答案
也许你需要一个动态的梨数组:
#include <vector>
#include <string>
#include <utility>
#include <iostream>
std::vector<std::pair<std::string, std::string>> fruits {
{ "Apple", "Yum" },
{ "Tomato", "Yuck" }
};
你可以重复这个:
for (auto it = fruits.cbegin(), end = fruits.cend(); it != end; ++it)
{
std::cout << "Fruit: " << it->first << ", Description: " << it->second << "\n";
}
或者使用时髦的新 range-for-loop:
for (auto const & p : fruits) { /* ... p.first etc ... */ }
关于c++ - 从 C++ 中的结构访问单个成员类型的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8856592/