gpt4 book ai didi

c++ - 无法在 C++ 中推送 vector 和列表中的项目?

转载 作者:行者123 更新时间:2023-11-30 03:07:28 24 4
gpt4 key购买 nike

这是一个基本的归并排序程序:

问题是当我尝试将项目插入“vector 合并”时,没有任何反应。 (请引用代码下方的gdb数据)

vector<long> merge(vector<long> &L, vector<long> &R){

int i = 0;
int j = 0;
vector<long> merged;

while((i < L.size())&&(j < R.size())){
if ((L[i] <= R[j])){
merged.push_back(L[i]);
i++;
}else{
merged.push_back(R[j]);
j++;
}

while(i < L.size())
{
merged.push_back(L[i]);
i++;
}

while(j < R.size())
{
merged.push_back(R[j]);
j++;
}
return merged;

}
}

//===================================GDB 数据======== ===========================

(gdb) n
52 int i = 0;
(gdb)
53 int j = 0;
(gdb)
54 vector<long> merged;
(gdb) print i
$2 = 0
(gdb) print merged
$3 = {<std::_Vector_base<long, std::allocator<long> >> = {
_M_impl = {<std::allocator<long>> = {<__gnu_cxx::new_allocator<long>> = {<No data fields>}, <No data fields>}, _M_start = 0x7fffffffdcd0,
_M_finish = 0x7fffffffdcf0, _M_end_of_storage = 0x7fffffffdde0}}, <No data fields>}
(gdb) print *(merged._M_impl._M_start)@merged.size()
$4 = {140737488346528, 4199556, 140737488346432, 140737488346656}

Problem I: Why the merged vector is not null? Or did I used wrong gdb command?? But same command works on other vectors in this program..


(gdb)
$5 = {140737488346528, 4199556, 140737488346432, 140737488346656}
(gdb) n
56 while((i < L.size())&&(j < R.size())){
(gdb) print *(merged._M_impl._M_start)@merged.size()
$6 = {140737488346528, 4199556, 140737488346432, 140737488346656}
(gdb) n
57 if ((L[i] <= R[j])){
(gdb) print L[i]
$7 = (long &) @0x6060b0: 31616136
(gdb) print R[i]
$8 = (long &) @0x6060d0: 1873051691
(gdb) n
58 merged.push_back(L[i]);
(gdb) print *(merged._M_impl._M_start)@6
$14 = {140737488346528, 4199556, 140737488346432, 140737488346656, 6316272, 6316280}
// Before any push_back operation, dump the content of merged.

(gdb) n
59 i++;

// Question 2, Push_back does not work...
(gdb) print *(merged._M_impl._M_start)@1
$17 = {140737488346528}
(gdb) print *(merged._M_impl._M_start)@2
$18 = {140737488346528, 4199556}
(gdb) print *(merged._M_impl._M_start)@8
$19 = {140737488346528, 4199556, 140737488346432, 140737488346656, 6316272, 6316280, 6316280, 4205125}

谁能帮帮我??

最佳答案

你的算法有一个错误,现在看起来第一个项目会被正确合并,但随后所有的 L 都会被推送,然后是所有的 R。

看来移动右大括号可以解决您的问题。

vector<long> merge(vector<long> &L, vector<long> &R){

int i = 0;
int j = 0;
vector<long> merged;

while((i < L.size())&&(j < R.size())){
if ((L[i] <= R[j])){
merged.push_back(L[i]);
i++;
}else{
merged.push_back(R[j]);
j++;
}
}

while(i < L.size())
{
merged.push_back(L[i]);
i++;
}

while(j < R.size())
{
merged.push_back(R[j]);
j++;
}
return merged;
}

关于c++ - 无法在 C++ 中推送 vector 和列表中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5808944/

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