C++ string parsing (python style)

后端 未结 10 1162
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 07:52

I love how in python I can do something like:

points = []
for line in open(\"data.txt\"):
    a,b,c = map(float, line.split(\',\'))
    points += [(a,b,c)]
<         


        
10条回答
  •  萌比男神i
    2020-12-08 08:24

    Fun with Boost.Tuples:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
        using namespace boost::tuples;
        typedef boost::tuple PointT;
    
        std::ifstream f("input.txt");
        f >> set_open(' ') >> set_close(' ') >> set_delimiter(',');
    
        std::vector v;
    
        std::copy(std::istream_iterator(f), std::istream_iterator(),
                 std::back_inserter(v)
        );
    
        std::copy(v.begin(), v.end(), 
                  std::ostream_iterator(std::cout)
        );
        return 0;
    }
    

    Note that this is not strictly equivalent to the Python code in your question because the tuples don't have to be on separate lines. For example, this:

    1,2,3 4,5,6
    

    will give the same output than:

    1,2,3
    4,5,6
    

    It's up to you to decide if that's a bug or a feature :)

提交回复
热议问题