Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector converted all negative values to zero

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 } 
like image 685
Suhail Akhtar Avatar asked Jul 13 '18 07:07

Suhail Akhtar


People also ask

How do you replace all negative values with 0 in R?

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).

How do you get rid of a negative number in a vector?

The recommended way is to use the remove_if and erase pattern. Note that std::vector has two versions of erase().


2 Answers

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.

like image 170
Bathsheba Avatar answered Sep 21 '22 08:09

Bathsheba


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.

like image 42
lubgr Avatar answered Sep 22 '22 08:09

lubgr