【问题标题】:inserting numbers to an array using pointer notation c++使用指针符号c ++将数字插入数组
【发布时间】:2015-01-06 19:56:39
【问题描述】:

所以我试图将一个数字按升序插入数组,然后仅使用指针表示法打印数组。我尝试通过找到将插入数字的位置来做到这一点,然后我尝试将所有值存储在该位置以及在数组下方的位置之后。然后我想在正确的位置插入数字,然后将所有数字移回它们的位置+ 1。但是我认为我的指针符号中缺少一些东西,因为我的检查都没有出现,所以我的 for 循环甚至没有正在使用。任何帮助或建议将不胜感激。

using namespace std;
int main(int argc, char *argv[]) 
{
    int spot; // spot holder for the added number 
    int *pointer = NULL; 

    cout << "How many numbers do you want in your array" << endl; 
    int input; 
    cin >> input; 
    pointer = new int[input * 2 ];
    for (int index = 0; index < input; index ++)
    {
        cout << "Enter integer number" << index + 1 << endl; 
        cin >> *(pointer + index); 

    }
    for (int index = 0; index < input; index ++)
    {
        cout <<  *(pointer + index); 
    }
    cout << endl; 

    cout << "What number would you like to add?" << endl;
    int added; 
    cin >> added;  

    for (int index = 0; added < *(pointer + index); index++)
    {
        spot = index;  
        cout << "check .5: " << spot;
    }
    for (int index = spot; index < input + 1; index++)
    {
        *(pointer + input + index) = *(pointer + index); //& added 
        cout << "check 1: " << *(pointer + input + index); 
    }
    *(pointer + spot) = added; 
    for (int index = spot + 1; index < input + 1; index++)
    {
        *(pointer + index) = *(pointer + index + input); 
        cout << "check 2" ;
    }

    for (int index = 0; index < input + 1; index ++)
    {
        cout <<  *(pointer + index); 
    }
    cout << endl; 
}

【问题讨论】:

  • 你有 MCVE,stackoverflow.com/help/mcve 吗?
  • 好。 Ty 为代码。下一步:)) 1. 删除与您的问题无关的代码,只留下重现您的问题所需的最少代码。 2. 格式化/缩进你的代码。未格式化的代码真的很难遵循。
  • 为什么你分配的号码是用户指定的两倍?
  • 当表达式中有(pointer + input) 时,对于单个大小(不是两倍大小)的数组,结果已经超出范围(除非您减去某些内容)。
  • fyi,pointer[index]*(pointer + index) 一样多是“指针表示法”。事实上,一个被定义为另一个的同义词。

标签: c++ arrays pointers notation


【解决方案1】:

这是一个演示程序,展示了如何通过标准算法进行分配

#include <iostream>
#include <algorithm>

int main() 
{
    const size_t N = 5;
    int a[N] = { 2, 5, 1, 4, 3 };
    int b[N];

    int *first = b;
    int *last  = b;

    for ( int x : a )
    {
        auto p = std::upper_bound( first, last, x );

        if ( p != last )
        {
            std::copy_backward( p, last, last + 1 );
        }

        *p = x;
        ++last;
    }

    for ( int x : b ) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}

输出是

1 2 3 4 5 

方法是您需要按升序填充数组放置数字。在这种情况下,您应该使用二进制搜索方法来确定必须添加下一个数字的位置。然后你只需要从这个位置开始向右移动所有存在的元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多