Why does an empty vector call the value type’s default constructor?

Because you’re explicitly passing an initial size, which calls a constructor that has another parameter whose default value is s(). Just leave out the (0) (i.e. std::vector<s> v;) and it won’t happen. For completeness, the Standard 23.2.4-2 defines the constructor you’re calling as:     explicit vector(size_type n, const T& value =T(),                                     const Allocator& = Allocator()); Aside … Read more

How can I unpack (destructure) elements from a vector?

It seems what you need is “slice patterns”: fn main() { let line = “127.0.0.1 1000 what!?”; let v = line.split_whitespace().take(3).collect::<Vec<&str>>(); if let [ip, port, msg] = &v[..] { println!(“{}:{} says ‘{}'”, ip, port, msg); } } Playground link Note the if let instead of plain let. Slice patterns are refutable, so we need to … Read more

C++ template function compiles in header but not implementation

The problem you’re having is that the compiler doesn’t know which versions of your template to instantiate. When you move the implementation of your function to x.cpp it is in a different translation unit from main.cpp, and main.cpp can’t link to a particular instantiation because it doesn’t exist in that context. This is a well-known … Read more

How can you erase elements from a vector while iterating?

Since C++20, there are freestanding std::erase and std::erase_if functions that work on containers and simplify things considerably: std::erase(myNumbers, number_in); // or std::erase_if(myNumbers, [&](int x) { return x == number_in; }); Prior to C++20, use the erase-remove idiom: std::vector<int>& vec = myNumbers; // use shorter name vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end()); // or vec.erase(std::remove_if(vec.begin(), vec.end(), [&](int x) … Read more

packed vs unpacked vectors in system verilog

This article gives more details about this issue: http://electrosofts.com/systemverilog/arrays.html, especially section 5.2. A packed array is a mechanism for subdividing a vector into subfields which can be conveniently accessed as array elements. Consequently, a packed array is guaranteed to be represented as a contiguous set of bits. An unpacked array may or may not be … Read more

How to cheaply assign C-style array to std::vector?

The current std::vector doesn’t provide any capability or interface to take ownership of previously allocated storage. Presumably it would be too easy to pass a stack address in by accident, allowing more problems than it solved. If you want to avoid copying into a vector, you’ll either need to use vectors through your entire call … Read more