使用值类在C 中实现STL MAP
Implementation of stl map in c++ using class of values
我必须开发stl映射,其中键是整数,其中与键关联的值是5个元组。仅具有整数数据类型。
e.g key=1
value=(2,3,4,5,6)
key=2
value=(1,2,3,4,5)
等等。我如何实现它以插入和搜索操作。
是指如何将单键值映射到5个值的元组。如何完成?
取决于您的数据含义,我会选择其他方法。如果您的值在逻辑上属于合并在一起,那就是它们仅在组合中有意义,那么我只需将它们存储在通用的数据结构中,然后将此数据结构存储在地图中。为此,课程,结构或容器可能适合您的需求。同样,这取决于您的上下文,什么是最佳选择。如果您的值孤立存在,并且它们之间的唯一连接是它们共享相同的密钥,那么我将使用std :: Multimap。
如果您可以访问C++11
,则可以使用std::tuple
(或Boost tuple),我相信这是您案例的最佳拟合数据结构。请参阅下面的摘要,看看是否适合:
#include<tuple>
#include<map>
#include<iostream>
#include<stdexcept>
typedef std::tuple<int, int, int, int, int > fiveIntTuple;
void insert(std::map<int, fiveIntTuple>& values,
int key, int a, int b, int c, int d, int e){
values[key] = std::make_tuple(a,b,c,d,e);
}
fiveIntTuple search(const std::map<int, fiveIntTuple >& values, int key ){
return values.at(key);
}
void print(const std::map<int, fiveIntTuple >& values, int key){
try{
fiveIntTuple t;
t = search(values, key);
std::cout << "For key == " << key << " got: "
<< std::get<0>(t) << ","
<< std::get<1>(t) << ","
<< std::get<2>(t) << ","
<< std::get<3>(t) << ","
<< std::get<4>(t) << std::endl;
}catch(const std::out_of_range&){
std::cerr << "For key " << key << " ... not found" << std::endl;
}
}
int main(){
std::map<int, fiveIntTuple > my_values;
insert(my_values, 1, 2,3,4,5,6);
insert(my_values, 2, 1,2,3,4,5);
print(my_values, 1);
print(my_values, 2);
print(my_values, 3);
return 0;
}
执行此片段,您必须得到:
For key == 1 got: 2,3,4,5,6
For key == 2 got: 1,2,3,4,5
For key 3 ... not found
相关文章:
- 为什么使用 NDK 不能存在不同的 stl 实现?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 默认赋值运算符如何在实际 STL 中实现
- hashtable :如何理解这种基于STL中List的hashtable实现
- 如何知道用于实现标准代码段的确切数据结构和算法,例如在C++STL中?
- 使用 Boost HOF 实现 STL 漂亮打印
- 如何在C++中重新实现包含指针的 STL 容器的类的迭代器
- 在C++中实现无STL和无类的最小堆
- 我可以期望某些 STL 函数实现是可自动矢量化的吗?
- 使用 C++ STL 的数组实现
- 我应该如何在恒定长度的 STL 样式数据结构中实现max_size?
- C STL中如何实现Deque
- 错误试图实现STL迭代器
- 关于 c++ stl 谓词的实现
- 为什么不是条件 *First1 == * First2 ??(C++ STL 包括函数实现)
- 使用值类在C 中实现STL MAP
- 如何实现STL容器中对象的快速释放
- 应该如何为自定义类实现STL功能
- 如何实现 STL 风格的迭代器并避免常见的陷阱
- 说出一个实现STL兼容序列容器的好指南)