数组显示未知行为 [英] array showing unknown behaviour

查看:79
本文介绍了数组显示未知行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
    int arr[10];
    arr[0] = 1;
    arr[1] = 2;
    // sorting array
    sort(arr,arr+10);

    // printing array
    for(int i=0;i<10;i++)
    {
        cout<<arr[i]<<endl;
    }
    return 0;
}









输出如下:

-1212121212121

-1212121212121

-1212121212121

-1212121212121

-1212121212121

-1212121212121

-1212121212121

1

2









我想要的是什么:



1

2









怎么能我这样做





the output is like this:
-1212121212121
-1212121212121
-1212121212121
-1212121212121
-1212121212121
-1212121212121
-1212121212121
1
2




what i want:

1
2




how can i do this

推荐答案

对数组进行排序将永远不会返回1,2。它有10个成员。其他成员有什么价值观?使用你的调试器来查找。



数组只有两个成员初始化,你对整个数组进行排序。该数组的其他值是未知的。他们需要被设置为某种东西。



Sorting the array will NEVER return 1,2. It has 10 members. What values do the other members hold? Use your debugger to find out.

The array only has only two members initiallised and you sort the whole array. The other values of the array are unknown. They need to be set to something.

int arr[10] = {0,0,0,0,0,0,0,0,0,0};

arr[0] = 1;
arr[1] = 2;





您可以选择仅对前两个(或初始化成员)进行排序 - 您必须只显示该数组的子部分而不是整个10个成员。然后将给出1,2.





1.是的,你必须将所有值设置为已知值 - 你可以使用一个for循环或memset()。



2.你可以按照我说的排序数组的一个子集 - 你必须只显示那些排序的值而不是整个数组。



You may choose to sort only the first 2 (or initialised members) - you must then only display that subsection of the array not the whole 10 members. That will then give 1,2.


1. Yes you must set all values to known values - you can use a for loop or memset().

2. You can as I said sort a subset of your array - you must then only display those sorted values not the whole array.


要将所有项目设置为默认的已知值,只需从
To set all items to a default known value, just change from
引用:

int arr [ 10];

int arr[10];



to

int arr[10] = {0}; // init ALL the array items with value 0





注意 C ++ 11 标准提供统一初始值设定项,数组容器和范围 for loop:



Note the C++11 standard provides uniform initializers, the array container and ranged for loop:

#include<iostream>
#include <array>
#include<algorithm>

using namespace std;

int main()
{
    array <int,10> arr{0}; // this initializes all the items with 0
    arr[0] = 1;
    arr[1] = 2;
    // sorting array
    sort(arr.begin(),arr.end());

    for ( auto  x : arr)
    {
      cout << x << endl;
    }
}


这篇关于数组显示未知行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆