Declaration of an array of vectors

When i compile this prog, i get errors sayin
1.'d' undeclared"
2.Each undeclared identifier is reported only once for each function it appears in. what is the problem here with declaration of an array of vectors??


#include<iostream>
#include<vector>
using namespace std;
int main()
{
int m,a,b,i;
cin>>m;
for(i=0;i<m;i++)
{
vector<int> d[i];
}
for(i=0;i<m;i++)
{
cin>>a>>b;
d[a].push_back(b);
}
return 0;
}
You declare d inside one of the for loops; it doesn't exist outside that for loop so an attempt to access it in the next one generates the error.
example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream>
#include<vector>

using namespace std;

int main(){
      int SizeofLoop = 0;
      int number = 0;

      cout << "Enter looping size : ";
      cin   >> SizeofLoop;

      vector<int> v;//Vector is a container
  
      for(int i = 0 ; i < SizeofLoop ; i++ ){
            cout << "Enter number " << (i+1) << " to vector : ";
            cin   >> number;
	    v.push_back(number);
      }

	  for( int i = 0 ; i < SizeofLoop ; i++ ){
		  cout << "Number " << (i+1) << " : " << v[i] << endl;
	  }

      system( "pause" );
      return 0;
}

DO you know clearly about vector?
@felicia123 yeah im fine with what u've coded but my prob is wit assigning an array of vectors in a better scope
@zhuge yep i've got it.. but for declaring an array of vectors,, i need a loop.. so how do i define it in a better scope,, i.e how do i define it such tat it can be accessed throughout the main() function??
like that why you want to use vector?

quite confuse with yours question. haha..
There are two problems with the original code. d only exists within the scope of the first for statement, and one may not define an array with a variable that is not also a compile-time constant: i, although some compilers have an extension enabled by default that allows it.

Since you're already using a vector, why not just use a vector of vectors?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <iomanip>
#include <vector>

typedef std::vector<int> int_vec ;
typedef std::vector<int_vec> vvec ;

int main()
{
    vvec v(5) ; // create a vector containing 5 vector<int>s

    unsigned count = 0 ;

    for ( unsigned i = 0; i<5 ; ++i )
        for ( unsigned j=0; j<5 ; ++j )
            v[i].push_back(count++) ;

    std::cout << "v = {\n" ;
    for ( unsigned i=0; i<v.size() ; ++i )
    {
        std::cout << "\t{ " ;
        for ( unsigned j=0; j<v[i].size(); ++j )
            std::cout << std::setw(2) << v[i][j] << ' ' ;
        std::cout << "}\n" ;
    }
    std::cout << "}\n" ;
}
Last edited on
Topic archived. No new replies allowed.