Certainly! Below is a C++ class named DataTable that encapsulates the members you specified:
std::map<std::string, std::vector<float>> data_;
std::map<int, std::string> idx_to_columns;
std::map<std::string, int> columns_to_idx;
The class provides basic methods to add columns, add data, and retrieve data.
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <stdexcept>
class DataTable {
public:
// Add a new column
void add_column(const std::string& column_name) {
if (columns_to_idx.count(column_name)) {
throw std::runtime_error("Column already exists.");
}
int idx = columns_to_idx.size();
columns_to_idx[column_name] = idx;
idx_to_columns[idx] = column_name;
data_[column_name] = std::vector<float>();
}
// Add a value to a column
void add_value(const std::string& column_name, float value) {
if (!columns_to_idx.count(column_name)) {
throw std::runtime_error("Column does not exist.");
}
data_[column_name].push_back(value);
}
// Get a value at a specific row and column
float get_value(const std::string& column_name, size_t row) const {
auto it = data_.find(column_name);
if (it == data_.end()) {
throw std::runtime_error("Column does not exist.");
}
if (row >= it->second.size()) {
throw std::out_of_range("Row index out of range.");
}
return it->second[row];
}
// Get number of rows (assumes all columns have the same number of rows)
size_t num_rows() const {
if (data_.empty()) return 0;
return data_.begin()->second.size();
}
// Get number of columns
size_t num_columns() const {
return columns_to_idx.size();
}
// Print the table
void print() const {
// Print header
for (const auto& [idx, col] : idx_to_columns) {
std::cout << col << "\t";
}
std::cout << "\n";
// Print rows
size_t rows = num_rows();
for (size_t i = 0; i < rows; ++i) {
for (const auto& [idx, col] : idx_to_columns) {
std::cout << data_.at(col)[i] << "\t";
}
std::cout << "\n";
}
}
private:
std::map<std::string, std::vector<float>> data_;
std::map<int, std::string> idx_to_columns;
std::map<std::string, int> columns_to_idx;
};
// Example usage
int main() {
DataTable table;
table.add_column("A");
table.add_column("B");
table.add_value("A", 1.0f);
table.add_value("A", 2.0f);
table.add_value("B", 3.0f);
table.add_value("B", 4.0f);
table.print();
std::cout << "Value at (A, 1): " << table.get_value("A", 1) << std::endl;
return 0;
}
Notes:
- The class assumes all columns have the same number of rows for simplicity.
- Error handling is included for common issues.
- You can expand this class with more features as needed.