What is wrong with the following code
vector < double >* a;
a->push_back(25);
a->push_back(30);
a->push_back(15);
a->push_back(40);
cout << a->at(2) << endl;
It should print 15, but it prints nothing
What is wrong with the following code
vector < double >* a;
a->push_back(25);
a->push_back(30);
a->push_back(15);
a->push_back(40);
cout << a->at(2) << endl;
It should print 15, but it prints nothing
a is a pointer but is not properly initialized... it must be like:
int main()
{
std::vector<double>* a = new std::vector<double>;
a->push_back(25);
a->push_back(30);
a->push_back(15);
a->push_back(40);
std::cout << a->at(2) << std::endl;
delete a;
return 0;
}
What is wrong ...?
You are using a pointer where an automatic duration value is more appropriate.
std::vector < double > a;
a.push_back(25);
a.push_back(30);
a.push_back(15);
a.push_back(40);
std::cout << a.at(2) << std::endl;
Your pointer wasn't initialized. Additionally, based on the answer by ΦXocę 웃 Пepeúpa ツ, make sure when you are working with pointers to use new/delete correctly. For every new
keyword, there should be a delete
. It is also good practice to avoid dangling pointers (pointers that do not reference anything) by setting them to NULL
(as of C++11, it's recommended to use nullptr
: NULL vs nullptr (Why was it replaced?) and What exactly is nullptr? questions offer some good explanations) when you are done.
However, in this case, I agree with Acorn. You shouldn't have to point to a vector
object because of how it allocates memory. It should be sufficient to just use a vector
for your solution.