Thread: Vector Help

  1. #1
    Registered User gpr1me's Avatar
    Join Date
    Mar 2006
    Posts
    14

    Vector Help

    Say i have code like below:

    Code:
            vector<int> test;
    	test.push_back(1);
    	test.push_back(2);
    
    	for(size_t i = 0; i < test.size(); ++i)
    		cout << test[i] << endl;
    Which prints out:
    1
    2

    Ok no problem. But if i change it so i have a pointer to a vector of int's like this:

    Code:
            vector<int> *test;
    	test->push_back(1);
    	test->push_back(2);
    
    	for(size_t i = 0; i < test->size(); ++i)
    		cout << test[i] << endl;
    I get this error:

    Code:
    Error	1	error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::vector<_Ty>' (or there is no acceptable conversion)	d:\school\comp446\project\genalib\genalib.cpp	18
    So how would i use the [] operator of the vector stl templates when i use a pointer to a vector or int's? Would i have to use test->at(i)? It works if i do that but im just wondering if i can use the [] operator or not.

  2. #2
    Registered User
    Join Date
    Aug 2002
    Location
    Hermosa Beach, CA
    Posts
    446
    Blind guess, dereference the pointer:

    Code:
        cout << (*test)[i] << endl;
    The crows maintain that a single crow could destroy the heavens. Doubtless this is so. But it proves nothing against the heavens, for the heavens signify simply: the impossibility of crows.

  3. #3
    Registered User gpr1me's Avatar
    Join Date
    Mar 2006
    Posts
    14
    thanks, it tried to do that like this:

    Code:
    cout << *test[i] << endl;
    But yeah, i understand now

Popular pages Recent additions subscribe to a feed