你可以在C++中嵌入循环(在彼此中)

jke*_*eys 2 c++ pointers iterator loops vector

我正在进行合并排序功能.我得到了排序 - 我试图让我的合并部分完成.假设我正在学习C++,对指针有粗略的了解,并且不了解std :: vector :: iterator的所有规则(或std :: vector's).

假设num是从大小为"int ar [num]"的数组中复制(std :: copy)值的原始std :: vector的大小.假设farray的值为(0到(num/2)),sarray的值为((num/2)到num).

int num = original.size();
std::vector<int> final(num);

for (std::vector<int>::iterator it = farray.begin(); it != farray.end(); ++it) {
     for (std::vector<int>::iterator iter = sarray.begin(); iter != sarray.end(); ++iter) {
         if (*it > *iter) final.push_back(*it);
          else
               final.push_back(*iter);
     }
}
Run Code Online (Sandbox Code Playgroud)

这段代码编译,我的最新稳定版本的Bloodshed Dev-C++不会抛出任何警告或错误.我不知道这是否有效,我仍然需要尝试cout所有的final值.我只是想知道这是否常见,容易出错,还是只是风格不好.如果是这样,你会如何

Sma*_*ery 7

这是有效的......但for循环可能不是你想要的.当你使用两个for循环时,每次外循环循环时,你的内循环会一直回到起始位置.所以如果你的载体包含:

farray: 10 9 8 4 3
sarray: 7 6 4 3 1
Run Code Online (Sandbox Code Playgroud)

然后你的最终数组将包含如下内容:

10 10 10 10 10 9 9 9 9 9 8 8 8 8 8 7 6 4 4 4 7 6 4 3 3
Run Code Online (Sandbox Code Playgroud)

因为您正在测试每个组合,并将较大的组合添加到最终列表中.更好的解决方案可能是记住每个列表的迭代器,只需使用一个循环.不要循环遍历列表,只需将它们放在一起 - 如果sarray有更大的数字,然后递增你的sarray迭代器,并将其与旧的farray迭代器进行比较.当sarray和farray都是空的时候停止你的循环.

vector<int> fiter = farray.begin();
vector<int> siter = sarray.begin();
vector<int> final;

// Let's traverse both farray and sarray.
// We'll want to stop this loop once we've traversed both lists.
while (fiter != farray.end() && siter != sarray.end())
{
    if (fiter == farray.end())
    {
        // we must have gone right through farray - 
        // so use the value from sarray, and go to the next one
        final.push_back(*siter);
        siter++;
    }
    else if (siter == sarray.end())
    {
        // we must have gone right through sarray - 
        // so use the value from farray, and go to the next one
        final.push_back(*fiter);
        fiter++;
    }
    else if (*siter > *fiter)
    {
        // siter is the bigger of the two - add it to the final list, and
        // go to the next sarray entry
        final.push_back(*siter);
        siter++;
    }
    else // *fiter >= *siter
    {
        // fiter is the bigger of the two - add it to the final list, and
        // go to the next farray entry
        final.push_back(*fiter);
        fiter++;
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有测试过 - 如果这是作业,那么尝试理解我做了什么,自己去写,而不是复制+粘贴.