数组操作...变得更简单了吗? [英] Array Manipulation ... made simpler?

查看:84
本文介绍了数组操作...变得更简单了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,

快速提问,随时向我指出课程或常见问题解答.有更快或更有效的方法来执行以下操作吗?只需将值沿数组向下滑动即可:

Hey,

Quick question, and feel free to just point me at a class or FAQ. Is there a faster or more efficient way to do the following? Just slide values down an array:

int a[5] = {1, 2, 5, 2, 1};

a[4] = a[3];
a[3] = a[2];
a[2] = a[1];
a[1] = a[0];

a[0] = //Some input



我只是在寻找一种将所有值向下滑动1位的方法.预先感谢您回答我的琐碎问题.



I''m just looking for a way to slide all the values down by 1 place. Thanks in advance for answering my trivial question.

推荐答案

使用集合而不是数组.如果不能这样做,请分配一个大一个元素的新数组,然后将另一个数组移到新数组中,该数组从新数组中的元素1开始.
Use a collection instead of an array. If you can''t do that, allocate a new array that''s one element larger, and then move the other array into the new one starting at element 1 in the new array.


其中有oldie-goldie memmove [
There is the oldie-goldie memmove[^]:
#include <cstring>
  //...
  int a[5] = {1, 2, 5, 2, 1};
  memmove(&a[1], &a[0], sizeof(a)-sizeof(a[0]));


memmove 这样的调用最有可能被优化以利用块内存移动内在操作,尽管一个不错的编译器会看到您的for -loop(或顺序代码(无论您拥有什么),并在编译过程中将其替换为memmove .如果这是一个主要因素,则可以运行一些性能测试,尽管如果仅是数百或什至1000个您正在谈论的元素,则可能无关紧要.
Calls like memmove will most likely be optimized to take advantage of block-memory move intrinsic operations, although a decent compiler would see your for-loop (or sequential code, whatever you have), and replace it with a memmove during compilation. You could run some performance tests if this is a major factor, although if it''s just a few hundred or even 1000 elements you are talking about, it probably does not matter much.


这篇关于数组操作...变得更简单了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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