gpt4 book ai didi

c++ - 从 C++ 中的结构访问单个成员类型的所有元素

转载 作者:太空宇宙 更新时间:2023-11-04 12:13:22 24 4
gpt4 key购买 nike

假设我在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com