question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
70,597,027
70,687,515
GPU Memory Management in OpenGL and DirectX 12
I am currently improving my knowledge in OpenGL and DirectX 12 in order to create graphics applications with both APIs. I studied several tutorials but I still do not completely understand, how the memory is managed on the GPU side. In OpenGL (my application runs an OpenGL 3.3 context), the frame buffers are created im...
For DirectX 12, it uses the same lifetime model as previous versions of Direct3D: The object is kept alive until the reference count hits 0. It's then eligible for destruction. The exact time of cleanup is up to the driver/runtime as it typically does 'delayed destruction' (it actually has both an 'internal' and 'exter...
70,597,506
70,597,619
Does Enum have any downsides to using
Recently I found out that there is such a thing as enumerations in C and C ++. It immediately seemed to me that it is very visually convenient. But, please tell me, does the enum have any negative aspects? If I use them extensively in my code - will this not lead to some kind of problem in the future?
Here are the drawbacks of the classical enumerations: The enumerators have no scope (C) The enumerators implicitly convert to implicitly to int The enumerators pollute the global namespace The type of the enumerator is not defined. It just has to be big enough to hold the enumerator. This link contains relevant and...
70,597,800
70,598,258
Convert from std::wstring to std::string
I'm converting wstring to string with std::codecvt_utf8 as described in this question, but when I tried Greek or Chinese alphabet symbols are corrupted, I can see it in the debug Locals window, for example 日本 became "日本" std::wstring_convert<std::codecvt_utf8<wchar_t>> myconv; //also tried codecvt_utf8_utf16 std::s...
std::string simply holds an array of bytes. It does not hold information about the encoding in which these bytes are supposed to be interpreted, nor do the standard library functions or std::string member functions generally assume anything about the encoding. They handle the contents as just an array of bytes. Therefo...
70,597,988
70,598,081
Generic friend operator== overload
I am currently stuck on a problem that I can't solve. I am a beginner in the world of c++. For a homework, I have to create a generic class to represent a fraction like 5/6 or 11/4. This class is generic which allows to determine the type of the nominator and numerator (unsigned short, unsigned, unsigned long). The goa...
You can do this the following way: template <typename T> class Frac { //friend declaration template <typename S, typename U> friend bool operator==(const Frac<S>& lhs, const Frac<U>& rhs); private: T numerator, denominator; }; template <typename T, typename U> bool operator==(const Frac<T>& lhs, const Frac<U>& ...
70,598,124
70,601,026
Calling child method from obj of parent class
I have a couple of classes derived from Element. Each of them has a generate() method that returns something. Also, I have a Rep class that is derived from Element, too. I need to initialize a Rep object with any of Element children and be able to call generate(). #include <string> #include <vector> #include <iostream>...
Rep is slicing the Element it is being given. And Element does not have a generate() method. But even if it did, it would have to be virtual, but you can't overload a virtual method based solely on its return type. I would suggest making Rep be a template class instead, eg: template<typename ActionType> class Rep : pu...
70,598,245
70,600,534
Initialize pointer member in struct with array of ints
I have an int* member in my struct. I want to initialize this member while initializing the struct, without having to resort to a temp array: struct MyStruct{ int* arrInts; }; MyStruct m = { {1, 2} // Nor does compound literals work: (int[]){2, 4, 6} }; This throws an error in MSVC 2019. So a t...
That is solution b: A compatible replacement for int*. In this version I disabled the copy constructor and copy assignment altogether. If you want to copy, you have to decide and specify what happens with the arrInts array (e.g. should another array be allocated or the pointer should point at the same array). The arrIn...
70,598,413
70,598,874
Why does std:sqrt on Eigen's diagonal().row() fail with "no instance of overloaded function matches argument list"
I am trying to calculate the square root of each element of the .diagonal() of a Eigen::Matrix3d. Using std::sqrt(matrix.diagonal().row(i)) will give me a compile error: no instance of overloaded function "std::sqrt" matches the argument list -- argument types are: (Eigen::Block<Eigen::Diagonal<Eigen::Matrix<double,...
It's because the result type of matrix.diagonal().row(n) is a one by one matrix. You can convert this to a flat type with the .value() member function: #include <iostream> #include <Eigen/Dense> int main() { Eigen::Matrix3f m; m << 1, 2, 3, 4, 5, 6, 7, 8, 9; std::cout << std::sqrt( m.dia...
70,599,707
70,599,835
Removal of the punctuation from strings given as an input by the user
Am presently reading the book C Primer 5th edition, and this question is asked in the book, question problem being 3.10. So, basically we have to remove the punctuations if they exist in the string that we would provide it with. I've attempted the question and even I get the successful output when I initialize the stri...
Standard cin >> only gets the first "word" in a line; words are typically separated by a space, which is why everything after the space after he@@,llo is ignored. What you need to use instead is getline(cin, s) to capture the entire line.
70,599,823
70,600,770
Shared_ptr instance is not set for an object as expected
I have a struct A which has a member another struct C. So A with c1Ptr_ as member. I use 2 structs S and N. N has as member A, a_ and S has as member C, c_. After I instantiated A and create for S a c object using the created A object and I pass the created A object to N I would expect to have the A->c1Ptr_ in N as we...
You can try to work this out on your own by drawing the objects a, s, and n and their contents, and what their contents point to: auto a = std::make_shared<A>(); // a(c1Ptr_ = null) S s(a->c1Ptr_); // a(c1Ptr_ = null), s(c1Ptr_ = null) N n(a); // a(c1Ptr_ = null), s(c1Ptr_ = ...
70,600,162
70,600,219
Double object pointer array as function argument?
I come with a perhaps odd question. I was doing an exercise and I ran into a problem. The point was to make an Employee class, and then a function that has an array of Employee** and its size as an argument, and to make it show every employee with more than 5 years of experience. Here is the relevant pieces of the Empl...
The way you are passing in the array is wrong. Currently Employee** tab[] means that you have an array of pointers to a pointer to an Employee object. What you want to have is either Employee* tab[] or Employee** tab which are both arrays of pointers to an Employee object. Note that Employee** is the same as Employee* ...
70,600,536
70,600,738
how to properly convert byte array in java to char pointer in jni
I am new to C/C++, so I don't know how to properly convert a byte array in Java to a char array in JNI. For example, I have an inputString containing "Hello world!", I use this to get the byte array: byte[] data = inputString.getBytes(); Then in the JNI layer, I use: jbyte *array = (*env)->GetByteArrayElements(env, da...
Your byte[] array is not null-terminated (does not end with a 0x00 byte), but you are clearly treating it as if it were. When printing the bytes, the "extra" characters are random values coming from surrounding memory when the print accesses beyond the bounds of the array, which is undefined behavior. Use (*env)->GetAr...
70,600,886
70,602,114
How do I use a composed Asio operation with C++20 coroutines to return a value?
I have a composed async operation which uses non-boost Asio 1.18.1 to resolve and connect to a host and service. I want it to pass the actual endpoint it connects to, to the completion token. Right now it does not. #include <iostream> #include <string_view> #include "asio.hpp" template <typename Token, typename Execu...
I thought I had already tried this, but just changing the signature of the async_compose template parameter and self.complete works. For errors it seems like you need to explicitly catch the system_error, pass it as a error_code to the completion handler, and it may be either passed to the completion handler of the use...
70,601,602
70,608,644
How to work with Rcpp strings variables which could be NULL?
I am writing an R package + Rcpp code to work with an existing C++ library. After going through the tutorials here: https://gallery.rcpp.org/articles/optional-null-function-arguments/ , I'm struggling with how to work with NULL and strings. I am confused that I cannot cast from type Rcpp::Nullable<std::string> to std::...
Here is a minimally complete answer. In the function body you can adjust your tests according to your needs, this is just a placeholder example. Code #include <Rcpp.h> // [[Rcpp::export]] Rcpp::List foo(Rcpp::NumericVector v) { // we just us a random vector here to determine: if positive // we inject a strin...
70,601,822
70,602,002
In practice, when `std::unordered_map` must be used instead of `std::map`?
In practice, is there any circumstance which std::unordered_map must be used instead of std::map? I know the differences between them, say internal implementation,time complexity for searching element and so on. But I really can't find a circumstance where std::unordered_map could not be replaced by std::map indeed.
I know the difference between them, say internal implementation,time complexity for searching element In that case, you should know that that the average asymptotic element lookup time complexity of unordered map is constant, while the complexity of ordered map is logarithmic. This means that there is some size of co...
70,601,992
70,603,934
c++ thread local counter implement
I wanna implement a high performance counter in multi-thread process, like this, each thread has a thread local counter named "t_counter" to count query(incr 1/query) and in "timer thread" there is a counter named "global_counter", what I want is each second, global_counter will get each t_counter(s) and add them to gl...
Starting with your second question, you can find all the specifications here. Summarizing, thread local variables are defined in .tdata / .tbss. Those are somewhat similar to .data, however accessing those is different. These sections are replicated per thread. The actual variable offset is computed at the runtime. A v...
70,602,043
70,641,231
Avoid memory fragmentation when memory pools are a bad idea
I am developing a C++ application, where the program run endlessly, allocating and freeing millions of strings (char*) over time. And RAM usage is a serious consideration in the program. This results in RAM usage getting higher and higher over time. I think the problem is heap fragmentation. And I really need to find a...
If everything really is/works as you say it does and there is no bug you have not yet found, then try this: malloc and other memory allocation usually uses chunks of 16 bytes anyway, even if the actual requested size is smaller than 16 bytes. So you only need 4000/16 - 30/16 ~ 250 different memory pools. const int chun...
70,602,278
70,625,182
Openmp with more than INT_MAX iterations - is it legal?
Here is a loop that works perfectly fine: #include <inttypes.h> #include <iostream> int main() { for (int32_t i = -2; i < INT32_MAX-2; i++) { std::cout << i << std::endl; } } Adding omp parallel for clause seems to break the code by introducing int overflow. #include <inttypes.h> #include <iostream> int main()...
It's not a bug in a compiler but rather unspecified behavior in OpenMP. See 2.9.1 Canonical Loop Form If var is of an integer type, then the type is the type of var. ... The behavior is unspecified if any intermediate result required to compute the iteration count cannot be represented in the type determined above. ...
70,602,526
70,602,577
Search paths "/usr/local/include/glm/gtx" versus Use of undeclared identifier 'gtx'
Mac Big Sur C++ OpenGL attempting to learn quaternions from a tutorial. The gtx headers are under usr/local/include/glm. Can anyone figure out what is wrong with my header includes or header search path? Thanks. Minimum reproducible code that fails for this issue: #pragma clang diagnostic push #pragma clang diagnostic ...
In tutorial 1 of the link in the comment, the author introduces using namespace glm; which I assume they expect you to use throughout the tutorials. The namespace that you want to look into is not just gtx, but glm::gtx, so without the using namespace you need to fully qualify it: MyQuaternion = glm::gtx::quaternion::...
70,603,024
70,604,319
error: expected primary-expression before ‘long’ long double d = 1/long double(n); | ^~~~
I wrote a program which takes an integer k and calculates geometric sum till 2^k. using namespace std; long double recursive( long double n){ if(n==1){ return 1; } long double ans = recursive(2*n); return n+ans; } int main() { int k; cin>>k; int n = 1<<k; long double d ...
This is something inherited from C. While doing the code analysis, the compiler sees "long" and "double" as two separate words. The same would occur for something like "unsigned int". There are multiple ways to achieve what you want. In C you would cast it long double my_var = 1/(long double)4; C++ supports this becau...
70,603,855
70,704,065
How to set python function as callback for c++ using pybind11?
typedef bool (*ftype_callback)(ClientInterface* client, const Member* member ,int member_num); struct Member{ char x[64]; int y; }; class ClientInterface { public: virtual int calc()=0; virtual bool join()=0; virtual bool set_callback(ftype_callback on_member_join)=0; }; It is from SDK which I ...
You need a little C++ to get things going. I'm going to use a simpler structure to make the answer more readable. In your binding code: #include <pybind11/pybind11.h> #include <functional> #include <string> namespace py = pybind11; struct Foo { int i; float f; std::string s; }; struct Bar { std::fun...
70,604,357
70,605,251
std::map with std::vector as key -- complexity of lookup function
I have a set of N customers, indexed 0,...,N-1. Periodically, for some subset S of customers, I need to evaluate a function f(S). Computing f(S) is of linear complexity in |S|. The set S of customers is represented as an object of type std::vector<int>. The subsets that come up for evaluation can be of different size e...
Complexity of lookup in a map is O(log N) That is, roughly log N comparisons are needed when there are N elements in the map. The cost of the comparison itself adds to that linearly. For example when you compare M vectors with K elements, then there are roughly log N comparisons, each comparing M*K vector elements, ie ...
70,604,358
70,631,970
Does pybind11 default arugments expression been called every time when the python API been invoked?
I'm trying to add an expression as default arguments to my python function API, which is implemented by pybind11. For example, here's the C++ function: void my_print(std::chrono::system_clock::time_point tp = std::chrono::system_clock::now()) { std::cout << tp << std::endl; } PYBIND11_MODULE(my_module, m) { m.doc(...
This is evaluated once, during the (runtime) initialization of the pybind bindings. The way this feature is implemented is by overloading operator= of py::arg to return a different type, py::arg_v (short for argument with default value).
70,604,628
70,604,691
Recursive class template and implicit instantiation error in C++
The following minimal reproducible example contains a template struct B with default argument type containing a lambda A<[]{ return 1; }>, B is recursively inherited from B<>. And there is a specialization of B for any A<z>. template<auto> struct A{}; template<class = A<[]{ return 1; }>> struct B : B<> {}; template<a...
Which compiler is right here? Both are, since B is ill-formed; NDR. As always, [temp.res]/8 applies: The validity of a template may be checked prior to any instantiation. The program is ill-formed, no diagnostic required, if: (8.4) - a hypothetical instantiation of a template immediately following its definition wou...
70,604,687
70,604,756
why would returned value of "make_share<Type>" in function list be rvalue?
here is my code: #include <bits/stdc++.h> class Quote { public: Quote() = default; Quote(const string& book, double sales_price) : bookNo(book), price(sales_price) {} string isbn() const { return bookNo; } private: string bookNo; double price = 0.0; }; class Basket { public: void add_item(sh...
std::make_shared returns a std::shared_ptr<...>, which is not a reference type, therefore the expression std::make_shared<...>(...) is a prvalue (a subcategory of rvalues). This is true for all functions returning objects by-value, rather than by-reference. Non-const lvalue references cannot bind to rvalues, as the mes...
70,605,134
70,606,154
Implement a template of a Queue, using 2 Classes
I have a problem. I have implemented a Queue, while using a Class "Queue" and a Class "Element". the problem i have now is, that I can't work out how to create the template for class Element. If I don't use the template and just use int instead of T. Everything works fine. I already looked for many examples on the Inte...
The implementation of template classes must be done in the .h The following code compiles. #include <iostream> #include <string> template <class T> class Element{ public: Element( T inhalt_element ){ inhalt = inhalt_element; next = nullptr; } T getInhalt() const { return inhalt; } void setInhalt(T ...
70,605,511
70,606,034
How to use 'mutable' correctly so the set iterator won't be const?
I'm trying to remove the employee in my code and change his salary back to 0, but all I get in the function is his id. I used the built in iterator for the set, but found out that it is const. How can I use mutable, or some other way to change his salary to 0? I have an employee and a manager- the manager can hire or f...
The design of std::set ensures that elements of the set "cannot be modified" i.e. they can only be accessed via const references. This is for a good reason: std::set relies on the order of its elements remaining the same thoughout the lifetime to maintain its internal search tree datastructure. Ways to deal with this a...
70,605,685
70,605,796
How is this 'for' loop relevant in the keylogger?
I'm reading a book on writing a keylogger for fun; I came across this 'for' loop and I'm confused as to how it is relevant. #include <iostream> #include <fstream> #include <windows.h> #include <Winuser.h> using namespace std; void log(); int main() { log(); return 0; } void log() { char c; for(;;) ...
for(;;) The infinite loop keeps running (listening) for(c=8;c<=222;c++) Run values from 8 to 222 included [8,222] GetAsyncKeyState(c) == -32767) Determines whether a key is up or down at the time the function is called So now you are testing against that ASCI represented by c. Now what does the magic number -3276...
70,605,861
70,606,007
Cannot find std::experimental::when_any
I am trying to use std::experimental::when_any and std::experimental::when_all which according to Anthony Williams are in <experimental/future> header. I am using Visual Studio 2022 (same is for 2019) and cannot find this header/functions neither under C++17 standard nor under C++20 standard configurations. Can someone...
The experimental headers are not part of the standard. An implementation may provide them, but is not required to. They are defined for features that the C++ committee is working on incorporating into a future standard. Neither Visual Studio 2019 nor 2022 provide <experimental/future>
70,606,942
70,608,140
Choosing from multiple DLL versions
Today I build my application and packaged the installer with QtIF. It worked nice on my computer but complained about missing msvcp140_1.dll in another computer. Then I run find . -iname "msvcp140_1.dll" and found more than five different ones on my computer, I checked the md5sum. Then I spend the time to try all of th...
Call the MS Redist Installer from your Installer. This can be done quietly, so that the end user does not notice it. Find the vcredist_x64.exe file (or vcredist_x32 for 32 Bit applications), add it to your installer, let it extract to the "TEMP" folder and then call vcredist_x64.exe /quiet at the end of your install. ...
70,607,712
70,607,881
Attempting to reference a deleted function (copy c'tor)
I got this example of spinlock from Anthony Williams, and its something wrong with it (or I had a long day). #include <atomic> class spinlock { std::atomic_flag flag; public: spinlock() : flag(ATOMIC_FLAG_INIT) {} void lock() { while (flag.test_and_set(std::memory_order_acquire)); } void un...
ATOMIC_FLAG_INIT can only be used as follows: std::atomic_flag v = ATOMIC_FLAG_INIT; It is unspecified if flag(ATOMIC_FLAG_INIT) will work. If visual studio defines ATOMIC_FLAG_INIT as {} then your code is presumably ending up creating an std::atomic_flag with {} then calling the deleted copy constructor of flag. If ...
70,608,353
70,608,420
How to get rid of warnings that precompiler definitions are not definied
There is a file that I downloaded from the Unity web-site #pragma once // Standard base includes, defines that indicate our current platform, etc. #include <stddef.h> // Which platform we are on? // UNITY_WIN - Windows (regular win32) // UNITY_OSX - Mac OS X // UNITY_LINUX - Linux // UNITY_IOS - iOS // UNITY_TVOS -...
You should not use #if to test an undefined macro. The warning implies that you should use #ifdef instead. You may not define a previously defined macro. You could first undefined the old definition, but that's rarely a good idea. Using ifdef helps to get rid of the first warning, but the second one is still in place ...
70,608,372
70,608,566
tuple of vectors from std::tuple
I'm trying to create a tuple of vectors from a std::tuple (Reason: https://en.wikipedia.org/wiki/AoS_and_SoA) and came up with the following piece of code. Can anyone think of a more elegant, less verbose solution? PS: I'm stuck with a C++14 compiler... template<std::size_t N, class T, template<class> class Allocator> ...
You can use C++14 std::index_sequence to extract the elements of the tuple. #include <tuple> #include <vector> #include <utility> template<class IndexSeq, class Tuple, template<class> class Alloc> struct tuple_of_vectors; template<class Tuple, template<class> class Alloc, std::size_t... Is> struct tuple_of_vectors<st...
70,608,387
70,611,318
SWIG typemap 2d array to Python list
This is next level of this question. I need to cast 2d C char array to Python list. Python side device_info = getInfoFromCpp() print(device_info.angles) for angle in device_info.angles: print("Angel: " + angle) Error <Swig Object of type 'char (*)[MaxStringLength]' at 0x000000D8B2710330> Execution error: 'SwigPyObje...
Your code as is worked for me, but here are some corrections as mentioned in the question comments and a working example: test.i %module test // This works for any size of 2d char array assuming it contains // UTF-8-encoded, null-terminated strings (no error checking!) %typemap(out) char [ANY][ANY] %{ $result = Py...
70,608,425
70,722,807
try except and inheritance
Why the result is "B", I thought that it should hit first inherited class ("A")? When I ran it with class B that do not inherit anything from class A it hits first catch block, but I don't know reason for behavior like this in code below: #include <iostream> #include <exception> using namespace std; class A {}; clas...
Your classes are some variant of the deadly diamond of death case of multiple inheritance: the base class A is twice a base class of C: once directly, and once indirectly via B: A |\ | \ | B | / |/ C The consequence o...
70,608,692
70,608,839
Does program fail because class lack copy ctor or proper assignment operator?
I'm struggling to understand the exact reason the program fails. Regarding the following program: #include <iostream> template < class T, size_t SIZE> class Stack { T arr[SIZE] = {}; int pos = 0; public: Stack & push(const T & t) { arr[pos++] = t; return *this; } Stack & pu...
Because you provided a custom move cosntructor and assignment operator, the compiler no longer generates default copy constructor and assignment operator. You either need to write those too, or, even better, remove the custom move operations. The compiler will then generate all 4 for you, and they might be better than ...
70,608,713
70,609,217
Problem when trying to find memory leaks by using crtdbg.h
I am first time trying to use CRT library to detect memory leaks. I have defined #define _CRTDBG_MAP_ALLOC at the begginging of the program. My program is made of classes one struct and main function. In main function i have _CrtDumpMemoryLeaks(); at the end. I tried to follow these Instructions. And I wanted to get li...
Ok, It was impossible to answer my question with the information I gave(I am sorry). The problem was that I had a Base class and derived classes. And in the base class I did not have a virtual destructor. Adding virtual destructor fixed my problem and removed all memory leaks.
70,608,834
70,609,259
Returning a matrix array in C++ function
I am trying to write an OLS regression in C++. I want the user to specify how many observations and variables goes into the X (independent variable matrix). I want to write this as a function outside the int main() function. But everytime I return the array, I get a type error. How do I specify that I want function inp...
Mistake 1 In C++ the size of an array must be a compile time constant. So take for example, int n = 10; int arr[n]; //INCORRECT because n is not a compile time constant The correct way to write the above would be const int n = 10; int arr[n]; //CORRECT Similarly in your code: int mat[num_rows][num_cols];//INCORRECT b...
70,609,271
70,609,356
c++ call an overriden virtual function with a derived argument
How can I call an overridden virtual function with a derived argument? The argument I'm calling it with is of a derived class of the argument it was defined and overriden with. //Args struct ArgBase{ int val; }; struct ArgDerived: ArgBase{ int derivedVal; }; ///// struct Base { int name; virtual int...
You should accept the argument by reference or pointer for it to behave polymorphically virtual int doSomething(const ArgBase& a) = 0; then you can cast in your overriden function return static_cast<const ArgDerived&>(a).derviedVal; of course static_cast assumes that this cast is valid at runtime. If you are unsure o...
70,609,349
70,609,540
Is assign with braces the same as call the constructor?
I know that for scalar types you can assign values with braces like int a { 0 };. This helps with cast, type conversion ecc. But what for udt? Is shared_ptr<int> myIntSmartPtr { my_alloc(42), my_free }; the same as shared_ptr<int> myIntSmartPtr = shared_ptr<int>(my_alloc(42), my_free); The braces should call the cons...
This is direct list initialization. shared_ptr<int> myIntSmartPtr { my_alloc(42), my_free }; This is an example of the first syntax: T object { arg1, arg2, ... }; (1) The exact effect it has is therefore List initialization is performed in the following situations: direct-list-initialization (both explicit and no...
70,609,855
70,609,963
Data member pointers as associative container keys
I am trying to create an std::set of pointers to data members. However, I can't find a method to sort or hash such pointers. They can't be compared with operator<, they don't seem to be supported by std::less and there is no standard integer type that is guaranteed to hold their representation (they might not fit in st...
Compare them bytewise, e.g. using this comparator: #include <cstring> #include <type_traits> struct BitLess { template <typename T> requires std::has_unique_object_representations_v<T> constexpr bool operator()(const T &a, const T &b) const { return std::memcmp(reinterpret_cast<const char *>(&a...
70,610,264
70,610,839
Where can I find the library that provides String.substring() method?
I'm trying to compile an Arduino project on Linux, abstracting away the hardware parts. Consider the following line: int keyNumRepeat = userInputPrev.substring(6, 8).toInt(); It looks like Arduino uses some non-standard library, which isn't on my system: hsldz_totp_lock/hsldz_totp_lock.ino:335:38: error: ‘String’ {aka...
It looks like Arduino has a custom implementation of String. Since it's open source, here are the header and class files. I only skimmed through them, but they don't appear to be heavily dependent on the rest of the Arduino core API. That said, you may be better off replacing their implementation with standard c++. Esp...
70,610,603
70,611,128
How to declare concept function signature with a template type?
Is there a way to have a concept function signature that has a template argument? Something like this: template<typename SomeTypeT, typename U> concept SomeType = requires(SomeTypeT s) { { s.SomeFunction<U>() }; }; ?
The shown concept definition works, except that you need to tell the compiler that SomeFunction is a template: template<typename SomeTypeT, typename U> concept SomeType = requires(SomeTypeT s) { { s.template SomeFunction<U>() }; }; This is always necessary if you want to reference a template member of a dependent ...
70,611,109
70,611,315
How do std::exception's derivatives pass the string from their constructor to its what() virtual function?
I'd like to reimplement the standard exception hierarchy. std::exception is defined in the following way, according to the documentation: class exception { public: exception () noexcept; exception (const exception&) noexcept; exception& operator= (const exception&) noexcept; virtual ~exception(); virtual cons...
Yes, they most likely store the string in a private member. Not a plain std::string though, because copying those can throw. Probably something equivalent to std::shared_ptr<std::string>.
70,611,234
70,611,406
Default fallback for C++ template functions using enable_if
I want to write a C++ mechanism, where different instantiations of a function are called if a given class Param is derived from a certain base class. This works pretty nicely with std::is_base_of and std::enable_if. However, I would like to have a "default version" of this doStuff() function that is called for "every o...
When using std:::enable_if, you will have to provide a 3rd SFINAE'd overload that handles the default conditions which are not handled by the other overloads, eg: #include <iostream> #include <type_traits> class A {}; class B : public A {}; class X {}; class Y : public X {}; class Other {}; template <typename Par...
70,611,683
70,611,788
Array constant not evaluating to constant even though only constexpr functions called in initialization
This is a simplified, reproducible version of my code: type_id.h template<typename> void type_id() {} typedef void(*type_id_t)(); c_sort.h (based on this answer) template<typename Array> constexpr void c_sort_impl(Array& array_) noexcept { using size_type = typename Array::size_type; size_type gap = array_.si...
A recent version of GCC or Clang will tell you the evaluation that failed to yield a constant expression. See https://godbolt.org/z/adhafn8v7 The problem is the comparison: array_[i] > array_[i + gap] A comparison between unequal function pointers (other than to check whether or not they are equal) has an unspecified ...
70,611,921
70,611,922
Swift Static Library based on C++ sources: linker command failed error: ld: symbol(s) not found for architecture x86_64 clang
I've C++ based swift static library called: FooCppBasedSwiftLibrary It's a Swift Static Library which uses some C++ sources mixed with Objective C using .mm files (Objective C++) ObjectiveC++ classes are exposed to Swift(within the same library) using module.private.modulemap file Library on its own builds successfull...
TLDR: Use linker flag: -lc++ or -lstdc++ // You can skip to the "The Endgame" section below Initial Workaround Background While going through lot of forums for solution I came across someone's thoughts: NOTE: This text is quoted from a thread of similar question (as mine), but the difference being: Importing Swift Sta...
70,612,017
70,612,181
Sudoku Solver code gives unexpected result
Question Link: https://leetcode.com/problems/valid-sudoku/description/ Below is my code for Sudoku Solver. I am expected to return true if the sudoku is solvable else false. class Solution { public: bool solveSudoku(vector<vector<char>> &board, int row, int col) { // If the position is now at the end of the...
You are misinterpreting the task. Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: The filled cells do NOT violate Sudoku's rules.
70,612,196
70,612,374
"using namespace <blank>" within the source for the library <blank>
I'm newish to C++, and I'm trying to write a library. I am using a custom namespace for the library, glz, as this seems like good practice to avoid conflicts with other libraries. The only problem is the library files end up cluttered with the namespace, especially because I have a bunch of types I've defined. For exam...
Will [using namespace glz within the .cpp] end up messing with the namespace of the library users? No, there will not be problems for the library users. But, there can be problems for the library developer / maintainer (i.e. presumably you). The problems are less frequent compared to using namespace in the header. I...
70,612,294
70,612,767
Getting parameter type of function with templates
Let's say I have a function with the following signature: void foo(std::string const& a, int b, char &c) { ... } How could I do something like param_type<foo, 3>::type to get type == char? Background: I have a set of macros/TMP which generates a struct for converting a json object into a c++ value. I also have a s...
You can create a function traits with partial specialization: template <auto func, std::size_t I> struct param_type; template <typename Ret, typename... Args, Ret (*func)(Args...), std::size_t I> struct param_type<func, I> { using type = std::tuple_element_t<I, std::tuple<Args...>>; }; // C-ellipsis version aka p...
70,612,389
70,613,445
std::hex cannot process negative numbers?
I'm trying to use std::hex to read hexadecimal integers from a file. 0 a 80000000 ... These integers are both positive and negative. It seems that std::hex cannot handle negative numbers. I don't understand why, and I don't see a range defined in the docs. Here is a test bench: #include <iostream> #include <sstream> #...
Setting std::hex tells the stream to read integer tokens as though using std::scanf with the %X formatter. %X reads into an unsigned integer, and the resulting value would overflow an int even through the bit pattern fits. Because of the overflow, the read fails, and the contents of i cannot be trusted to hold the expe...
70,612,537
70,612,653
C++ calculation of long long with int
below you can find a part of my C++ code of a box class. When I want to calculate the volume for l=1039 b=3749 h=8473 I am expecting 33004122803. Unfortunately I do not understand why only the first implementation (CalculateVolume1) gives the correct answer. The other two calculations result in -1355615565. Can someone...
In the first one, (long long) l*b*h, the cast applies to l, as if it had been written ((long long)l)*b*h. So l gets converted to long long. And since one of the factors in the multiplication is long long, the other two are promoted to long long and the result of the multiplication is correct. "Fixing" the syntactic err...
70,612,577
70,623,107
Does anyone know of a fix for an MSVC compiler bug/annoyance where SIMD Extension settings get "stuck" on AVX?
Does anyone know of a fix for an MSVC compiler bug/annoyance where SIMD Extension settings get "stuck" on AVX? The context of this question is coding up SIMD CPU dispatchers, closely following Agner's well-known dispatch_example2.cpp project. I've been going back and forth in three different MSVC projects and have dead...
I figured this out (it's simple and boring). For the incremental object files I'm compiling 3 .obj files from the same .cpp (the .cpp with the vector code). When the MSVC SIMD settings are changed in the project level Properties, they may or may not get inherited in the .cpp file Properties. This is where the project g...
70,612,729
70,612,800
Exception thrown when trying to access a protected variable from a child class after a dynamic casting
I am trying to learn about dynamic casting in C++. So I have developed 2 classes to test some things related to dynamic casting: class Entity { protected: int x = 10; public: virtual void f1() { cout << "f1 from Entity class" << endl; } }; class Player : public Entity { public: void f1() { cout << "f1 from...
dynamic_cast will never lie. It checks the runtime type of the object to see if it matches the T gi8ven in the dynamic_cast<T>. You created an instance of the Entity base class. The runtime type of this object is Entity because that's what you created. dynamic_cast knows the runtime type of the object, so it knows dyna...
70,612,730
70,612,834
How can I make this expression involving floating-point functions a compile-time constant?
I have a constant integer, steps, which is calculated using the floor function of the quotient of two other constant variables. However, when I attempt to use this as the length of an array, visual studio tells me it must be a constant value and the current value cannot be used as a constant. How do I make this a "true...
It is not possible with the standard library's std::pow and std::floor function, because they are not constexpr-qualified. You can probably replace std::pow with a hand-written implementation my_pow that is marked constexpr. Since you are just trying to take the power of integers, that shouldn't be too hard. If you are...
70,613,097
70,613,217
In IsClassT<T>, why use "int C::*"? I am confusing about the int type
An example described in book C++ Templates The Complete Guide: template <typename T> class IsClass { private: typedef char One; typedef struct { char a[2];} Two; template<typename C> static One test(int C::*); template<typename C> static Two test(...); public: enum { Yes = (sizeof(IsClass<...
Because the Standard says so. In [dcl.mptr]: 3 - Example: [...] double X::* pmd; [...] The declaration of pmd is well-formed even though X has no members of type double. [...] 4 - A pointer to member shall not point to [...] “cvvoid”. Some possible reasons: if you had to check data members, you wouldn't be able to ...
70,613,175
70,613,425
Atomically copy a bit (or bits) into an integer
I have some code that copies masked bits into an integer by first clearing them in the target int then ORing them into the int. Like this: bitsToSet = 6 targetInt &= ~(1 << bitsToSet) targetInt |= desiredBitValue << bitsToSet The problem is that it now needs to be thread safe, and I need to make the operation atomic. ...
You could use a compare-exchange loop: void SetBitsAtomic(std::atomic<int>& target, int mask, int value) { int original_value = target.load(); int new_value = original_value; SetBits(new_value, mask, value); while (!target.compare_exchange_weak(original_value, new_value)) { // Another thread may...
70,613,471
70,620,457
Cython program (print Hello world) much slower than pure Python
I am new to Cython. I've written a super simple test programm to access benefits of Cython. Yet, my pure python is alot faster. Am I doing something wrong? test.py: import timeit imp = ''' import pyximport; pyximport.install() from hello_cy import hello_c from hello_py import hello_p ''' code_py = ''' hello_p() ''' c...
I strongly suspect a problem in your configuration. I have (partially) reproduced your tests in Windows 10, Python 3.10.0, Cython 0.29.26, MSVC 2022, and got quite different results Because in my tests the Cython code is slightly faster. I made 2 changes: in hello_cy.pyx, to make both code closer, I have added the new...
70,613,489
70,613,597
C++ type to hold members that can't be initialized in the constructor
I have some members that can't be initialized at construction time of the container class because the information to construct them is not available. At the moment I'm using std::unique_ptr to construct them later when the information becomes available. The dynamic allocation/indirection is an unnecessary overhead as I...
std:::optional is what you are looking for, eg: #include <optional> struct Inner { Inner(int someValue) : internalValue(someValue) {} int internalValue; }; struct Outer { Outer(){/*...*/} void createInner(int someValue) { inner = Inner(someValue); } std::optional<Inn...
70,613,542
70,614,185
Conversion from string literal loses const qualifier
error C2664: 'void add_log(char *,...)': cannot convert argument 1 from 'const char [33]' to 'char *' message : Conversion from string literal loses const qualifier (see /Zc:strictStrings) I restarted my computer and now my project stopped being able to be built. I've looked everywhere that had the similar problems b...
As of today, all I had to do was add a const before anything that I use a char* for. This was used with VS2019 using std:c++17 and Multi-Byte Character Set. The original code: void add_log(char* format, ...) The new code void add_log(const char* format, ...)
70,613,774
70,613,916
How to get all derived classes from a base class in C++?
I'm implementing a game engine in C++ which uses an ECS (Entity-Component-System). Each GameObject can have multiple Components (stored in GameObject's std::vector<Component*> _components). I have a method that allows me to get a Component of a GameObject by specifying the type of Component I want: // In GameObject.h t...
Assuming these classes are all polymorphic/dynamic (which they need to be to use typeid like this), you can just use dynamic_cast instead: template <typename T> T* GetComponent() { for (Component* c : _components) { if (T *tc = dynamic_cast<T *>(c)) return tc; } return nullptr; }
70,614,047
70,614,178
Using erase - is there a way to make this code less repetitive?
This code deletes six lines from a file about a person from a contact list. This code works perfectly fine, however I don't know how to make this code less repetitive. I use a while loop to push my lines inside a vector, and then use the following for loop to erase from the vector. At the end of the loop, I recreate th...
Instead of erasing the first element for 6 times, you can do: file.erase(file.begin() + i, file.begin() + i + 6) The two args in this erase method denotes the range [first, last) to erase. Reference link
70,614,651
70,614,700
Templated function type lost when embedding templates
When playing around with C++20's concepts, I've found that when making a concept describing how a function should be (i.e. T must be a callable function that takes a size_t as argument), then using that concept in another template, the type of the function seems to be "lost". I don't really have a good way of phrasing ...
When you write this: template<typename Func, typename ... Args> concept FuncWithArgs = requires (Func f, Args... args) { f((size_t)1, args...); }; template<FuncWithArgs Func, typename ... Args> void Foo(const Func& f, size_t i = 0, Args... args) { f(i, args...); } The declaration of Foo is shorthand for this: tem...
70,615,011
70,615,056
Non-constant-expression cannot be narrowed from type 'unsigned long' to 'int' in initializer list
please help a c++ newbie understand what is going wrong here. I got compile error message of Non-constant-expression cannot be narrowed from type 'unsigned long' to 'int' in initializer list on leetcode web and my local ubuntu terminal, but it works perfectly fine on my CLion IDE. Also could explain why I got the err...
When you use brace-initialization, it is forbidden for a narrowing conversion to be used to convert from the type of the value in the braced list to the type that the constructor actually requires. heights[0].size()-1 has type size_t, and the constructor of std::vector<int> takes std::initializer_list<int>. Usually, in...
70,615,288
70,615,425
exception thrown error. why is it happening? and what should i do to fix it?
int main() { int** a; int l, h; cout << "the lenght of the matrix is= "; cin >> l; cout << "the height of the matrix is= "; cin >> h; a = new int* [l]; a[l] = new int [h]; //a = new int [l][h]; if (l = h) { Pn(l,a); } } void Pn(int l,int** a) { intMatrix(l, l, a)...
You are not allocating the array correctly. After a = new int* [l];, you try to access a[l], which is out of bounds. You need to allocate a separate int[] for each element of the array's 2nd dimension. Even if you were doing that correctly, there are other problems in the code: leaking the array. if (l = h) is using ...
70,615,371
70,615,581
What happens when running (int *)"some string"
I'm learning the pointer nowadays and I find there is a code on the book std::cout << (int *)"Home of the jolly bytes"; I run it and it print the 0x55c064d9b005 that seem like something's address and I want to know what did it print, so I use "*" try to check its value at that address and convert it to char and foud ...
On this statement: std::cout << (int *)"Home of the jolly bytes"; It is indeed printing the starting address of the characters in the string literal. A string literal is a const char[N] array (in this case, N=24), and an array decays into a pointer to its 1st element. std::istream does not have any operator<< that ac...
70,615,480
70,615,582
Accessing private member variables of a class from a static method
I am able to access the private member variable of the class shown in below code directly using an object instance (pointer to object). As per my understanding private members should not be accessible. Can someone please help to explain the reason behind this behaviour ? #include <iostream> class myClass; using myClas...
static myClassPtr create(unsigned int val) { create() is a static method of myClass, it is a member of this class. As such it it entitled to access all private members and methods of its class. This right extends not only to its own class instance, but any instance of this class. As per my understanding private membe...
70,615,486
70,615,524
Problem with casting pointers from one structure to another structure?
I'm trying to cast the address of individual array components into another structure Here are the structures: #define ADDRESS_SPACE 8 struct dma_engine { int *Address[ADDRESS_SPACE] = {nullptr}; }; struct data_engine { int data[ADDRESS_SPACE] = {0x10,0x14,0x18,0x1B,0x20,0x24,0x28,0x2B}; }; Its working when ...
You need to change Address to be a pointer to int[ADDRESS_SPACE]: #define ADDRESS_SPACE 8 struct dma_engine { int (*Address)[ADDRESS_SPACE] = nullptr; // correct type }; struct data_engine { int data[ADDRESS_SPACE] = {0x10, 0x14, 0x18, 0x1B, 0x20, 0x24, 0x28, 0x2B}; }; int main() { dma_engine Dma_0; ...
70,615,789
70,615,837
undefined reference to `Class::Function() / error: Id returned 1 exit status
I'm trying to initialize value, I follow Bjarne Stroustrup's book but cannot run this code. #include <iostream> using namespace std; struct Date { int y, m, d; // year, month, day Date(int y, int m, int d); // check for valid & initialize void add_day(int n); // increase the Date by n ...
In the C++ programming language, you can define a struct just like you define a class. The reason you're getting the error is because you haven't defined the methods strictly. #include <iostream> using namespace std; struct Date { /* fields */ int _year, _month, _day; /* constructor */ Date(int y...
70,615,937
70,616,088
How to run a command as root with C or C++ with no pam in linux with password authentication
TL;DR How does for example su or sudo work with no PAM? Hello, I want to play around with suid and stuff, I already got the SUID part and the SUID bit and stuff, but the problem is that it's not asking me for a password and as I want it to ask a password and find su and sudo quite mangled in source I am very confused. ...
First, the basics: each process has a userid and a groupid (I am going to ignore supplemental attributes like additional groupids). Userid 0 is root. That's it, end of story. When you have a process whose userid is 0, it's a root process. End of story. How a process acquires its userid 0 is immaterial. If a process's u...
70,615,977
70,666,261
QThread run function with unknown number of arguments and types
I'm tyring to write a QThread function. And in run function there is a function m_pFunc in the while loop.The m_pFunc is a function pointer with unknown number of arguments annd types. How to achieve this function pointer? void func1(int){ cout<<"func1"<<endl; } void func2(int,char){ cout<<"func2"<<endl; } class CThre...
class CThread: public QThread { Q_OBJECT Q_DISABLE_COPY(CThread) public: using PFunc = std::function<void()>; //use std::function CThread() = default; ~CThread() = default; template<class F> //template here CThread(F&& pFunc) : m_bRunning(false), m_pFunc(...
70,616,526
70,616,986
most efficient way to find all the anagrams of each word in a list
I have been trying to create a program that can find all the anagrams(in the list) for each word in the text file (which contain about ~370k words seperated by '\n'). I've already written the code in python. And it took me about an hour to run. And was just wondering if there is a more efficient way of doing it. My cod...
Using the word sorted alphabetically by character as a search key is the direction to go. And maybe you are already doing this (I hardly ever use python) with this line in your code : [[i,''.join(sorted(i))] for i in ls] Anyway this is my c++ take on your problem. Live demo here : https://onlinegdb.com/_gauHBd_3 #incl...
70,616,742
70,618,465
Can atomic_thread_fence(acquire) prevent previous loads being reordered after itself?
I understand atomic_thread_fence in C++ is quite different with atomic store/loads, and it is not a good practice to understand them by trying to interpret them into CPU(maybe x86)'s mfence/lfence/sfence. If I use c.load(memory_order_acquire), no stores/loads after c.load can be reordered before c.load. However, I thin...
After reading your question more carefully, looks like your modernescpp link is making the same mistake that Preshing debunked in https://preshing.com/20131125/acquire-and-release-fences-dont-work-the-way-youd-expect/ - fences are 2-way barriers, otherwise they'd be useless. A relaxed load followed by an acquire fence ...
70,617,006
70,618,335
How to rotate an object around a point with GLM OpenGL C++?
I'm trying to do something like this, but for some reason my cube still rotates around the origin. What am I doing wrong? glm::mat4 identity = glm::mat4(1.0f); // construct identity matrix glm::mat4 trans; glm::mat4 rot; glm::mat4 transBack; glm::mat4 M; glm::vec4 br = glm::vec4(currentPositionX - 0.4, 0.0f, currentP...
Formula to rotate a point around (x,y,z) is: T(x,y,z) * R * T(-x,-y,-z) // operations are combined from right to left you have to move the point P(x,y,z) to center of locale coordinate system, apply rotate and translate back to world space. auto rotAroundPoint(float rad, const glm::vec3& point, const glm::vec3& axis...
70,617,062
70,617,327
C++ output depends on global variable initialization
This Code is solution of n-queen problem. Solving the problem I found that the output changes depends on global variable ans initialization. If ans initialized before grid and input value is 8, the output value is 28. If ans initialized after grid and input value is 8, the output value is 92. I guess its memory problem...
Your program has undefined behavior. This is because at some points inside the isValid function you're using negative indices while accessing array grid's elements. You can verify this by printing the value of x(which you then use in grid[i][x]) and notice that there are some negative values. This will result in undefi...
70,617,252
70,617,416
what is empty function size?
integer is 4 byte double is 8 byte What is the size of an empty function? void test(){} //-> size???? void test1(){ int a, int b, double c } //-> size???? void test2(){ test() } -> size?????? When I run the program, the result is the same void test(){} void test1() {int a} void main() { cout<<sizeof(&test) <<...
ISO C++ does not have a notion of the size of a function. How the compiler creates the machine-level instructions for the individual functions and merges them into an entire program is not specified by the ISO standard. Every individual platform can do this its own way. Therefore, it would not make sense for the ISO st...
70,617,385
70,657,632
ZMQCPP using socket_t as class variable
I'm creating a class to handle ZMQCPP that I can use within several different projects. I want to have the context_t and socket_t be a class variable so I do not have to pass them around to different functions as parameters (what I currently do). But I keep getting errors and am unsure if this is even possible. I've lo...
For anyone that comes across this; I was able to achieve my desire by using ZMQ C++ API functionality. You'll need the "zmq_addons.hpp". class zmqClientTCP { public: zmqClientTCP(); // Default Constructor ~zmqClientTCP(); // Deconstructor void connect(); ...
70,617,969
70,624,418
ZLIB with small memory usage
I'm working on embedded device (STM32) with < 5kb free FLASH memory left. I'm trying to compress string with zlib library. I created function HERE and it returns -2 (Z_STREAM_ERROR). What I did: On zconf.h, I changed value of MAX_MEM_LEVEL to 1 and MAX_WBITS to 5 to lower memory usage. But i still returns -2 (Z_STREAM...
No. The minimum amount of RAM required by deflate is 9K. You might try a different compressor, such as lz4. The deflate code itself compiles to 33K on my machine (x86_64 ISA), with speed optimization. I tried compiling with aggressive space optimization, which got it down to 25K.
70,618,320
70,618,435
The constructor of base class is not called by derived class when base class pointer is used
Why the base class constructor is not called twice in the following code? #include<iostream> using namespace std; class base{ public: base(){cout << "In the Base Constructor\n"; } ~base(){ cout << "In Base Destructor\n"; } }; class derived: public base{ public: de...
This is a pointer to something. base *bptr; It is not initialised. It does not point to anything clean. It especially does not point to any already created object. Even if it did, that would not cause any constructor to be executed. If there would be any object the pointer points to, then the creation of that object w...
70,618,341
70,623,469
how to create templated-like namespace for member functions
I am curretntly trying to define a namespace/struct which contain function pointers which store a specific implementations (let's say a structure to contain several functions). For now everything works fine with the following structure: class foo{ int a; int b; public: explicit foo(int _a, int _b) : a(_a),...
Since you want some input data to stay longer than a single function call, unless it's fully compile-time data a runtime state is inevitable. The question is how you want this data to be encapsulated - different approaches will yield very different (subjective) feelings of how convenient they are. Based on your usage e...
70,618,350
70,618,565
What exactly empty input means for cin.get()?
I think it's a simple question, but I don't understand the concept in this sample of code, mainly in the while loop: #include <iostream> const int ArSize = 10; void strcount(const char * str); int main(){ using namespace std; char input[ArSize]; char next; cout << "Enter text:\n"; cin.get(input,...
If cin.get(input, ArSize); reads no characters (i.e. the first character it encounters is a newline) it calls setstate(failbit) putting the stream into a failed state and therefore while(cin) becomes false, ending the loop.
70,618,884
70,619,703
Unable to pass `pyarrow` table to `arrow::Table`
I'm trying to pass a pyarrow table to c++ via pybind11. In this example I'm simply trying to print the number of rows of a pyarrow table passed from python. #include <pybind11/pybind11.h> #include <Python.h> #include <iostream> #include <arrow/python/pyarrow.h> // Convert pyarrow table to native C++ object and print i...
The error tells you that the c++ class arrow::Table is missing its full definition. That is often the case if the class is only declared in some header but not defined. To fix the error, you probably need to add an #include statement. The definition might be in the header "arrow/table.h" as suggested in the comments, b...
70,618,889
70,622,162
How to create a program that can overwrite a pre-initialized variable with user inputted data during runtime?
I was tasked to create an ATM mock program and my problem is overwriting the money and PIN variables with the information that the user will enter. Here it is: #include <iostream> using namespace std; void Check(int money) { cout << "Your current balance is: " << money << endl; } void Deposit(int money) { int depo...
You can simply do this by using a while loop. Run an infinite while loop and break it whenever you want to exit from the program. Here is the code: #include <iostream> using namespace std; void Check(int money) { cout << "Your current balance is: " << money << endl; } void Deposit(int money) { int deposit; cout ...
70,619,355
70,623,205
how to utilize cudaMemcpy and cudaMalloc?
I'learning CUDA programming. To figure out what is copy unit of cudaMemcpy() and transport unit of cudaMalloc(), I wrote the below code, which adds two vectors,vector1 and vector2, and stores result into vector3. However, after compilation and execution, the result in vector3 was not as expected. I'm not pretty sure wh...
For an array that is intended to hold 64 int elements: int vec1[64]; ... for(int i=0;i<64;i++){ vec1[i]=i; These are not correct: cudaMalloc((void**)&gpu_vec1,64); cudaMalloc((void**)&gpu_vec2,64); cudaMalloc((void**)&gpu_vec3,64); ... cudaMemcpy(gpu_vec1,vec1,64,cudaMemcpyHostToDevice); ...
70,619,527
70,620,594
GTKMM - Error drawing image for some widths
I'm trying to draw on a window with Gtkmm for C++, cairo::context, gdk::pixbuf. I've noticed that for some widths (in my example 298), instead of my image, I get some horizontal black lines (alternated with white stripes). For other widths (in my example 300) I get a normal image. (I'm just drawing a yellow background...
I'm used to the fact that image rows are often (not always) stored with a certain alignment. Whenever I see an image that appears erroneously in stripes, the row alignment is the first thing I would check. With this suspicion in mind, I look for some gdkmm (or Gdk) doc. Instead I found a comment in the Gdk source code....
70,620,090
70,620,184
Visual Studio: what is the difference between 'Build Solution' and 'Rebuild Solution' when i do not use precompiled headers
I try to understand what is the difference between the 2 built types in visual studio (Build vs Rebuild Solution). As i know when i use precompiled headers the simple built will not complile the precompiled headers as long the code in these files remain the same, but 'rebuilt' will compile them always. So what happend ...
Using Build will typcally only rebuild the files that needs to be rebuilt because of changes you've made to the code. If you create two files in your project/solution, a.cpp and b.cpp, and then Build the first time, both will be compiled (into a.obj and b.obj) and then linked into an .exe file. If you then make changes...
70,620,650
70,621,028
C++ Member and vtable order in diamond (multiple) virtual inheritance
I wanted to know the ordering of member variables and vtable pointers in C++ on a diamond virtual inheritance. Consider the below inheritance: class Base { int b; }; class Derived: public virtual Base { int d; }; class Derived2: public virtual Base { int d2; }; class Derived3: public Derived, public Deri...
what is the correct ordering of member variables and vtable pointers? There is no "correct ordering". This is not specified in the C++ standard. Each compiler is free to arrange the memory layout of this class hierarchy in any fashion that's compliant with the C++ standard. A compiler may choose the layout of the cla...
70,621,067
70,621,191
How does std::unordered_map determine the location of a specific key in a hash table?
The documentation mentions that std::unordered_map uses a hash table. How does it achieve O(1) lookup of a specific key in the hash table? The only way I can think of is to store each key at an address computed from the hash value of the data it holds. If this is the case, how does it keep all of the keys close togethe...
Typically a hash map keeps an array of buckets inside. A bucket, on the other hand is a list of entries. And so something like this: template<class TKey, class TValue> class HashMap { vector<vector<pair<TKey, TValue>>> Buckets; }; Then when you do a lookup, it simply takes the key, computes its hash, say hash, goe...
70,621,203
70,621,498
ifndef with cpp file in new library
Hello im trying to build my own library in c++, and after many hours of searching and trying i learnt that a good way of doing one would be using nested classes, so i made some code in this form of tree: file tree So i divided all the class files into different header files(i know this is harder and maybe not necessary...
Static variables must be defined only once in the entire program. If you define them in a header file, they are defined in every .cpp file that includes the header. Move these lines into a .cpp file: float TestLibrary::Core::Constants::const_PI = 3.1415; float TestLibrary::Core::Constants::const_Euler = 2.71828; Or us...
70,621,688
70,624,442
A "constexpr" function should not be declared "inline"
By analyzing code using SonarLint, I got a message (the title of the question) about a destructor that is declared like below: class Foo { public: . // default ctor . // parameterized ctor . inline ~Foo() = default; // dtor . . // copy ctor = delete . // copy assignment operator = delete . // move ctor . ...
Yes: An explicitly-defaulted function that is not defined as deleted may be declared constexpr or consteval only if it is constexpr-compatible ([special], [class.compare.default]). A function explicitly defaulted on its first declaration is implicitly inline ([dcl.inline]), and is implicitly constexpr ([dcl.constexpr]...
70,622,617
70,622,677
for-loop counter gives an unused-variable warning
My program has an iterative algorithm with a for-loop that I had written as for ( auto i: std::views::iota( 0u, max_iter ) ) { ... } I really like the fact that it can be written like this, even if the necessary header files are enormous. When I compile it though I get a warning that i is an unused variable. When I wr...
i is indeed never used. You might add attribute [[maybe_unused]] (C++17) to ignore that warning: for ([[maybe_unused]]auto i : std::views::iota(0u, 2u)) { std::cout << str << "\n"; }
70,623,318
70,631,611
How to know a generic type T if it has an appropriate constructor for use?
I am implementing a doubly linked list which has sentinel nodes as its head and tail, say this class named List. Node is a private structure in List. This class has a private method Init for initializing the head and tail node, which is invoked in the constructors of List. template<typename T> class List { public: ...
Your code has a type T that should follow the concepts you are requiring. In your case, you want it to be default constructible. If the instantiator of the template doesn't provide a T the complies, it'll get a large template error. You could add a static_assert to your code, to provide a better message (and to provide...
70,623,395
70,624,022
Why doesn't this_thread::sleep_for need to be linked against pthread?
Usually when building thread related code in GCC, explicit linking against pthread is necessary: g++ -pthread main.cxx However, the following code compiles, links, and runs fine without being linked against pthread: #include <iostream> #include <thread> using namespace std::chrono_literals; int main() { std::thi...
Why doesn't this_thread::sleep_for need to be linked against pthread? Because the call to std::this_thread::sleep_for translates into underlying call to nanosleep, which is defined in libc.so.6, and not in libpthread.so.0. Note that when linking with GLIBC-2.34 and later, using other functions (which previously requi...
70,624,027
70,643,475
What to use on Nodejs addons. Node.h or Napi.h
I have some pretty simple questions. What is the main difference between node.h and napi.h. What should I use for normal/personal use case. Why are there more "nodejs" headers. (node.h, napi.h, nan.h, node_api.h, ...) I have looked on Internet for answers on these questions but I could find any. I'm sorry if this is ...
There are four different interfaces for a Node.js addons The raw node.h (C++) which is no interface at all - in this case you will have to deal with different V8/Node.js versions - which is very hard and cumbersome; The old Node.js Nan (C++) which is still maintained and it allows you to have an uniform C++ API across...
70,624,519
70,625,599
Boost gzip how to output compressed string as text
I'm using boost gzip example code here. I am attempting to compress a simple string test and am expecting the compressed string H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA as shown in this online compressor static std::string compress(const std::string& data) { namespace bio = boost::iostreams; std::stringstream compresse...
The example site completely fails to mention they also base64 encode the result: base64 -d <<< 'H4sIAAAAAAAACitJLS4BAAx+f9gEAAAA' | gunzip - Prints: test In short, you need to also do that: Live On Coliru #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/filteri...
70,624,600
70,652,032
faiss: How to retrieve vector by id from python
I have a faiss index and want to use some of the embeddings in my python script. Selection of Embeddings should be done by id. As faiss is written in C++, swig is used as an API. I guess the function I need is reconstruct : /** Reconstruct a stored vector (or an approximation if lossy coding) * * this functio...
This is the only way I found manually. import faiss import numpy as np a = np.random.uniform(size=30) a = a.reshape(-1,10).astype(np.float32) d = 10 index = faiss.index_factory(d,'Flat', faiss.METRIC_L2) index.add(a) xb = index.xb print(xb.at(0) == a[0][0]) Output: True You can get any vector with a loop required_v...
70,625,489
70,627,491
++v2 output to stop before my first variable
I'm trying a very basic C++ exercise: Write a program that prompts the user for two integers. Print each number in the range specified by those two integers. This is my program: #include <iostream> int main() { std::cout << "Write two numbers: " << std::endl; int v1 = 0, v2 = 0; std::cin >> v1 >> v2; s...
I finally added this code in order to work and to read both cases as a comment suggested before: #include <iostream> int main() { std::cout << "Write two numbers: " << std::endl; int v1 = 0, v2 = 0; std::cin >> v1 >> v2; std::cout << "The numbers between " << v1 << " and " << v2 << " are: " << std::end...
70,625,788
70,625,914
Calculate the sum of all arguments(non-type parameters) passed through a template
I want to calculate the sum of all arguments (non-type parameters) passed through a template. I compiled the following program with: g++ -std=c++17 -g -Wall -o main main.cpp. It seems that I miss something, because I get this errors when compiling: error: call of overloaded ‘func<N_0>()’ is ambiguous std::cout <...
In both the first and second code example, calling the function with only one (template) argument results in both function templates being viable. The packs will simply be empty. However, in overload resolution in the second example the variadic template is considered less specialized than the non-variadic one, basical...
70,626,858
70,626,871
macOS: C++11 Compilation Error with Apple clang Version 13 In Terminal but not In Xcode
I'm trying to run an example from Microsoft Docs on delegating constructors in C++. For small bits of code like this, I like to use VS Code, but when I use my usual make command in the terminal I get the error, error: delegating constructors are permitted only in C++11 I do not get this error when I run the same code i...
You need to add --std=c++11 to the g++ command line options in your Makefile. Visual Studio defaults to the latest possible C++ standard. gcc defaults to the earliest.
70,627,117
70,627,498
Loading Wave File but there is random nonsense at the end of the data rather than the expected samples
I've got a simple wav header reader i found online a long time ago, i've gotten back round to using it but it seems to replace around 1200 samples towards the end of the data chunk with a single random repeated number, eg -126800. At the end of the sample is expected silence so the number should be zero. Here is the si...
WAV is just a container for different audio sample formats. You're making assumptions on a wav file that would have been OK on Windows 3.11 :) These don't hold in 2021. Instead of rolling your own Wav file reader, simply use one of the available libraries. I personally have good experiences using libsndfile, which has ...
70,627,386
70,627,591
Segmentation fault looking for longest strings in a vector
Given an array of strings, return another array containing all of its longest strings. The solution I developed is available below: #include <iostream> #include <vector> using namespace std; vector<string> solution(vector<string> ia) { int maxi = -1; int size = ia.size(); vector<string> iasol; for (int i = 0...
Since I found the readability of the source code you developed low, I developed a new solution for this problem. #include <iostream> #include <vector> using namespace std; /* Returns the size of the vector with the maximum length. */ size_t getMaximumSize(vector<string> input); /* Returns a vector container based on...