-2
int n=1000000;

vector <int> divisors[1000001];

void solve()

{
   
    for(int i=1; i<=n; i++)
         
        for(int j=i; j<=n; j+=i)
               
      divisors[j].push_back(i);

}

Now, I want to print all the elements of the divisors. How can I do this?

3 Answers3

1

You need two loops to iterate first through the array of vectors, then through each vector. C++ has improved a lot over the years so there's now simple ways to do this:

#include <vector>
#include <iostream>
constexpr int n=1000000;

std::vector<int> divisors[n+1];

void solve()
{
    for(int i=1; i<=n; i++)
        for(int j=i; j<=n; j+=i)
            divisors[j].push_back(i);
}

int main()
{
    solve();
    for (auto &i : divisors)
        for (auto j : i)
            std::cout << "array index:" << &i - &divisors[0] << "  Entry " << j << std::endl;
}

As an aside, this is quite slow because vectors are expanded producing a lot of heap thrashing. One way to speed this up quite a bit is to make a second array of ints and increment the value in each element using the same loop structure. Then go through all the vectors in the array and resize them to the required size. I'll leave this as an exercise for the OP.

doug
  • 3,840
  • 1
  • 14
  • 18
0

You need to go through the size of the vector like so,

for(int i = 0; i < vector_name.size(); i++){
    cout << vector_name.at(i) << " ";
}
Yunfei Chen
  • 630
  • 1
  • 8
  • 20
  • `vector` is not an object. – doug Jul 07 '20 at 03:28
  • You should provide an answer that uses the OP's example names. Ideally one that iterates through the array of vectors then through the elements of each vector many of which will be empty. – doug Jul 07 '20 at 03:49
0

It also working

vector<int>::iterator it;
for (int i=1; i<=1000000; i++)
{ 
for(it=divisors[i].begin();it!=divisors[i].end(); it++)cout<<*it<<" "; cout<<endl;}