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

标签 c++ visual-studio-2010

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

相关文章:

c++ - 多次调用更新时 Qt 应用程序崩溃

javascript - VS 2010 Javascript 匹配大括号/括号突出显示

database - 在 VB.Net 2010 中读取/写入 Access 数据库

wpf - WPF 中设计时数据的问题

c++ - 优化循环与代码复制

c++ - opencv:将 Mat 转换为 IplImage 问题

c# - 使用不同的参数重新加载表单 c#

c++ - 错误 LNK2019 ARuco 和 OpenCV VS2010 c++

c++ - 在 Windows 上编译 libssh2

c++ - 如何从 std::sample 中提取剩余元素