Best way to split a vector into two smaller arrays?

前端 未结 4 1775
一个人的身影
一个人的身影 2021-02-01 16:01

What I\'m trying to do:

I am trying to split a vector into two separate arrays. The current int vector contains an element per line in a text file. Th

4条回答
  •  青春惊慌失措
    2021-02-01 16:34

    Solution to split vector to variable count parts using iterator.

    #include 
    #include 
    
    int main()
    {
       // Original vector of data
       std::vector mainVec{1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9, 9.0};
       // Result vectors
       std::vector> subVecs{};
       // Start iterator
       auto itr = mainVec.begin();
       // Variable to control size of non divided elements
       unsigned fullSize = mainVec.size();
       // To regulate count of parts
       unsigned partsCount = 4U;
       for(unsigned i = 0; i < partsCount; ++i)
       {
           // Variable controls the size of a part
           auto partSize = fullSize / (partsCount - i);
           fullSize -= partSize;
           // 
           subVecs.emplace_back(std::vector{itr, itr+partSize});
           itr += partSize;
       }
       // Print out result
       for (const auto& elemOuter : subVecs)
       {
           std::cout << std::fixed;
           for (const auto& elemInner : elemOuter)
           {
               std::cout << elemInner << " ";
           }
           std::cout << "\n";
       }
    }
    

提交回复
热议问题