In the normal way I will use:
int A[100];
for (int i = 0; i < 100; i++){
A[i] = i+1;
}
But have any other way to do that more efficient(running time)?
In the normal way I will use:
int A[100];
for (int i = 0; i < 100; i++){
A[i] = i+1;
}
But have any other way to do that more efficient(running time)?
In C++, the most effective (my chosen measure of efficiency is developer effort to produce and maintain) way to start with such problems is to try to find a standard algorithm to fit the bill. In this case, a suitable algorithm is std::iota()
(in standard header <numeric>
since C++11).
std::vector<int> A(100);
std::iota(A.begin(), A.end(), 1); // alternative: std::iota(std::begin(A), std::end(A), 1);
or (if you insist on using an array)
int A[100]
std::iota(std::begin(A), std::end(A), 1);
Before C++11, a use of std::generate()
with an appropriate functor will work. As noted by interjay in comments, that may not be most efficient in terms of developer effort (over, say, a simple loop). However, whipping up an appropriate functor - a struct
type with a suitable constructor, data member, and operator()
- can become second nature once one is used to the notion of using facilities in the standard library.
In C, a simple loop is probably fine, at least in the first instance (i.e. unless you have specific measurements providing evidence that "inefficiency", however, you define that, is excessive).