为什么这个简单的批处理方法不能按预期工作?

时间:2015-02-16 22:01:01

标签: c++

我试图在c++中编写一个简单的批处理方法,这是我的方法:

vector<vector<string>> batch(vector<string> source, int count)
{
    vector<string> temp;
    vector<vector<string>> result;
    int counter = 0;
    for (auto x : source) {
        if (counter == count) {
            result.push_back(temp);
            temp.clear();
            counter = 0;
        }
        else {
            temp.push_back(x);
            counter++;
        }
    }

    if (temp.size() > 0)
        result.push_back(temp);

    return result;
}

所以给定此输入并且count = 3:

a,a,a,b,b,b,c,c,c

它应该返回:

a,a,a
b,b,b
c,c,c

但我得到了:

a,a,a
b,b,c
c

我认为该问题与temp.clear()有关,我尝试将temp的元素复制到另一个vector并将其添加到result,但它没有改变一切。那么,我的错误在哪里?

这是测试代码:

vector<string> v = { "a","a","a","b","b","b","c","c","c" };

auto result = batch(v, 3);

for (auto x : result) {
    for (auto y : x){
        cout << y << " ";
    }
    cout << endl;
}

3 个答案:

答案 0 :(得分:3)

你需要在for循环中将每次迭代推送到temp。

if (counter == count) {
    result.push_back(temp);
    temp.clear();
    counter = 0;
}
temp.push_back(x);
counter++;

答案 1 :(得分:2)

vector<vector<string>> batch(vector<string> source, int count)
{
    vector<string> temp;
    vector<vector<string>> result;
    int counter = 0;
    for (auto x : source) {
        temp.push_back(x);
        counter++;
        if (counter == count) {
            result.push_back(temp);
            temp.clear();
            counter = 0;
        }
    }
    if (temp.size() > 0)
        result.push_back(temp);
    return result;
}

答案 2 :(得分:1)

您可以考虑另一种选择:

typedef vector< string > svec;
typedef vector< svec >   vecsvec;
vecsvec batch( svec source, int count )
{
    vecsvec ret;
    while( source.size() > 0 )
    {
        ret.push_back( svec( source.begin(), source.begin() + count ) );
        source.erase( source.begin(), source.begin() + (count > source.size() ? source.size() : count) );
    }
    return ret;
}