如何使用boost来连接地图的键和值,尤其是当值是结构时

时间:2017-03-23 20:07:24

标签: c++ c++11 boost stringstream boost-regex

在下面的代码目标中分别遍历地图并获取键和值,是否有一种方法可以在每个条目中单独执行 我需要加入键及其值(这是一个结构)

#include <boost/algorithm/string.hpp>
#include <boost/range/adaptors.hpp>
#include <vector>
#include <string>
#include <functional>
#include <iostream>
struct valueInfo
{
   std::string val1;
   std::string val2;
   std::string val3;
   valueInfo(const std::string A, const std::string B, const     std::string C):val1(A),val2(B),val3(C){}

};

typedef std::map<std::string,valueInfo*> AssetMap ;

void foo(const AssetMap& pList)
{

using namespace boost::adaptors;
for (const auto & key : pList | boost::adaptors::map_keys  ) {
    std::cout << key << " ";

}
for (const auto & key : pList | boost::adaptors::map_values) {
         std::cout << key->val1 << key->val2<< key->val3<< "\n";
}

}
int main()
{
AssetMap myMap;
std::string key = "11233";
valueInfo *myvalues = new valueInfo ("Tejas","Male","Employee");
//std::cout<<myvalues;
//myMap.insert(std::make_pair(key, myvalues));
myMap.insert(std::make_pair(key, myvalues));
myMap.insert(std::make_pair("111", myvalues));

myMap.insert(std::make_pair("222", myvalues));

myMap.insert(std::make_pair("333", myvalues));

myMap.insert(std::make_pair("444", myvalues));

foo(myMap);

}

当前输出

111 11233 222 333 444 TejasMaleEmployee
TejasMaleEmployee
TejasMaleEmployee
TejasMaleEmployee
TejasMaleEmployee

期望的输出

111{TejasMaleEmployee}
11233{TejasMaleEmployee}
222{TejasMaleEmployee}

提前致谢 特加斯

1 个答案:

答案 0 :(得分:0)

此代码为c ++ 14。根据要求提供c ++ 11版本。

无需升压适配器。将迭代器解引用到<const key, value>对的对象。

我还修复了内存泄漏。

#include <memory>
#include <vector>
#include <string>
#include <functional>
#include <iostream>
#include <map>

struct valueInfo
{
    std::string val1;
    std::string val2;
    std::string val3;

    valueInfo(const std::string A, const std::string B, const std::string C)
            : val1(A)
            , val2(B)
            , val3(C) {}

};

// reference wrapper in unequivocal - the map does not control the lifetime of the object
typedef std::map <std::string, std::reference_wrapper<valueInfo>> AssetMap;

void foo(const AssetMap& pList)
{
    for (auto&& entry : pList) {
        auto&& key = entry.first;
        auto&& value = entry.second.get();
        std::cout << key << " {" << value.val1 << " " << value.val2 << " " << value.val3 << " }\n" ;
    }
}

int main()
{
    AssetMap    myMap;
    std::string key       = "11233";
    auto   myvalues = std::make_unique<valueInfo>("Tejas", "Male", "Employee");
    myMap.emplace(key, *myvalues);
    myMap.emplace("111", *myvalues);
    myMap.emplace("222", *myvalues);
    myMap.emplace("333", *myvalues);
    myMap.emplace("444", *myvalues);


    foo(myMap);

}