dimanche 19 juin 2016

Can't access vector on the heap


I have a vector in the heap, but can't get its elements - it doesn't compile - gives n error 'cannot bind 'std::basic ostream' Stack vector and simple array work fine. What is wrong here?

#include <iostream>
#include <vector>

using namespace std;

int main()
{

    vector<int> * factors= new vector<int>(4);
    cout<<factors<<endl;
    cout<<(factors+1)<<endl;
    //cout<<factors[1]<<endl;

    factors->push_back(12);
    factors->push_back(232);
    factors->push_back(54);
    factors->push_back(42);

    //cout<<*factors; //error - cannot bind 'std::ostream..' lvalue to 'std::basic_ostream...'
   // cout<<factors[0]; // error

        //vector in stack
    vector<int> factors3(4);
    factors3.push_back(43);
    factors3.push_back(543);
    factors3.push_back(64);
    factors3.push_back(26);
    cout<<"factors3 "<<factors3[3]<<endl; //gives "0"
    cout<<"factors3 "<<factors3.at(3)<<endl; //gives "0"

    int * factors2=new int[10];
    factors2[0]=32;
    factors2[1]=35;
    factors2[2]=676;
    factors2[3]=123;
    cout<<factors2[0]<<endl; //it's OK
    cout<<factors2[1]<<endl;
    cout<<*factors2<<endl;

    cout << "Done" << endl;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire