gpt4 book ai didi

c++ - 你能在 C++ 中嵌入 for 循环吗?

转载 作者:太空狗 更新时间:2023-10-29 23:38:29 24 4
gpt4 key购买 nike

我正在研究合并排序函数。我得到了排序 - 我正在尝试完成我的合并部分。假设我正在学习 C++,对指针有粗略的了解,并且不理解 std::vector::iterator(或 std::vector,就此而言)的所有规则。

假设 num 是从大小为“int ar[num]”的数组复制 (std::copy) 值的原始 std::vector 的大小。假设 farray 的值为 (0 to (num/2)),sarray 的值为 ((num/2) to 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);
}
}

这段代码可以编译,我最新的 Bloodshed Dev-C++ 稳定版本不会抛出任何警告或错误。我不知道这是否有效,我仍然需要尝试计算 final 的所有值。我只想知道这是常见的、容易出错的还是糟糕的风格。而且,如果是这样,您将如何

最佳答案

它是有效的...但是 for 循环可能不是您想要的。当您使用两个 for 循环时,每次外循环循环时,您的内循环都会回到开始。因此,如果您的 vector 包含:

farray: 10 9 8 4 3
sarray: 7 6 4 3 1

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

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

因为您正在测试每一个组合,并将较大的组合添加到最终列表中。更好的解决方案可能是为每个列表记住一个迭代器,并且只使用一个循环。与其遍历一个列表,不如一起遍历它们——如果 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++;
}
}

我还没有测试过 - 如果这是作业,那么尝试理解我所做的,然后自己写,而不是复制+粘贴。 p>

关于c++ - 你能在 C++ 中嵌入 for 循环吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/766605/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com