Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-26 08:55:29
Original
194 people have browsed it

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

How to Store Disparate Data Types in a Single C Container

In C , containers such as vectors and maps typically hold objects of a single data type. However, there are scenarios where you may want to store objects of multiple types in the same container.

To address this challenge, consider using Boost.Any. Boost.Any is a template class that can represent any data type. You can store instances of Boost.Any in a container, which allows you to hold objects of different types within the same collection.

Here's an example of how you can use 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>
Copy after login

Another option is to create a custom Union or Struct. A union allows you to store different data types in the same memory location, while a struct can hold multiple data members of different types. However, unions can have undefined behavior if the wrong member is accessed, and structs can be inefficient if only one member is actively used.

Ultimately, the best approach depends on the specific requirements and constraints of your application. Consider the pros and cons of each option to determine the most appropriate solution.

The above is the detailed content of How can I store different data types in a single C container?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!