Assigning values in a vector in non-sequential order

512 views Asked by At

I want to implement a code similar to the below-mentioned one using vectors in the most efficient and easiest manner. How do I do it?

int a[1005];
for(int i=1;i<=1000;i+=5)
    a[i]=i*i;

When I try doing the same using vectors,compiler throws assertion failed error..subscript out of range...

vector<int> a;
for(int i=1;i<=1000;i+=5)
    a[i]=i*i;

So,I tried pushback function...However the index of vector could only be increased from 0 to number of calls to pushback and not in the way I want i.e 1,6,11,16

vector<int> a;
for(int i=1;i<=1000;i+=5)
    a.pushback(i*i);
3

There are 3 answers

0
Carlton On

Declare the vector with the size you want as a constructor argument: vector<int> a(1000);

4
Galik On

You need to tell the vector how many elements to have.

#include <vector>

int main()
{
    std::vector<int> a(1000); // 1000 elements

    for(int i = 0; i < 1000; i += 5)
        a[i] = i * i;
}

Also note arrays and vectors start from 0 not 1. So a 1000 element array or vector counts form 0 - 999 (not 1 - 1000).

0
PaulMcKenzie On

My answer is going to be a little different than the others so far.

If the goal is to store numbers in a container, and not care about sizing, or care about whether the data is stored contiguously, then the solution could be to use a std::map<int, int>.

Example:

#include <map>
#include <iostream>
using namespace std;

int main()
{
    std::map<int, int> a;
    for(int i=1;i<=1000;i+=5)
        a[i]=i*i;

    // output the results  
    auto it = a.begin();
    while (it != a.end())
    {
         cout << it->first << " has a value of " << it->second << endl;
         ++it;
    }
}

Live Example: http://ideone.com/sfgfmu

Note that there were no changes to your original code, except to change the declaration of vector to map.

Each entry in the map has a key/value pair of the i item as the key, and its square as the data. Then you can use the operator [] of the map similar to how you would use it for an array. However, there are differences, in that a map has to do a lookup, while an array is direct access, plus a map will fill in an entry if the item doesn't already exist.

As far as performance, the map has to store the items differently than an array for this to work. Thus you more than likely will get a small degradation in speed, but not a lot (since a map finds items in logarithmic time, not linear).

So it's up to you whether to stick with a vector and deal with the resizing issue, or go with a std::map and live with convenience with a possible degradation in speed (but may not be a lot if any degradation, depending on your usage).