Posts

Showing posts with the label vector

Is there a convenient way to replicate R's concept of 'named vectors' in Raku, possibly using Mixins?

8 Recent questions on StackOverflow pertaining to Mixins in Raku have piqued my interest as to whether Mixins can be applied to replicate features present in other programming languages. For example, in the R-programming language, elements of a vector can be given a name (i.e. an attribute), which is very convenient for data analysis. For an excellent example see: "How to Name the Values in Your Vectors in R" by Andrie de Vries and Joris Meys, who illustrate this feature using R 's built-in islands dataset. Below is a more prosaic example (code run in the R-REPL): > #R-code > x <- 1:4 > names(x) <- LETTERS[1:4] > str(x) Named int [1:4] 1 2 3 4 - attr(*, "names")= chr [1:4] "A" "B" "C" "D...

What does std::vector look like in memory?

I read that std::vector should be contiguous. My understanding is, that its elements should be stored together, not spread out across the memory. I have simply accepted the fact and used this knowledge when for example using its data() method to get the underlying contiguous piece of memory. However, I came across a situation, where the vector's memory behaves in a strange way: std::vector<int> numbers; std::vector<int*> ptr_numbers; for (int i = 0; i < 8; i++) { numbers.push_back(i); ptr_numbers.push_back(&numbers.back()); } I expected this to give me a vector of some numbers and a vector of pointers to these numbers. However, when listing the contents of the ptr_numbers pointers, there are different and seemingly random numbers, as though I am accessing wrong parts of memory. I have tried to check the contents every step: for (int i = 0; i < 8; i++) { numbers.push_back(i); ptr_numbers.push_back(&numbers.back()); for (auto ptr_number :...

Printing addresses of vector's elements shows garbage [duplicate]

This question already has an answer here: Why does streaming a char pointer to cout not print an address? 4 answers Consider: #include <vector> #include <string> #include <iostream> using namespace std; int main() { vector<char> vChar; vChar.push_back('a'); vChar.push_back('b'); vChar.push_back('c'); vChar.push_back('d'); vector<int> vInt; vInt.push_back(1); vInt.push_back(2); vInt.push_back(3); vInt.push_back(4); cout << "For char vector Size:" << vChar.size() << " Capacity:" << vChar.capacity() << "\n"; for(int i=0; i < vChar.size(); i++) { cout << "Data: " << vChar[i] << " Address:" << &vChar[i] << "\n"; } cout << "\nFor int ve...