const std::map<boost::tuples::tuple, std::string>?

8
// BOOST Includes
#include <boost/assign.hpp>             // Boost::Assign
#include <boost/assign/list_of.hpp>     // Boost::Assign::List_Of
#include <boost/assign/std/map.hpp>     // Boost::Assign::Map_List_Of
#include <boost/tuple/tuple.hpp>        // Boost::Tuples
// STD Includes
#include <map>
#include <vector>
#include <string>
// Using namespaces
using namespace std;
using namespace boost;
using namespace boost::assign;
// Consts
    const map<string, string> query_map = map_list_of<string, string>
    ("4556_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 4556")
    ("7552_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 7552")
    ("234x_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 2344 OR PMU_ID = 2345 OR PMU_ID = 2346 OR PMU_ID = 2347 OR PMU_ID = 2348")
    ("813x_SELECT_FILENAME", "SELECT FILENAME FROM Files WHERE PMU_ID = 8132 OR PMU_ID = 8133 OR PMU_ID = 8134 OR PMU_ID = 8135 OR PMU_ID = 8136");
    const map<string, std::vector<int>> vector_map = map_list_of<string, std::vector<int>>
    ("4556", list_of(4556))
    ("7552", list_of(7552))
    ("234x", list_of(2344)(2345)(2346)(2347)(2348))
    ("813x", list_of(8132)(8133)(8134)(8135)(8136));

使用boost,可以初始化const std::containers以进行测试等。像上面的代码所示,创建const std::map或std::map非常容易。创建一个const map>稍微复杂一些,但仍然相当容易。
我正在尝试设计一个const std::map,string>,但我无法初始化它。有其他人成功吗?
// Typedefs
typedef boost::tuples::tuple<string, string, string> x3_string_tuple;
// Constants
const map<x3_string_tuple, string> query_selector_map = map_list_of<x3_string_tuple, string>
("4556", "SELECT", "FILENAME"), "4556_SELECT_FILENAME"); // ETC.

请始终包含编译错误产生的错误消息(如果有)。 - Johannes Schaub - litb
2个回答

22

我尝试了这个方法,但失败了,因为映射表的键需要可比较(使用std::less),因此需要定义operator<boost::tuple的比较运算符在头文件boost/tuple/tuple_comparison.hpp中定义。

包含该头文件后,这段代码可以正常工作:

#include <boost/assign/list_of.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
#include <map>
#include <string>

using std::string;
typedef boost::tuple<string, string, string> tpl_t;

int main() {
    using boost::assign::map_list_of;
    std::map<tpl_t, string> const m = 
        map_list_of(tpl_t("a","b","c"), "c")(tpl_t("x","y","c"), "z");
}

0

我会尝试

const map<x3_string_tuple, string> query_selector_map = map_list_of<x3_string_tuple, string>
(x3_string_tuple("4556", "SELECT", "FILENAME"), "4556_SELECT_FILENAME");

但是,说实话,也许更容易的方法是将字符串分成三个单独的列表,然后逐一将它们组合成一个元组,并将其添加到映射中。

那是我的最初想法,但结果导致了大量的编译错误。继续前进 - 看看会发生什么。 - Maciek
我曾考虑过使用3个列表变量,但我没能看出如何使用boost:assign一次性初始化它们,以便它们可以一起工作 :/ - Maciek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接