【问题标题】:C++ position in index removal of hard coded list of numbersC++ 在硬编码数字列表的索引删除中的位置
【发布时间】:2018-02-27 09:25:31
【问题描述】:

我有一个非常简单的问题。我对这个简短程序的目标是让它显示一组数字(这是硬编码的),然后让用户指定应该从哪个索引中删除数组的数字。然后它输出新数组。该程序有效,但有一个重大错误。例如,当我运行它并选择位置 2 时,它应该删除 45,而不是删除 34。程序输出:

12 45 2 8 10 16 180 182 22

而不是: 12 34 2 8 10 16 180 182 22

请注意,如果您还记得列表从 0 开始,我想要删除的数字位置改为在我实际想要删除的数字之前的位置删除。谢谢!

//This program demos basic arrays

#include <iostream>
using namespace std;

const int CAP = 10;

int main()
{
    //read index from user, delete number in position of index they specify. 
    //when printing the list, number should be gone. 
    int size;
    int list[CAP] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
    size = 10;
    int i, delIndex;

    cout << "Your list is: " << endl;
    for (i = 0; i < CAP; i++)
    {
        cout << list[i] << endl;
    }

    cout << "\nPlease enter index to delete from: ";
    cin >> delIndex;

    for (i = delIndex; i <= 10; i++)
    {
        list[i - 1] = list[i];

    }
    cout << "The index position you specified has been deleted." << endl;
    cout << "The new array is: " << endl;
    for (i = 0; i < (size - 1); i++)
    {
        cout << list[i] << endl;
    }
    return 0;
}

【问题讨论】:

  • 您的代码将所有元素从您输入的索引复制到其左侧的元素。索引 0 为 12,索引 1:34,索引 2:45。您的复制操作将索引 2 复制到位置 2-1(复制 45 到 34)。
  • 尝试 list[i] = list[i+1] with i
  • 你知道我会怎么解决这个问题吗?多年来,我一直在搞乱第二个 for 语句,但由于我是 c++ 新手,所以我无法弄清楚...
  • 迈克尔你刚刚告诉我的修复了它!非常感谢。

标签: c++ list indexing


【解决方案1】:

替换这个:

for (i = delIndex; i <= 10; i++)
{
    list[i - 1] = list[i];
}

这样:

for (i = delIndex; i < size-1; i++)
{
    list[i] = list[i+1];
}

【讨论】:

  • 我认为您应该指出您已经修复了 两个 错误。首先是明显的 i-1i 的事情。其次,原始访问了i[10],但您的代码没有。作为一个 nit,OP 代码有一个变量 CAP 而不是 size
  • 感谢您的评论,我认为这很明显,但我所做的小改动使用户可以多次删除数字,您只需添加 --size;
【解决方案2】:

既然你用的是 C++,为什么不直接使用标准向量呢?

#include <vector>

// Initialize
int vv[10] = { 12, 34, 45, 2, 8, 10, 16, 180, 182, 22 };
std::vector<int> myvector(&vv[0], &vv[0]+10);

根据编译器的不同,还有其他更简单的方法来初始化向量。见how to initialize a vector

那么你就可以直接使用vector的erase方法了(这里我假设用户知道索引是从0开始的,否则你可以直接放delIndex-1):

myvector.erase (myvector.begin()+delIndex);

您可以轻松地遍历向量以显示其内容(根据编译器,有更简单的方法,use the auto keyword)。

for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
    std::cout << ' ' << *it;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2010-10-27
    • 1970-01-01
    • 2012-04-14
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-01-14
    相关资源
    最近更新 更多