samedi 28 janvier 2017

Range For Loop over an Element of a Map

Consider the example below. config_parser is an object of a class whose method variable_map() returns an object of the type std::map<std::string, std::vector<std::string>>. The first loop gives incorrect or garbage result while the second loop give correct result. What am I missing?

Compilers tested with: GCC 6.3.1, clang 3.9.1, (c++14)

 std::vector<std::string> rules = config_parser.variable_map()["CellQRule"];

 for (const auto rule : config_parser.variable_map()["CellQRule"]) {
   std::cout << rule << std::endl;
 }
 for (const auto rule : rules) {
   std::cout << rule << std::endl;
 }

The following code also gives correct result for both the loops.

 auto map = config_parser.variable_map();
 auto q_rules = map["CellQRule"];

 for (const auto rule : map["CellQRule"]) {
    std::cout << rule << std::endl;
 }
 for (const auto rule : q_rules) {
   std::cout << rule << std::endl;
 }

Aucun commentaire:

Enregistrer un commentaire