I made a vector of constant size to store negative values, and then printing the values all I got was zeroes. I just want to know why it is not storing negative values.
#include <iostream> #include <vector>  int main() {     std::vector<int> v(5);     v.push_back(-1);     v.push_back(-2);     v.push_back(-3);     v.push_back(-4);     v.push_back(-5);      for (int i=0; i<5; i++)        std::cout << v[i] << " ";  // All I got was zeroes } 
                To convert negative values in a matrix to 0, we can use pmax function. For example, if we have a matrix called M that contains some negative and some positive and zero values then the negative values in M can be converted to 0 by using the command pmax(M,0).
The recommended way is to use the remove_if and erase pattern. Note that std::vector has two versions of erase().
That's because push_back puts new elements onto the end of the vector.
You can see the effect by running i to 9: the negative numbers will occupy v[5] to v[9].
Writing
std::vector<int> v{-1, -2, -3, -4, -5};   instead is a particularly elegant fix.
The constructor that you invoke fills the first 5 elements with zeros, see here (#3 in the list of overloads):
Constructs the container with count default-inserted instances of T
(where the "default-inserted instance" of an int is 0). What you might have wanted is
std::vector<int> v;  v.reserve(5); /* Prevent unnecessary allocations as you know the desired size. */  v.push_back(-1); /* ... */   An alternative using the original constructor call is
#include <numeric>  std::vector<int> v(5);  std::iota(v.rbegin(), v.rend(), -v.size());   though this does more work than necessary as every element is first default constructed and then assigned to a new value again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With