Why is this so much slower in C++?

后端 未结 9 2054
盖世英雄少女心
盖世英雄少女心 2020-12-31 11:49

I have converted this simple method from C# to C++. It reads a path table and populates a list of lists of ints (or a vector of vectors of ints).

A sample line from

9条回答
  •  天涯浪人
    2020-12-31 12:29

    The whileloop in your code seems to be very messy and long, as it is doing things in a way which is not needed:

    A simple and fast equivalent code would be this:

    int result;
    stringstream ss(line);
    while ( ss >> result ) //reads all ints untill it encounters non-int
    {
        pathLookupVectors[i][j].push_back(result);
    }
    

    In C++, such loop is idiomatic as well. Or instead of this manual loop, you could write use std::copy 1:

    std::copy(std::istream_iterator( ss ), 
              std::istream_iterator(), 
              std::back_inserter(pathLookupVectors[i][j]));
    

    1. It is taken from @David's comment.

    Or even better if you do this, when you push_back the vector itself:

     if (getline(myFile, line)) //enter if a line is read successfully
     {
       stringstream ss(line);
       std::istream_iterator begin(ss), end;
       pathLookupVectors[i].push_back(vector(begin, end));
     }
    

    Done!

提交回复
热议问题