Initialize empty vector in structure – c++
Both std::string and std::vector<T> have constructors initializing the object to be empty. You could use std::vector<unsigned char>() but I’d remove the initializer.
Both std::string and std::vector<T> have constructors initializing the object to be empty. You could use std::vector<unsigned char>() but I’d remove the initializer.
I’ve been reading questions here for an hour or two regarding this error I’m getting and most of them forgot to #include string (which I had already done), or to overload the << operator. Here’s the code in question: And the error I’m getting: All I’m trying to do is return the vector. I read … Read more
There’s a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:
I think the problem is that you are erasing members of the vector you are iterating through. What happens if you erase the first element? i 1 2 3 Ei v1 v2 v3 If we erase 1 when i = 1, our vector indices and values are below and now i = 2. i 1 … Read more
The straight forward answer is you need an iterator. The iterator for std::vector supports random access, which means you can add or subtract an integer value to or from an iterator. The better answer is don’t use an index, use an iterator. What is your loop? You should be able to refactor the loop to … Read more
There are many solutions, here’s a few I’ve come up with:
If you have access to C++11 you can use range-based for loops Otherwise you should use begin() and end() You can also use std::begin and std::end (these require C++11 as well) begin will return an iterator to the first element in your vector. end will return an iterator to one element past the end of your vector. So the order in which you get the elements iterating … Read more
You can call clear, and that will destroy all the objects, but that will not free the memory. Looping through the individual elements will not help either (what action would you even propose to take on the objects?) What you can do is this: That will create an empty vector with no memory allocated and … Read more
You don’t want to push_front on a vector ever. Adding an element to the front means moving every single other element in the vector one element back: O(n) copying. Terrible performance.
Your first statement is not true. The elements in vector<someType> myVector will live until the vector is destroyed. If vector<someType> is a local variable, it will be destroyed automatically when it goes out of scope. You don’t need to call delete explicitly. Calling delete explicitly is error-prone if you take into account that because of exceptions that might be thrown, your delete statement … Read more