c++中 map<string,string>如何 按插入顺序输出
时间: 2024-02-12 08:32:31 浏览: 30
在 C++11 之前,STL 中的 map 并没有提供按照插入顺序输出的功能。不过,可以使用 boost 库中的 boost::multi_index_container 来实现这个功能。
boost::multi_index_container 是一个可以通过多个索引对容器进行排序和查找的容器。
下面是一个使用 boost::multi_index_container 来实现按照插入顺序输出的例子:
```c++
#include <iostream>
#include <string>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
using namespace boost::multi_index;
struct data
{
std::string key;
std::string value;
};
typedef multi_index_container<
data,
indexed_by<
sequenced<>,
hashed_unique<
member<data, std::string, &data::key>
>
>
> map_type;
int main()
{
map_type map;
map.emplace_back(data{"key1", "value1"});
map.emplace_back(data{"key2", "value2"});
map.emplace_back(data{"key3", "value3"});
for (auto& item : map.get<0>())
{
std::cout << item.key << ": " << item.value << std::endl;
}
return 0;
}
```
输出:
```
key1: value1
key2: value2
key3: value3
```
这里使用了两个索引:sequenced 和 hashed_unique。sequenced 索引按照插入顺序排序,而 hashed_unique 索引用于快速查找 key。
在遍历时,使用 get<0>() 获取 sequenced 索引,即按照插入顺序遍历。