【问题标题】:c++ Insert in array algorithm malfunctioningc ++插入数组算法故障
【发布时间】:2016-02-03 19:57:20
【问题描述】:
#include <iostream>
using namespace std;

/* This code is not working as it does not insert the value of item in the
array instead the value of item is zero. But i have troubleshooted this
problem and figured out that the code works fine if i define "int item" as
constant variable or use int i as global variable instead of defining in the
for loop. so my question is what is the reason behind this malfunctioning or
is there any programming secret i haven't aware of yet*/

int main()
{
    int LA[] = {1, 3, 64, 98, 54};
    int k = 3;

    int n = 5;
    int item = 46;
    int j = n;

    for(int i = 0; i < n; i++)
    {   
        cout << "LA[" << i << "] = " << LA[i] << endl;
    }

    n++;

    for( ; j >= k; j-- )
    {
        LA[j+1] = LA[j];
    }

    LA[k] = item;
    cout << endl << "After insertion" << endl << endl;

    for(int i = 0; i < n; i++)
    {
        cout << "LA[" << i << "] = " << LA[i] << endl;
    }

    return 0;
}

【问题讨论】:

  • int LA[] 自初始化以来具有固定大小。查找std::vector。请注意,j = 5LA[j] 已经超出范围。
  • 请自己调试丑陋的代码(或有const int n = 5;
  • 还有一个更可能的重复“你能在初始化后调整 C++ 数组的大小吗?” stackoverflow.com/questions/756906/…。简短的回答:你不能。如果您需要可调整大小的数组,请使用 std::vector。

标签: c++ arrays insert


【解决方案1】:

LA 具有固定大小。它是一个静态数组,您无法更改cc++ 中的大小。目前j 将为5,您将尝试访问数组和未定义行为 边界之外的LA[5]

您有 3 个选项:

  1. 在静态数组中保留足够的空间以容纳所需的一切:LA[10] = {...
  2. 使用动态内存并调整大小:int *LA = new int[10];(查找此方法)
  3. 最好的,使用std::vector&lt;int&gt;

【讨论】:

    【解决方案2】:

    如果您想将项目作为数组的第 k 个元素插入,您应该知道 LA 数组没有第 6 个索引 (LA[6])。所以在第二个循环之前,用n-1初始化j。 此外,如果您想拥有所有值,您应该使用std::vector,它可以动态添加值和索引。 有关向量的进一步研究,请参阅此链接:Here

    【讨论】:

      猜你喜欢
      • 2015-12-11
      • 1970-01-01
      • 2019-05-03
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多