首頁  >  文章  >  後端開發  >  如何在單一 C 容器中儲存不同的資料類型?

如何在單一 C 容器中儲存不同的資料類型?

Linda Hamilton
Linda Hamilton原創
2024-10-26 08:55:29195瀏覽

How can I store different data types in a single C   container?

如何在單一C 容器中儲存不同的資料類型

在C 中,向量和地圖等容器通常會保存單一物件資料類型。但是,在某些情況下,您可能想要在同一個容器中儲存多種類型的物件。

要解決此挑戰,請考慮使用 Boost.Any。 Boost.Any是一個可以表示任何資料類型的模板類別。您可以將 Boost.Any 的實例儲存在容器中,這樣您就可以在同一集合中保存不同類型的物件。

以下是如何使用 Boost.Any 的範例:

<code class="cpp">#include <boost/any.hpp>
#include <vector>

int main() {
  std::vector<boost::any> myContainer;

  int x = 5;
  std::string y = "Hello";
  double z = 3.14;

  // Add objects of different types to the container
  myContainer.push_back(boost::any(x));
  myContainer.push_back(boost::any(y));
  myContainer.push_back(boost::any(z));

  // Retrieve objects from the container and cast them to their original types
  int recoveredX = boost::any_cast<int>(myContainer[0]);
  std::string recoveredY = boost::any_cast<std::string>(myContainer[1]);
  double recoveredZ = boost::any_cast<double>(myContainer[2]);

  // Use the recovered objects
  std::cout << recoveredX << std::endl;
  std::cout << recoveredY << std::endl;
  std::cout << recoveredZ << std::endl;

  return 0;
}</code>

另一個選項是建立自訂UnionStruct。聯合允許您在同一記憶體位置儲存不同的資料類型,而結構可以保存多個不同類型的資料成員。但是,如果訪問了錯誤的成員,聯合可能會出現未定義的行為,而如果只主動使用一個成員,結構可能會效率低下。

最終,最佳方法取決於應用程式的特定要求和約束。考慮每個選項的優缺點,以確定最合適的解決方案。

以上是如何在單一 C 容器中儲存不同的資料類型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn