简体   繁体   中英

Split a vector in a loop so that the size of the next vector decreases by 1, C++

I have a vector a{1,2,3,4,5,6,7,8,9,10} I need to split it into vectors of different lengths. I can set the maximum length of a vector The next division of the vector should decrease the size of the vector by 1

I'll try to explain it better:

Input: std::vector a{1,2,3,4,5,6,7,8,9,10}, int size = 4

Output: std::vector<std::vector > b{{1,2,3,4}, {5,6,7}, {8,9}, {10}}

I know how to divide a vector into equal parts.

std::vector<std::vector<double>> SplitVector(const std::vector<double >& vec, size_t n)
        {
            std::vector<std::vector<double>> outVec;

            size_t length = vec.size() / n;
            size_t remain = vec.size() % n;

            size_t begin = 0;
            size_t end = 0;

            for (size_t i = 0; i < std::min(n, vec.size()); ++i)
            {
                end += (remain > 0) ? (length + !!(remain--)) : length;
                outVec.push_back(std::vector<double>(vec.begin() + begin, vec.begin() + end));
                begin = end;
            }

            return outVec;
        }

But I need to divide the vector so that the size of the next vector is less by 1.

This solution will do what you asked and I believe it is less confusing than what you had:

  • input: std::vector<double> a = {1,2,3,4,5,6,7,8,9,10} , n = 4
std::vector<std::vector<double>> SplitVector(const std::vector<double>& vec, size_t n)
{
    std::vector<std::vector<double>> outVec;
    size_t begin, end;

    for (begin = 0; n > 0; n--) {
        end = std::min(vec.size() - begin, n);

        outVec.push_back(std::vector<double>(vec.begin() + begin, vec.begin() + begin + end));
        
        begin += end;
    }

    return outVec;
}
  • output: std::vector<std::vector<double>> v = {{1,2,3,4},{5,6,7},{8,9},{10}}

Keep in mind, however, that you didn't specify the case where the division of the vector isn't perfect (vector a has more values), so this solution will ignore any values that come after the case where n == 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM