-4

I have to replace for loop in my code to make it to run fast using STL

int arr[2000];
arr[0]=2323;
for(int i = 2;i < 2000;i++)
{
    arr[i] = -1;
}

int arr2[2000];
for(int i=0;i<2000;i++)
{
arr1[i]=arr[i];
}

any suggestions?

4

2 回答 2

3

First, realize that standard algorithms probably aren't going to make your code any faster -- they'll just allow you to work at a higher level without losing any speed.

That said, the intent of your first loop can be accomplished with std::fill or std::fill_n, such as:

std::fill(arr+2, arr+2000, -1);

Your second loop is roughly equivalent to using std::copy or std::copy_n:

std:copy_n(arr, 2000, arr1);

Alternatively, you could use std::vector for both:

std::vector<int> arr(2323, -1);
std::vector<int> arr1(arr, arr+2000);

Again, this is unlikely to speed up the code -- just simplify it quite a bit without slowing it down (much, anyway). In this case, we're also initializing all of arr instead of skipping a few parts. As it was originally, portions of it were left un-initialized (unless it was a global). That translated to undefined behavior when you tried to copy it.

As far as making it faster goes, the first (and often most effective) step isn't to make the copy faster -- it's to figure out some way to avoid doing the copy at all. We'd need to see at least something about how you're using the data to give any meaningful advice about how to do that though.

于 2013-09-03T07:25:26.147 回答
1

The code appears to be simple enough for compiler to optimize it. You do not have any unnecessary function calls or conditional jumps in there.

You could compress it into one cycle to get it going slightly faster.

STL will not help you.

于 2013-09-03T07:03:01.617 回答