I need a vector that can be cleared from memory at any time. Here is the code:
auto *joj = new std::vector<int>; int j = *joj.size(); It gives an error: the expression must have the class type in the second line. How to write in this case?
I need a vector that can be cleared from memory at any time. Here is the code:
auto *joj = new std::vector<int>; int j = *joj.size(); It gives an error: the expression must have the class type in the second line. How to write in this case?
int j = joj->size(); int j = (*joj).size(); Choose :)
Just the point priority (member choice) is above the asterisk priority (dereference).
joj->at(i) != 0 . Or do not create a vector with new . - PinkTux(*joj)[i] or joj->operator[](i) . If you need the operator [] . You can use at() , but here it’s a minus (and it’s also a plus :)) in that it checks the outbound vector. - HarryTo begin with, it is not at all clear why you allocate the object of the std::vector class itself in dynamic memory. This object takes up little memory, usually less than 16 bytes, regardless of how many elements it contains.
For example, when you run the following demo program, which declares an object of class std::vector<int> with a thousand elements, the object itself takes only 12 bytes.
#include <iostream> #include <vector> int main() { std::vector<int> v( 1000 ); std::cout << sizeof( v ) << std::endl; } Output to console:
12 Usually, to free up memory occupied by a vector, a technique using the member function of the swap class is used. for example
#include <iostream> #include <vector> int main() { std::vector<int> v( 1000 ); std::cout << "v.capacity() = " << v.capacity() << ", v.size() " << v.size() << std::endl; std::vector<int>().swap( v ); std::cout << "v.capacity() = " << v.capacity() << ", v.size() " << v.size() << std::endl; } Output of the program to the console
v.capacity() = 1000, v.size() 1000 v.capacity() = 0, v.size() 0 As for your code snippet
auto *joj = new std::vector<int>; int j = *joj.size(); then the unary operator * has a lower priority than the postfix operation of the function call, and you just need to first apply the dereference operator to the pointer.
Therefore you can write either as
int j = ( *joj ).size(); either like
int j = joj->size(); Keep in mind that the type int chosen incorrectly to store the result returned by the size function. It may not be able to represent all the values returned by this function. Therefore, at least it would be better to again apply the auto type specifier in the variable declaration. for example
auto j = joj->size(); Like this:
int j = (*joj).size(); Source: https://ru.stackoverflow.com/questions/595380/
All Articles
new. nothing needs to be created vianew. - Abyx