0

有谁知道任何库或示例将读取/写入 csv 并根据传递的地图(可能嵌套)来推断类型并填充地图。

这可能会涉及一些递归模板代码。

map<int, map< double, map< string, double > > > 期望格式为 123,93.003,BLAH,42.24 的 csv

map<Date, map< string, vector< double > > > // arbitary length vector 1/1/2013,BLAH,0.1,0.2,0.3,0.4.....0.99

谢谢。

4

1 回答 1

0

这是我想出的

#include <iostream>
#include <algorithm>
#include <iterator>
#include <tuple>
#include <typeinfo>

using std::tuple;
using std::get;

template< class... Args >
struct parser;

// Specialization for std::tuple
template< class... Args >
struct parser<tuple<Args...>> {
   typedef tuple<Args...> tuple_type;

   static tuple_type parse( std::istream& is ) {
      tuple<Args...> result;
      _parse<0, tuple_type>::parse(is, result);
      return result;
   }

private:
   template< size_t N, class T >
   struct _parse;

   template< size_t N, class A0, class... An >
   struct _parse<N, tuple<A0, An...>> {
      static void parse( std::istream& is, tuple_type& t ) {

         std::cout << "Enter " << typeid(A0).name() << ": ";
         if (!( is >> get<N>(t) ))
         { std::cout << "Bad input!\n"; is.clear(); }
         is.get();

         // Recurse on the rest of the list
         _parse<N+1, tuple<An...>>::parse(is, t);
      }
   };

   // Termination
   template< size_t N >
   struct _parse<N, tuple<>> {
      static void parse( std::istream& is, tuple_type& t ) {
         /* */
      }
   };
};

int main() {
   typedef tuple<int, double, char> tuple_type;
   tuple_type t = parser<tuple_type>::parse( std::cin );

   std::cout << get<0>(t) << ", " << get<1>(t) << ", " << get<2>(t) << std::endl;
}

输出

$ ./a.out
Enter i: 0
Enter d: 0.0
Enter c: w
0, 0, w


$ ./a.out
Enter i: 0
Enter d: 0.0
Enter c: w
0, 0, w
于 2013-06-04T23:54:14.087 回答