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,542,993
70,543,751
Why does the thread sanitizer complain about acquire/release thread fences?
I'm learning about different memory orders. I have this code, which works and passes GCC's and Clang's thread sanitizers: #include <atomic> #include <iostream> #include <future> int state = 0; std::atomic_int a = 0; void foo(int from, int to) { for (int i = 0; i < 10; i++) { while (a.load(std::me...
The thread sanitizer currently doesn't support std::atomic_thread_fence. (GCC and Clang use the same thread sanitizer, so it applies to both.) GCC 12 (currently trunk) warns about it: atomic_base.h:133:26: warning: 'atomic_thread_fence' is not supported with '-fsanitize=thread' [-Wtsan] 133 | { __atomic_thread_fenc...
70,543,041
70,545,421
Address of variable supplied instead of its value
I wan testing an example of fopen and fclose in C++ where the code reads the integer values in thee file but if the file is empty (no integers), the value retrieved is not 0 but -858993460. i think this is the address of the variable in fscanf() but how could i get the null or /0 value the following code is problematic...
The fix is simple, never miss returned values of IO functions. FILE* pFile; // pFile = fopen("input.txt", "r"); // fscanf(pFile, "%d", &num); // while (n != 5) { if ((pFile = fopen("input.txt", "r")) == NULL) // If unable to open file return 1; while (n != 5 && fscanf(pFile, "%d", &num) == 1) { // And if num is s...
70,543,372
70,543,641
How to cast from const void* in a constexpr expression?
I'm trying to reimplement memchr as constexpr (1). I haven't expected issues as I have already successfully done the same thing with strchr which is very simmilar. However both clang and gcc refuse to cast const void* to anything else within constexpr function, which prevents me to access the actual values. I understan...
No, it is impossible to use void* in such a way in constant expressions. Casts from void* to other object pointer types are forbidden in constant expressions. reinterpret_cast is forbidden as well. This is probably intentional to make it impossible to access the object representation at compile-time. You cannot have a ...
70,543,449
70,543,537
How to use std::acumulate for matrix
#include <iostream> #include <numeric> #include <vector> using matrix = std::vector<std::vector<int>>; int main() { matrix mtx{5, std::vector<int>(5)}; int sum = 0; for (const auto i : mtx) // can be avoided ? sum += std::accumulate(i.begin(), i.end(), 0, [](int a, int b){a > 0 ? a + b : a...
Based on your lambda, looks like you want to just sum the positive entries: #include <iostream> #include <numeric> #include <vector> using Number = int; using Matrix = std::vector<std::vector<Number>>; int main() { Matrix mtx{5, std::vector<Number>(5, 1)}; Number sum_positives = std::accumulate( mtx.begin(...
70,543,626
70,544,325
Program freezing if function is present after the freezing point
When function analiza() isn't commented, my program shows both messages in input() function. (przed, po), But, if I uncomment the analiza() after input(), it breaks. I tried cleaning buffers, diffrent libraries ect. NOTHING helped. Code: #include <iostream> using namespace std; unsigned int liczba_osob, liczba_klapek,...
For the given input, your function analiza makes 200000 = 2 * 10^5 calls to the function czy_mozliwe. That function in turn calls greatest, which makes 2 * 10^5 iterations of a loop with a comparison in each iteration, and then czy_mozliwe proceeds to run its own loop with 2 * 10^5 iterations. So in order to finish exe...
70,543,672
70,543,700
Allowing access to protected member function for class outside of namespace
Consider the following code: namespace A { class B { protected: friend class C; static void foo(); }; } class C { public: C() { A::B::foo(); } }; int main() { C c; return 0; } As currently constructed, this code will not compile - the friendship declared in class B applies to a (currently non-e...
Adding a forward declaration for class C worked for me, what compiler are you using? class C; namespace A { class B { protected: friend class ::C; static void foo(); }; } // ... Live demo Edit: as Vlad points out, both friend C and friend ::C also work, provided you have that forward declaration in...
70,543,980
70,544,218
Finding if a class template can be instantiated with a set of arguments, arity-wise (in C++17)
I have a template that takes a template template parameter and a pack of type arguments. I want to instantiate the template with the arguments only if the arities match. Something like this: // can_apply_t = ??? template<template<typename...> typename Template, typename... Args> struct test { using...
fantasized that it would be as simple as this: No... not as simple... when you write using type = std::conditional_t<can_apply_t<Template, Args...>, Template<Args...>, void>; the Template<Args...> must be an acceptable type also when test of conditional...
70,544,353
70,544,509
How to make online compilers to ignore debug statements in C++?
I am using these lines of code for debugging my C++ program. void dbg_out(){cerr << endl;} template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); } #define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) But the problem with this is t...
You can make the preprocessor conditionally define the macro: #ifdef DEBUG_LOG #define dbg(...) std::cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__) #else #define dbg(...) #endif Now if you compile with the option -DDEBUG_LOG, the log would be sent to std::cerr. An online judge wouldn't add that command ...
70,545,403
70,545,514
Libcurl - curl_multi_wakeup
Reading the function description curl_multi_wakeup: enter link description here Calling this function only guarantees to wake up the current (or the next if there is no current) curl_multi_poll call, which means it is possible that multiple calls to this function will wake up the same waiting operation. I am confused...
curl_multi_wakeup is meant to be used with a pool of threads waiting on curl_multi_poll. What the document says is that if you call curl_multi_wakeup repeatedly, it will possibly wake up only a single thread, not necessarily one thread for each call to curl_multi_wakeup.
70,545,636
70,545,666
Is there a way to check if a platform supports an OpenGL function?
I want to load some textures using glTexStorageXX(), but also fall back to glTexImageXX() if that feature isn't available to the platform. Is there a way to check if those functions are available on a platform? I think glew.h might try to load the GL_ARB_texture_storage extensions into the same function pointer if usi...
You need to check if the OpenGL extension is supported. The number of extensions supported by the GL implementation can be called up with glGetIntegerv(GL_NUM_EXTENSIONS, ...). The name of an extension can be queried with glGetStringi(GL_EXTENSIONS, ...). Read the extensions into a std::set #include <set> #include <str...
70,545,944
70,546,154
c++ coroutines final_suspend for promise_type
below is a snippet testing empty coroutine playing with promise_type #include <iostream> #include <coroutine> #define DEBUG std::cout << __PRETTY_FUNCTION__ << std::endl struct TaskSuspendAll { // must be of this name struct promise_type { TaskSuspendAll get_return_object() noexcept { ...
Being suspended at its final suspend point is the definition of a coroutine being done. Literally; that's what coroutine_handle::done returns. Attempting to resume such a coroutine is UB. So your expectation is not correct.
70,546,084
70,577,034
How do I annotate seq-cst atomic fences for the thread sanitizer?
I learned that TSAN doesn't understand std::atomic_thread_fence, and to fix it, you need to tell TSAN which atomic variables are affected by the fence, by putting __tsan_acquire(void *) and __tsan_release(void *) next to it (for acquire and release fences respectively). But what about seq-cst fences? As I understand, t...
@dvyukov on Github confirmed the __tsan_acquire+__tsan_release instrumentation (same as for acq-rel fences) should be enough. I'm not sure if it means that TSAN doesn't distinguish between seq-cst and acq-rel operations in general, or not.
70,546,162
70,546,215
Function to provide a default value when working with std::map
I am trying to write a function, which will give me a default value when the key is not inside a std::map. In all cases will my default value be numerical_limit::infinity(). Hovewer this simple example is not working. #include <iostream> #include <map> #include <limits> template<typename KeyType, typename ValueType> V...
First of all you use operator[] on the map object inside the function. That will never be allowed because it is a non-const function and you have passed the map by const reference. Instead you should rewrite the function implementation to use iterators: template<typename KeyType, typename ValueType> ValueType mapDefa...
70,546,204
70,546,230
C++ how can I create an array of objects when there is a constructor?
If myClass does not have a constructor the following works fine: myClass x[5]; If I put a constructor in myClass this line results in a compiling error. What is standard practice for creating an array of objects when a constructor is defined? Is it possible to populate the entire array of objects with a single const...
If myClass does not have a constructor the following works fine: This is if your class has no user-declared constructor. In that case it has an implicitly-declared default constructor, which is what will be used by myClass x[5]; to construct the objects. If you declare a constructor yourself, the implicit default co...
70,546,540
70,546,569
Infinite loop created when inputting "yy" into a char variable that should only take a single character such as 'y' or 'n', "nn" does not break code
The code in the cont function asks the user if they want to play my game again. The code works when receiving proper character inputs such as 'y' or 'n' as well as their respective capital letter variants, and the else block works properly to loop the function if an invalid input such as 'a' or 'c' is entered. However ...
Does it only take the first value? Yes, the >> formatted extraction operator, when called for a single char value, will read the first non-whitespace character, and stop. Everything after it remains unread. why does 'yy' cause a loop Because the first "y" gets read, for the reasons explained above. The second "y" r...
70,546,571
70,546,781
WSL Ubuntu showing "Error: Unable to open display" even after manually setting display environment variable
I'm using g++ on WSL Ubuntu. I cloned the GLFW repo using git, used the ccmake command to configure and generate the binaries, then used make inside the "build" directory to finally create the .a file. I installed all the OpenGL-related libraries to /usr/ld (I don't recall exactly which I installed, since I had to inst...
WSL on Windows 10 does not include support for GUI apps. You can build an app with OpenGL/X libraries, sure, but running it requires an X server on which to actually display it. In general, you have 3 options. I believe all of these will work with OpenGL, although I have not tested each of them in that capacity: The...
70,546,582
70,546,644
Passing istream& to function, calls constructor?
I'm reading C++ Primer, Lippman et. al. 5/e. Section 7.5.2. Delegating Constructors says, class Sales_data { friend std::istream &read(std::istream&, Sales_data&); public: // nondelegating constructor initializes members from corresponding arguments Sales_data(std::string s, unsigned cnt, double price): ...
the istream& constructor This is just a short-hand for "the constructor with a (single) parameter of type istream&". It may be a bit unlucky wording, since there is a possibility of confusion with "the constructor of istream&", but the difference is usually clear from context. Here it is obvious because it doesn't ma...
70,546,590
70,563,007
CGAL: identify "non-border" edges
I'm discovering CGAL, I tried the 3D convex hull. I tried it with the vertices of a cube, and I observed that the convex hull is a triangulation (I'm using Surface_mesh, not Polyhedron_3). So CGAL includes the diagonals of the faces of the cube in the list of edges. I want to identify such edges (because, for example, ...
A border edge is an edge that is incident to only one face, meaning that you have a non-closed output. Obviously this cannot happen for a 3D convex hull, except if you are in a degenerate case and the point set is not 3D. You can use a geometric predicate (CGAL::coplanar() with the points of the edge and the opposite v...
70,547,779
70,552,093
Debug Assertion Failed Expression __acrt_first_block == header
I have been trying to figure out why this is happening and maybe it is just due to inexperience at this point but could really use some help. When I run my code, which is compiled into a DLL using C++20, I get that a debug assertion has failed with the expression being __acrt_first_block == header. I narrowed down wher...
For anyone else who runs into a similar problem, here is how I fixed it. Essentially the function signature for the Init() function was the problem. The std::string parameter was causing the debug assertion to fire, my best guess as of right now was because of move semantics but that part I am still not sure on. So the...
70,547,815
70,547,853
What happens with extra spaces and newlines in C/C++ code?
Is there a difference between; int main(){ return 0; } and int main(){return 0;} and int main(){ return 0; } They will all likely compile to same executable. How does the C/C++ compiler treat the extra spaces and newlines, and if there is a difference between how newlines are treated differently than spaces in C cod...
Any sequence of 1+ whitespace symbol (space/line-break/tab/...) is equivalent to a single space. Exceptions: Whitespace is preserved in string literals. They can't contain line-breaks, except C++ raw literals (R"(...)"). The same applies to file names in #include. Single-line comments (//) are terminated with line-bre...
70,547,875
70,549,816
Strange behaviors of cuda kernel with infinite loop on different NVIDIA GPU
#include <cstdio> __global__ void loop(void) { int smid = -1; if (threadIdx.x == 0) { asm volatile("mov.u32 %0, %%smid;": "=r"(smid)); printf("smid: %d\n", smid); } while (1); } int main() { loop<<<1, 32>>>(); cudaDeviceSynchronize(); return 0; } This is my source code, the...
Why doesn't the system output smid under configuration 1? A safe rule of thumb is that unlike host code, in-kernel printf output will not be printed to the console at the moment the statement is encountered, but at the point of completion of the kernel and device synchronization with the host. This is the actual r...
70,548,248
70,548,329
Calling `.lock()` on weak_ptr returns NULL shared_ptr
I am somewhat confused by the behaviour of the .lock() call on a weak_ptr. My understanding is that .lock() will return a shared_ptr of the relevant type if it has not expired otherwise it will be a null pointer. From https://en.cppreference.com/w/cpp/memory/weak_ptr/lock : A shared_ptr which shares ownership of the ...
Weak pointer attaches only to existing shared pointers, by itself weak pointer doesn't hold or create any object pointer. In other words if you do: std::weak_ptr<int> wp; auto sp = wp.lock(); then it always returns nullptr. You have to pass Existing shared pointer in constructor or through assignment (=), e.g. std::sh...
70,548,260
70,548,300
C++ windows.h - window doesnt open
#include<windows.h> #include<iostream> #include<tchar.h> LRESULT CALLBACK WindowProcedure(HWND, UINT, WPARAM, LPARAM); TCHAR szClassName[ ] = _T("ClassName"); int WINAPI WinMain(HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nCmdShow) { HWND hwnd; MSG messages; WNDCLASSEX wincl...
This statement is wrong: wincl.lpszMenuName = szClassName; It needs to be this instead: wincl.lpszClassName = szClassName; You are not checking if CreateWindowEx() fails (returns NULL): hwnd = CreateWindowEx(...); if (hWnd == NULL) ... // <-- ADD THIS In this situation, it does fail, because you are not registering th...
70,548,510
70,549,071
what is the difference between const char * and const char ()[]
I found this function in some library that I would like to use but I can't figure out out to pass a std::string variable to it ---------- template<int KeyLen> std::vector<unsigned char> key_from_string(const char (*key_str)[KeyLen]) { std::vector<unsigned char> key(KeyLen - 1); memcpy(&key[0], *key_str, Key...
The function in the library only accepts pointers to string literals. Example: std::vector<unsigned char> key = plusaes::key_from_string(&"Foo"); Here KeyLen would be deduced to 4 because the string literal consists of 'F', 'o', 'o', '\0' You supply usr_key.c_str() to the function, which returns a const char*, and tha...
70,549,068
70,549,177
Does creating an object directly in a vector, and then removing it from the vector, calls to a destructor?
Say i have a class named test, and a vector std::vector<test> Tests; If i execute this code: Tests.push_back(test()); and then Tests.pop_back(); What happens to the test object? Is its destructor being called upon?
This example might show a little bit better what happens. Live demo here : https://onlinegdb.com/c6-N-vyPc Output will be : Creating first vector (push_back) >>>> Test constructor called >>>> Test move constructor called <<<< Test destructor called Destroying first vector <<<< Test destructor called Creating second v...
70,549,378
70,550,658
Why we need to add the "ranges" when calculate ha_innobase::read_time?
We see that MySQL needs to add the ranges when calculate the ha_innobase::read_time (/storage/innobase/handler/ha_innobase.cc), my question is why it need it? double ha_innobase::read_time( uint index, /*!< in: key number */ uint ranges, /*!< in: how many ranges */ ha_rows rows) /*!< in: estimated ...
This comment tells you the answer: /* Assume that the read time is proportional to the scan time for all rows + at most one seek per range. */ There is probably a seek for each range, and each seek increases the read time. Seeks were more costly on spinning storage devices, and most sites now use solid-state storage, ...
70,549,518
70,550,109
How to address a typedefed inner class of a class template that itself is a template?
I have a syntactic question rather, With the following iterator class inside of a vector class, #include <memory> #include <cstddef> #include <iterator> namespace ft { template <class T, class Alloc = std::allocator<T> > class vector; } template <class T, class Alloc> class ft::vector { public: typedef ...
For the out-of-line definition, you must unfortunately repeat the entire "signature" of all the nested templates, including constraints, if any. Cigien has given the right form: template <class T, class Alloc> template <class value_type> ft::vector<T, Alloc>::ptr_iterator<value_type>::ptr_iterator() {} Since this can...
70,549,812
70,550,011
Snake Game going too fast console c++
I've been following a few tutorials for making a somewhat Snake Game , just not a full-tailed-one , It's going alright and i think i got it almost right but I've got two problems #include <bits/stdc++.h> #include <conio.h> #include <unistd.h> using namespace std; int side,x,y; int fruitx,fruity,score,flag; bool isOver...
First sleep is a bit rough. See answers here for better solutions: Sleep for milliseconds Second you don't account for your own overhead. Your program might run faster/slower on different setups. For games in general you want to use a somewhat precise but fast time function to get an idea of how much to move everything...
70,549,850
70,549,930
weakly_incrementable constraint while using iota_view
To quickly create a for loop similar to python's for i in range(100), I could do: for (auto const i : std::views::iota(0, 100)) { /* ... */ } However, CLion is warning me to add a std::weakly_incrementable constraint to my auto: for (std::weakly_incrementable auto const i : std::views::iota(0, 100)) { /* ... */ } I k...
Is it possible for it to create something of a totally different type (not even weakly incrementable)? And can I safely ignore the warning? According to the synopsis of iota_view in [range.iota.view]: template<weakly_­incrementable W, semiregular Bound = unreachable_sentinel_t> class iota_view : public view_interface...
70,550,071
70,550,224
How do you convert a `std::string` hex value to an `unsigned char`
sample input a8 49 7f ac 24 77 c3 6e 70 ca 99 ca fc e2 c5 7b This fucntion converts the hex values in the sample to a string to be later converted into an unsigned char std::vector<unsigned char> cipher_as_chars(std::string cipher) { std::vector<unsigned char> hex_char; int j =0 ; for (int i = 0; i < ciph...
As a very simple solution, you can use a istringstream, which allows parsing hex strings: #include <cstdio> #include <iterator> #include <sstream> #include <string> #include <vector> std::vector<unsigned char> cipher_as_chars(std::string const& cipher) { std::istringstream strm{cipher}; strm >> std::hex; ...
70,550,162
70,550,204
Sort words alphabetically but "ch" is more than "h" using qsort with saving it as upper case
I just cant figure out, how to sort a char array (NO VECTOR) of words alphabetically. Because our alphabet has "ch" which is "bigger" than "h", so I need every word starting with "ch" go behind "h". This is mine current code of sorting, but i cant fogure it out, how to add "ch more than h" rule. And im using here "eve...
You'll need to define your own comparison function. [IMPORTANT] Notice this solution only looks at the first character. I.e. "aching" and "advert" will be ordered as ["aching", "advert"], and not as ["advert", "aching"], even when 'ch' should come after 'd'. [Demo] #include <algorithm> // sort #include <iostream> // ...
70,550,535
70,550,585
creating vector using new operator
I have an assignment and the question is "write a function that creates a vector of user-given size M using new operator" Code: #include <iostream> #include <vector> int main() { int user_size; std::cin >> user_size; int *p = new std::vector<int> g5(user_size); delete p; return 0; } pls give me a...
It's unclear, what is meant here by vector. Moreover, the assignment says nothing about the type of the data. If vector is meant to be an array of M then the following int*array = new int[M]; is the appropriate command (here assuming int as data type). In this case, you will need to delete the array later using the de...
70,550,617
70,550,686
Is there a way to make the compiler include functions from outer scopes when picking a candidate?
Consider this class and variadic member function: class foo { public: template<class C, class... Cs> void add(C&& c, Cs&&... cs) { ... add(cs...); } private: void add(){ } }; Is there a way to place the empty add overload that terminates the recursion inside another scope? ...
How about using if constexpr: namespace impl { void add() {} } class foo { public: template<class C, class... Cs> void add(C&& c, Cs&&... cs) { if constexpr (sizeof...(Cs) == 0) impl::add(); else add(cs...); } };
70,550,713
70,551,926
Hash function for a smart pointer class as key for an unordered map
So, I have a pointer wrapper class which stores only a pointer and I need to use this class instance as a key in an unordered map. I currently have a similar setup with this pointer wrapper instances as keys to a std::map by overriding bool operator< but for an unordered map setup I would need to override two other ope...
Since you seem to need a hash function only for using PointerWrappers in an unordered map, the hash function in the standard library should serve you well. (But these are not cryptographically secure hash functions so don't use them for anything else). Here is some code to show how to do this: #include <unordered_map> ...
70,550,907
70,551,347
How would one efficiently reuse code in a specialised template struct?
I am creating my own vector struct for a maths library. Currently, I would create the struct somewhat like this: template <unsigned int size, typename T> struct vector { // array of elements T elements[size]; // ... }; However, the main use case of the maths library will lead to mostly making use of 2-dim...
As correctly noted in comments for another answer, having reference fields is a big pain because you cannot reassign references, hence operator= is not generated automatically. Moreover, you cannot really implement it yourself. Also, on a typical implementation a reference field still occupies some memory even if it po...
70,550,983
70,552,118
http request using sockets on c++
I'm trying to do an HTTP request using sockets on Linux, and my function works now, but only with simple domains as www.google.com or webpage.000webhostapp.com. When I try to add a path and query like webpage.000webhostapp.com/folder/file.php?parameter=value, it starts failing. This is my code: #include <iostream> #inc...
gethostbyname() (which BTW is deprecated, you should be using getaddrinfo() instead) does not work with URLs, only with host names. Given a URL like http://www.exampleweb.com/folder/file.php?parameter=value&parameter2=value2, you need to first break it up into its constituent pieces (read RFC 3986), eg: the scheme htt...
70,551,359
70,552,458
How to print and modify char in C++
I want to create a project that will print the '|' character as 4 layers going 1 3 5 7 something like | ||| ||||| ||||||| I wrote a for loop for this and the code is here: for (int i = 1; i <= 4; i++) { //for loop for displaying space for (int s = i; s < 4; s++) { cout << " "; } //for loo...
Here is a solution: #include <iostream> #include <vector> std::size_t getLayerCount( ) { std::cout << "How many layers to print: "; std::size_t layerCount { }; std::cin >> layerCount; return layerCount; } std::vector< std::vector<char> > generateShape( const std::size_t layerCount ) { const std:...
70,551,378
70,551,577
Calculate integral using rectangle method in Pascal gives 0 while in C++ good results
I'm trying to implement the rectangle method in Pascal. The point is, I'm getting wrong results. I'm getting 0, while the same code in C++ gives me good results. Why is that? Thanks. Pascal: Program HelloWorld(output); function degrees2radians(x: real) : real; var result: real; begin result := x * 3.14159 / 180....
In your Pascal code result is a local variable, which has nothing to do with the special identifier called result that you want to use: function degrees2radians(x: real) : real; var result: real; begin result := x * 3.14159 / 180.0; end; You should remove result: real; in all your functions. However, "fixed" co...
70,551,699
70,551,743
Use of std::move in std::accumulate
In my Fedora 34 environment (g++), std::accumulate is defined as: template<typename ITER, typename T> constexpr inline T accumulate(ITER first, ITER last, T init) { for (; first != last; ++first) init = std::move(init) + *first; // why move ? return init; } If the expression init + *first is already an rval...
std::move(init) + *first can sometimes generate more efficient code than init + *first, because it allows init to be overwritten. However, since (as you observed) the result of the + will generally be an rvalue, there is no need to wrap the entire expression in a second std::move. For example, if you are accumulating s...
70,551,736
70,552,115
Problem in My Merge Sort Implementation C++
I've been learning about the merge sort algorithm, and I am having a bit of trouble. In my implementation, some of the numbers in the output are missing and others are repeated. I'm using vectors and following the algorithm described in Introduction to Algorithms by Cormen et. al. and Geeksforgeeks. Here's the code: #i...
Your merge function assumes that you are sorting with p=0. You should copy from p, not from 0. Then put back with k starting from p: //copy elements over for (int i = p; i < p + numLeft; i++) left.push_back(A[i]); for (int j = mid + 1; j < (mid + 1 + numRight); j++) right.push_back(A[j]); ...
70,551,862
70,552,027
pybind11 c++ unordered_map 10x slower than python dict?
I exposed a c++ unordered_map<string, int> to python, and it turned out this map is 10x slower than python's dict. See code below. // map.cpp file #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <string> #include <unordered_map> namespace py = pybind11; PYBIND11_MAKE_O...
You are comparing a native dictionary implementation (the one from the Python Standard Library) and a pybind wrapped one. I would bet a coin that a C++ program directly using std::unordered_map is certainly faster than the equivalent one, written in Python and using a dict. But it is not what you are doing here. Instea...
70,551,870
70,552,105
How i can utilize S(*)(int)?
For educational reasons, I'm studying the C++ language using clang-12 std=c++17 And I have the following code: Fullcode #include <cstdio> #include <iostream> #include <type_traits> using namespace std; struct S { void operator()(int) {} }; int main() { S(*d)(int); //d = whatValue?? return 0; } I'm studyi...
The variable d is a pointer to a function taking an int as argument and returning an S. Note that it cannot point to non-static member functions. You could, e.g., use it like this: struct S { void operator()(int) {} }; S f(int) { return S(); } int main() { S(*d)(int) = &f; S rc = d(17); } As functions de...
70,551,980
70,552,193
ctypes return array of strings std::vector<std::string>>
I am able to return a string after it is converted to a char*. import ctypes from subprocess import Popen, PIPE # Press the green button in the gutter to run the script. libname = "c:\temp\debug_api_lib.dll" c_lib = ctypes.windll.LoadLibrary(libname) class Gilad(object): def __init__(self, host, port): ...
The function is returning a char**, and you've told Python that it is returning a char*[3] (an array of 3 char* pointers, not a pointer itself), so the returned value isn't being interpreted properly by ctypes. Change the return type to ctypes.POINTER(ctypes.c_char_p), or alternatively change your program to return som...
70,552,086
70,552,228
Fixing bug in removing duplicates from sorted linked list
I'm trying to remove duplicates from a sorted linked list. I have written the algorithm but still missing a core bug logic that I can't trace. Consider the list 1->2->3->3->4->4->5 Output should be 1 - > 2 - > 5 The program works fine for a simple case, like 1>2>2>3, but for multiple duplicates like 1>2>2>3>3>5 it outp...
For starters this constructor Node() { } does not make a sense. Remove it. The statement prevSlow->next = fast->next; in this if statement if (fast->val == slow->val) { prevSlow->next = fast->next; fast = fast->next; slow->next = prevSlow->next; } in general can invoke undefined behavior because initial...
70,552,114
70,552,160
Makefile giving error with No target for rule G++
Complete Makefile noob here. I cannot figure out why this is happening, but I think it is whitespace/tab. I have this Makefile: BUILD_DIR = build/debug CC = g++ SRC_FILES = $(wildcard $(SRC_DIR)/*.cpp) OBJ_NAME = play INCLUDE_PATHS = -Iinclude LIBRARY_PATHS = -Llib COMPILER_FLAGS = -std=c++11 -Wall -O0 -g LINKER_FLAG...
You need to put commands on a new line: all: $(CC) $(COMPILER_FLAGS) $(LINKER_FLAGS) $(INCLUDE_PATHS) $(LIBRARY_PATHS) $(SRC_FILES) -o $(BUILD_DIR)/$(OBJ_NAME) and make sure it is indented with tab, not space It is also not python, it's make You couuld also use a semicolon to separate dependencies from commands li...
70,552,547
70,552,742
g++ boost iostreams zlib linking
I compiled boost iostreams with zlib and bzip2 support according to this tutorial https://www.boost.org/doc/libs/1_49_0/libs/iostreams/doc/installation.html : I changed working directory to ~/cpp_libs/boost_code/boost_1_55_0/libs/iostreams/build/ and typed: bjam -s ZLIB_SOURCE=~/cpp_libs/zlib_code/zlib-1.2.11 -s BZIP2_...
Here's the usual workflow that's used to build and install shared libraries on Linux. The exact details vary widely between different libraries and all packages but they all follow the same general framework: The software package builds an installation image, placing the libraries as <libdir>/<name>.<version>, where <...
70,553,335
70,553,995
VSCode Include path C++
I am trying to learn C++, but I am having trouble. When trying to compile my source file, I receive the below error message for all of my header files. I have tried adding multiple paths to my CPP properties file but am still having trouble identifying the problem. Above is the properties file I previously mentioned....
So as far as I am able to understand, you are trying to run main.cpp that has a user defined header file Book.h But Book.h is in another directory so, try using #include "../headers/Book.h" Basically you need to give the location of Book.h file in respect to main.cpp
70,553,401
70,553,445
Passing new value to a pointer via a recursive function in c++
How I can change the value of p to 1 passing it as an argument to a recursive function. This is my code: class Solution { void g(int n,int k,int *p){ if(k==0) return; if(k%n==0) g(n,k-1,1); cout<<p<< endl; g(n,k-1,p+1); } public: int josephus(int n, int k) { int p=...
The error says you cannot pass an int as a parameter to a function when it expects an int *. There is also a logical bug in your code: g(n,k-1,p+1); This recursive call increments the pointer value, which makes it point past the passed in object, since the function was called like this: { int p=1; ...
70,553,678
70,554,061
Is there a shorter way to calculate if (a == b || a == c) in C++
I am wondering if in c++11 you can calculate this: if (a == b || a == c) { // do something } In a much shorter and more concise way such as something like this: if (a == (b || c)) { // do something } (I know that the above code would not work [it would calculate if b or c and then check if the result is equal...
What you are basically doing is testing if a equals a value in a set. And yes std::set can be used but its slow. This example is a bit slower then hard coding the full expression. But it shows what is being calculated and the righthand side will look like a set/collection. #include <utility> // for std::size_t templat...
70,553,735
70,554,906
How to draw a perfect 3D Spring using Cylinders
I am trying to draw a Spring using only Cylinders. void spring(GLfloat rounds, GLfloat height, GLfloat thickness, GLfloat radius) { glColor3f(1.0, 1.0, 1.0); GLfloat j = 0; for (GLfloat i = 0; i <= rounds * 360; i += 5) { glPushMatrix(); glRotatef(i, 0, 1, 0); glTranslatef(0, j, rad...
A spring is a shape that is curved in 3 dimensions. Cylinders cannot be sticked together perfectly to form a spring. Why don't you create your own mesh with the OpenGL primitives? e.g.: Use a TRINGLESTRIP to wrap a long ribbon around a tube that is bent into a spring: #include <vector> #include <algorithm> void create...
70,554,169
70,554,353
Concept subsumption working for functions, but not for structs
Apologies for potentially wrong title, that is my best guess what is happening. I was learning some basic concepts and tried this: #include <concepts> #include <iostream> #include <memory> template<typename T> concept eight = sizeof(T) == 8; template<typename T> concept basic = std::is_trivial_v<T>; template<typenam...
Overloading template classes wasn't allowed before concepts, and it still not allowed even with concepts. Use partial specialization: template <typename T> requires eight<T> struct ffs {}; template <typename T> requires basic<T> struct ffs<T> {}; Or with the terse syntax: template <eight T> struct ffs {}; template <...
70,554,475
70,554,494
const pointer and pointer to const value as parameter
I have a program like below and expect that: with function void myFunc1 ( const int *x) ==> I cannot change the value of at the memory location that x points to, but can change the memory location that x points to. with function void myFunc2 ( int const *x) ==> I cannot change the location that x points to as it is a...
I don't see the different between having 2 parameters (const int *x) vs (int const *x): That's because int const* and const int* are the same thing. If you want to make the pointer const, you have to put a const on its right, like this: int * const, a constant pointer to (non-constant) integer. Unrelated (is it?) no...
70,554,489
70,554,505
What special member function is used for copy initialization in c++?
I'm testing c++ class initialization. class Point { private: int x,y; public: Point() = delete; Point(int a):x(a), y(0) { std::cout << "Conversion" << std::endl;} Point(const Point&) { std::cout << "Copy constructor" << std::endl;} //Point(const Point&) = delete; Point& operator=(const Poin...
Case I In case 1 the converting constructor is used since you have provided a constructor that can convert an int to Point. This is why this constructor is called converting constructor. Case II From mandatory copy elison Under the following circumstances, the compilers are required to omit the copy and move construct...
70,554,765
70,560,542
Why the breakpoints set in STL are "skipped/ignored" while using LLDB?
My goal is: I want to step into the some line of code of STL istream. So I used custom built "LIBC++13" with "Debug" build type(the command I used are shown at the bottom), so that (I think) I can get a fully debuggable version of STL, and be able to step into everything I want. But I got a problem. Here are my breakpo...
By default, lldb treats functions in the std::: namespace the same way as functions without debug information, and auto-steps back out instead of stopping in the function. For most users, the fact that you have source information for inlined stl functions is more an accident of the implementation than an indication of ...
70,555,169
70,555,206
Unable to read the entire file correctly using fseek() and fread()
I have a file with shader source which i want to read that looks like this: #version 460 core layout(location = 0) in vec2 pos; layout(location = 1) in vec3 color; layout(location = 0) out vec3 fragColor; uniform float rand; out gl_PerVertex { vec4 gl_Position; float gl_PointSize; float gl_ClipDistance[]; }; vo...
The difference between the two sizes is 19 which coincidencally is the number of lines in your shader. My guess is this has something to do with line ending conversations. Open the file as binary and the discrepency should go away.
70,555,320
70,555,925
Store function inputs for threads
Im trying to make a job system with a similar feature as std::thread where you can pass in parameters in a lambda which get captured e.g ( std::thread([&](int index){...} ), 5) ) This is the entire thread class #include <condition_variable> #include <functional> #include <thread> using uint = unsigned int; class Thre...
You have a very funny problem introduced :-) m_Job = m_Jobs.front(); m_Jobs.pop_back(); You always pick the FIRST element to execute, but remove the last one. The result is, that you always execute the first element. I expect, that is not what you want! And as your loop inserts with 0 first, it looks like the var is n...
70,555,805
70,556,547
C++ code don't have errors but not giving output
I am writing code for selection sort in c++. It gives no error when i compile it with the command g++ main.cpp -o main in powershell but when i run the code with ./main, it don't show anything. I tried with hello world program and it worked. I don't know why the selection sort code not working. Here Is the code of Sele...
There are 2 problems in your program. Mistake 1 In Standard 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 constant expression The correct way to write the above would be: const int n = 10; int arr[n]; //CORRECT Mistake 2 You're u...
70,556,008
70,556,098
Newton-Raphson in Pascal, not very good results
I implemented Newton-Raphson metohd in Pascal. It's strange because the same code in C++ gives good results (for 9 it's 3) but in Pascal for 9 it's 3.25, Why so? Pascal: Program NewtonRaphsonIter(output); {$mode objFPC} function newton_raphson_iter(a: real; p: real; eps: real; max_i: integer) : real; var x: real;...
repeat ... until C; loop terminates when the expression C evaluates to true. In your code, after the first iteration abs(x - a / x) > eps is true, so the loop terminates. The termination condition should be inverted: until abs(x - a / x) <= eps; Online demo
70,556,359
70,556,503
Binary Search with Duplicates
I am doing this particular exercise where I have to implement the Binary Search algorithm which returns the index of the first occurence of an element in a sorted array, if it contains duplicates. Since I am primarily working on my algorithmic skills in C++, I am only trying to do it in C++. Here is my code: #include <...
returns the index of the first occurence of an element in a sorted array, Your binary search algorithm requires that the data is sorted before you call it. Example: #include <algorithm> #include <sstream> int main() { std::istringstream in(R"aw(10 1 5 4 4 7 7 7 3 2 2 5 4 7 2 0 6 )aw"); int n; in >> n; ...
70,556,448
70,556,543
in the c++ hacker rank preperation cause, the last index returns 0 when i reverse it. but when i try the code out in visual studio, it works perfectly
HERE IS THE QUESTION I FACED ON HACKERRANK. the hackerrank question HERE IS THE CODE I PRINTED #include <iostream> using namespace std; int main() { int n; int array[n]; int c,x; cin>>n; //inputting the array size n=n+1; int m=n; if(n>=1 && n<=1000 && m>=1 && m<=1000 ) { ...
As mentioned in the comments, array should be initialized with a proper capacity. You should first read the size and then create the array. #include <iostream> using namespace std; int main() { int n; // First read the array size and then create the array. cin>>n; //inputting the array size int array...
70,556,755
70,558,965
Does implicit object creation apply in constant expressions?
#include <memory> int main() { constexpr auto v = [] { std::allocator<char> a; auto x = a.allocate(10); x[2] = 1; auto r = x[2]; a.deallocate(x, 10); return r; }(); return v; } Is the program ill-formed? Clang thinks so, GCC and MSVC don't: https://godbolt.o...
2469. Implicit object creation vs constant expressions It is not intended that implicit object creation, as described in 6.7.2 [intro.object] paragraph 10, should occur during constant expression evaluation, but there is currently no wording prohibiting it.
70,556,808
70,566,628
while loop running for every digit/character from input
Hey guys beginner in C++ and coding in general. I am currently making a tictactoe program. For the part of the program I am validating user input. Since it is a 3x3 table, I want to make sure their input is an integer and that they choose a number between 1~9. To do this I wrote //Validating user input void move() { ...
Let me try to explain to you the problem. It is a little bit subtle and not that easy to understand. Both other answers adress only the obvious part. Then, let us first recap that: The boolean condition in the while statement is loop invariant. Meaning, it will not be modified within the loop. Whatever it was before th...
70,557,046
70,557,114
How to use a switch case inside a for loop?
I'm doing a quiz program in C++ programming language. I have used a for loop to go through each switch case but when I run the program, it's just keep looping the case 0 and can't stop the loop after I answering my quiz. How should I solve it ? #include <iostream> #include <string> using namespace std ; void quiz_coun...
The issue isn't the loop + switch, but the infinite recursion you're using: display_question() calls question() question() calls quiz_count() quiz_count() calls display_question(), so you're back at step 1. The values of i you're observing are simply the values for different calls to the display_question function. Yo...
70,557,232
70,558,941
Trying to get a JSON output from cURLlib in c++
So I'm using cURLlib in C++ so that I can get market data using API's, problem is I'm not able to make head or tails from the documentation given about cURLlib for C++. The API returns a JSON file which I want to parse and take data from to use on my own algorithm. The only solution I see right now is to parse the str...
The only solution I see right now is to parse the string that's returned by cURL That is exactly what you need to do. but I think that seems too lenghty and tacky, so if there's someway I can get a direct output as a JSON file from cURL instead There is no option for that in libcurl. I could use nlohmann and itera...
70,557,681
70,557,779
Makefile: Compile C++ Files recursively
I am new to makefiles and tried reading resources on the internet to solve my problem, yet I am unable to find a solution. Basically I am working on a project which contains C++ and Cuda files. Since I like to keep my things structured, I usually use a nested folder structure like this: |- bin |- build | |- cc | ...
This rule doesn't make sense: $(CC_SRC): @echo compiling $(CC) $(CC_FLAGS) -c $< -o $a (I assume you mean $@ here not $a). This rule says that the way to create each of the source files is by compiling them. But, make doesn't need to build the source files: they already exist. So it never invokes yo...
70,557,696
70,560,263
decrypting cipher results in missing letters
I have a python endpoint that encrypts string using AES cbc mode and returns it to the client software written in c++ (in a hex space separated format ) The link for the c++ repo std::vector<unsigned char> cipher_as_chars(std::string cipher) { std::istringstream strm{cipher}; strm >> std::hex; std::vector...
Look at this example pycrypto does support pkcs#7 padding your take on padding is poor, just use the built-in padding function in that module Example taken from the link from Crypto.Cipher import AES from Crypto.Util.Padding import pad from Crypto.Util.Padding import unpad key=b'1234567890123456' cipher=AES.new(key,AE...
70,558,153
70,558,363
What happens to uninitialized variables in C/C++?
From "C++ Primer" by Lippman, When we define a variable, we should give it an initial value unless we are certain that the initial value will be overwritten before the variable is used for any other purpose. If we cannot guarantee that the variable will be reset before being read, we should initialize it. What happe...
Q.1) What happens if an uninitialized variable is used in say an operation? Will it crash/ will the code fail to compile? Many compilers try to warn you about code that improperly uses the value of an uninitialized variable. Many compilers have an option that says "treat warnings as errors". So depending on the com...
70,558,248
70,558,336
Stop computer beeping when printing the number 7
I'm printing a bunch of ascii chars to the console as a representation of binary numbers however whenever it prints out the number 7 to the console then windows makes a beeping noise. Looking online I can see some people talking about ascii 7 making a noise but I cant seem to find where to disable it in the code. for (...
Code 7 is bell. It is meant to do that. To disable it, you have 2 choices. Change the configuration of the terminal or OS (tell it to be silent). Add a conditional to the code, to skip this character. To do the conditional: use isprint e.g. #include <ctype.h> #include <iostream> int main(){ int c =7; if...
70,558,346
70,565,649
Generate random numbers in a given range with AVX2, faster than SVML _mm256_rem_epu32 remainder?
I'm currently trying to implement an XOR_SHIFT Random Number Generator using AVX2, it's actually quite easy and very fast. However I need to be able to specify a range. This usually requires modulo. This is a major problem for me for 2 reasons: Adding the _mm256_rem_epu32() / _mm256_rem_epi32() SVML function to my co...
If you range is smaller than ~16.7 million, and you don’t need cryptography-grade quality of the distribution, an easy and relatively fast method of narrowing these random numbers is FP32 math. Here’s an example, untested. The function below takes integer vector with random bits, and converts these bits into integer nu...
70,559,377
70,559,567
Qt or Win32 to obtain notification events for Windows or other systems, users manually switch dark/light mode?
Many articles I read are polling the registry and so on. Is there no corresponding notification event that can be obtained by C/C++?
In Win32, have a native top-level window (which can be hidden) on your main UI thread listening for WM_SETTINGCHANGE and WM_SYSCOLORCHANGE messages. When you get either event, repoll for screen resolution and desktop color settings. It's not just light-mode and dark mode you want to monitor for. Also be on the lookout...
70,559,589
70,559,658
What is the best way to copy a std::array passed as a parameter?
I've been working on a game written with C++ and SDL2 in my free time and I'm refining some of my base classes for drawable objects. These objects have a position (x and y) and a size (width and height). It makes more sense to me to store these objects in a fixed size array, so I've been using std::array to contain the...
Either way, by-reference or by-value, is ok. But don't assign individual elements manually. That is exactly what the assignment/constructor of std::array does for you. Whether, in general, constructor arguments which will be copied/moved into the class members should be passed by-value or by-reference is a more complic...
70,559,975
70,560,023
unordered_map elements disappeared after [] operation in c++
The behavior that unodered_map elements disappeared unexpectedly in the following C++ code confused me a whole lot. In the first for loop I stored the remainder of each element in time moduled by 60 and its count in unordered_map<int, int> m, in the second for loop, I printed the content in m, so far everything seems...
The third loop uses the [] operator inside the loop. for (auto [remainder,cnt]:m){ // ... n += m[remainder]*m[60-remainder]; unordered_map's [] invalidates all existing iterators if it results in a rehash. This includes the implicit iterators employed during range iteration. As shown, m[remainder] cannot cause...
70,560,112
70,560,173
Array inside Struct wont copy correctly
Was wondering if anyone could help me with this, I have this struct in my code struct Gate { int output[9]; }; And i had a vector of that struct, but pushing to the vector which normally would create a copy broke because its only a shallow copy, and my struct has an array so I tried to work around this by creating a...
Gate alwaysFirst{{0,0,0,1,1,1,2,2,2}}; Gate alwaysSecond{{0,1,2,0,1,2,0,1,2}}; These lines use aggregate initialization, which is only possible on aggregates, which cannot have user-declared constructors. By declaring a custom copy constructor, your type is not aggregate anymore. You can replace the aggregate initiali...
70,560,136
70,560,197
Creating a thread taking way too long
I'm experimenting with threads. My program is supposed to take a vector and sum it by breaking it down into different sections and creating a thread to sum each section. Currently, my vector has 5 * 10^8 elements, which should be easily handled by my pc. However, the creation of each thread (4 threads in my case) takes...
std::thread(sumPart, v, sz*i, sz*(i+1)) Arguments to thread functions are copied, as part of creating the execution thread. Even though sumPart takes it parameter by value v gets internally copied. copying a vector with 500000000 values will take a little bit of time. You can use std::ref to effectively pass v by r...
70,560,461
70,560,809
Sometimes a good practice to initialize a class pointer member variable to itself?
For a strictly internal class that is not intended to be used as part of an API provided to an external client, is there anything inherently evil with initializing a class pointer member variable to itself rather than NULL or nullptr? Please see the below code for an example. #include <iostream> class Foo { public: ...
It's a bad idea to start with, but a horrendous idea as a solution to null dereferences. You don't hide null dereferences. Ever. Null dereferences are bugs, not errors. When bugs happens, all invariances in your program goes down the toilet and there can be no guarantee for any behaviour. Not allowing a bug to manifest...
70,560,585
70,560,762
GetAsyncKeyState with held CTRL button and another "toggled" button not working as wanted
I got the following code for testing purposes: bool test = false; if (GetAsyncKeyState(VK_LCONTROL) && GetAsyncKeyState(VK_F2) & 1) { test = !test; std::cout << test << std::endl; } Now what I would like to happen is when I hold down the left control and then press F2 that the instructions are being properly h...
GetAsyncKeyState returns multiple things in its return value. The correct way to check if a key is down is: bool lctrldown = GetAsyncKeyState(VK_LCONTROL) < 0; That being said, waiting for a user to press F2 implies polling and polling is bad! If you only care about F2 in your own window then you should use TranslateAc...
70,560,629
70,560,829
std::reference_wrapper, constructor implementation explaination
I have been trying to understand the implementation of std::reference_wrapper, from here, which is as follows: namespace detail { template <class T> constexpr T& FUN(T& t) noexcept { return t; } template <class T> void FUN(T&&) = delete; } template <class T> class reference_wrapper { public: // types typedef T ty...
It's a technique you can use when you want the behaviour of the "forwarding reference", U&& in this case, but at the same time restrict what can bind to it. Deduction of T is aided by the deduction guide provided below. The detail::FUN<T>(std::declval<U>()) is there to ensure that the constructor is disabled when U is ...
70,560,886
70,561,145
Why are my strings not being printed correctly?
I want to write a piece of code to create a list of random potions for D&D 5e from a few given parameter lists. And I was almost done, every bit of code working properly apart from a single line of code. I expect an output of this sort: "The liquid is: Yellow with flecks of colour.". Instead, I get this: " with flecks ...
That could be the problem with line endings. If you created the file in Windows (thus you have "\r\n" line endings) and use this file in Linux, the getline would work differently. It will use '\n' as a delimiter, but will treat '\r' as a separate string. As the result you may get some appearences equal to "\r". At the ...
70,560,927
70,563,402
Print out bitset quickly in c++
Im writing a program that outputs binary, and I got alot of it I want to output to the terminal, but this takes along time. In other places in my program where I want to quickly output strings I use _putchar_nolock and for floating point and decimal numbers I use printf Currently my code looks like this for outputtin...
The problem is that cin and cout try to synchronize themselves with the library's stdio buffers. That's why they are generally slow; you can turn this synchronization off and this will make cout generally much faster. std::ios_base::sync_with_stdio(false);//use this line You can also get an std::string from the bitse...
70,560,964
70,561,257
C++20 concepts using ADL with circular dependency
I'm having a problem with concepts using ADL. edit 1: I mention ADL since the parse functions are supposed to be overloaded with user defined types. The from_string_view_parsable concept doesn't see the parse functions below since ADL doesn't apply to them. The functions would need to be defined or forward declared bef...
You can defer the requires expression to a type trait, which can be forward-declared: #include <sstream> #include <optional> #include <string_view> #include <type_traits> template <typename T> struct is_from_string_view_parsable; template <typename T> concept from_string_view_parsable = is_from_string_view_parsable<T...
70,561,094
70,561,186
Copying objects when passing by value - how many copies do I end up with?
Let me start off by saying that I'm very new to C++ currently - i have previously only really worked with python and javascript (quite a lot of exposure to python) and so, now that I'm learning C++ to expand my knowledge and understanding of lower level programming concepts I wanted to reach out and ask a specific ques...
Your question is a bit unclear since I'm not sure why you'd like to know how many copies are there. Edit your question if you'd like to know more explicit question. I smell XY-problem here. What you need to know is the variable scope. I assume _vChain is a class member or global variable somehere so _vChain will have a...
70,561,150
70,561,225
the function getrandom() only returning -1
I am attempting to get random numbers out of the getrandom() function however attempting to use it only returns -1 the code i am using below: #include<iostream> #include <sys/random.h> int main(){ void* d = NULL; ssize_t size = 10; ssize_t p = getrandom(d, size, GRND_RANDOM); std::cout << p << std::endl...
getrandom returns the number of bytes written. The first argument is the pointer to a byte buffer (to be filled with random bytes), the second argument is the number of random bytes that you want to be written to the buffer. Your return value (p) being -1 means that there was an error when writing the random bytes to ...
70,561,671
70,561,733
Return a python function from Python C-API
I am currently in the process of writing a small python module using the Python API, that will speed up some of the slower python code, that is repeatedly run in a in a simulation of sorts. My issue is that currently this code is takes a bunch of arguments, that in many use cases won't change. For example the function ...
I would seriously consider using swig instead of pybind11 for example. It's just peace of mind. If you don't want to use swig directly, you can at least see what swig does to wrap up features like proxy objects. http://www.swig.org/Doc2.0/SWIGPlus.html#SWIGPlus_nn38
70,562,001
70,562,392
Get return type of current function in C++
This question is similar to Get return type of function in macro (C++) but it is 10 Years old and is not answered. Any other solution would be accepted. I want to create an assert macro that only returns from the function if the condition isn't met, Like: #define ASSERT(X) if(!(X)) return {}; This doesn't work if the ...
This is possible using __PRETTY_FUNCTION__ (GCC, Clang) /__FUNCSIG__ (MSVC), a non-standard extension that gives you the name of the current function, including the return type. You can analyze the string at compile-time to see if it has void in it or not: #include <string_view> struct AnyType { template <typename...
70,562,112
70,562,186
Static Multiplication of Vector Using C++, Program not working
I have got this assignment but this program is not working and output is not getting properly. This program compiles successfully, but it gives error - Segmentation fault (core dumpped). I am not getting why this is happening. Please tell me what is the problem in the below code - #include<iostream> using names...
Vector(const int *a) does not initialize Vector::V, replace it with Vector(const int *a, int size) : Vector(size) but you will have to replace V1 = x; V2 = y; with V1 = Vector(x,3); V2 = Vector(y,3); This code will result in a memory leak btw.
70,563,158
70,569,226
Concept that requires a function to return another concept by value or reference
I'm learning C++ concepts. Now I can write a concept that requires the presence of a function which returns something that satisfies an other concept, but so far only by value (in function getB()). Function getC() gives an error because: because 'decltype(t.getC())' (aka 'const float &') does not satisfy 'floating_poin...
You could define a new concept that accepts floating point references, like so: template<typename T> concept FloatingPointReference = std::is_reference_v<T> && std::floating_point<std::remove_reference_t<T>>; Or if you don't care whether it returns by value or by reference you could check whether the decayed type adhe...
70,563,305
72,189,396
Strange unicode error when converting Chinese wide strings to regular strings in C++
Some of my Chinese software users noticed a strange C++ exception being thrown when my C++ code for Windows tried to list all running processes: 在多字节的目标代码页中,没有此 Unicode 字符可以映射到的字符。 Translated to English this roughly means: There are no characters to which this Unicode character can be mapped in the multi-byte target...
I managed to test on a Chinese machine and it turns out that converting a file path from wide string to a regular string will produce a bad file path output if the file path contains e.g. Chinese (non-ASCII) symbols. I could fix this bug by replacing calls to wide_string_to_string() with std::filesystem::path(wide_stri...
70,563,507
70,563,685
Should I delete pointer from `new` passed to a function which makes into a `shared_ptr`?
In the following code example: #include <iostream> class Foo{ }; class Bar{ public: void addFoo(Foo *foo){ auto my_foo = std::shared_ptr<Foo>(foo); } }; int main() { auto bar = Bar(); bar.addFoo(new Foo()); return 0; } Do I need to clean up the pointer created in main() by the bar.addFoo...
The very idea of a constructor taking a raw pointer is to pass the ownership to std::shared_ptr. So, no, you don't have to delete a raw pointer passed to std::shared_ptr. Doing this will lead to a double deletions, which is UB. Note that in general passing a raw pointer is dangerous. Consider the following more general...
70,563,532
70,563,970
Custom slider control in MFC (visual studio)
I am making a slider control in visual studio in MFC, I want to set the range from 14 to 100 and step size should be 0.25 as 14.25, 14.50, 14.75 . How can can make an custom slider control?
A CSliderCtrl wraps a trackbar control. As such, the former shares the same limitations with the latter. Specifically, the range is set through the TBM_SETRANGE message (or the TBM_SETRANGEMIN and TBM_SETRANGEMAX messages). Either message takes an integral value, so you cannot have the control operate on fractional val...
70,564,069
70,569,134
constexpr causes a GCC warning when used with string literal
The below code compiles: #include <iostream> int main( ) { const char* const str = "This is a constant string."; std::cout << str << '\n'; } However, this one gives a warning: constexpr char* const str = "This is a constant string."; Here: warning: ISO C++ forbids converting a string constant to 'char*...
Whether or not you are using constexpr here is not the issue. You are trying to store a string literal in a char* const which is not a pointer to immutable data (which the string literal is), but rather a pointer with a constant address. A string literal can be stored as const char* or const char* const instead. const ...
70,564,215
70,565,569
C++ custom-written strncpy without padding all characters to null is it safe?
#include <iostream> using namespace std; struct Packet { int a; char b[17]; int c; }; // char* dest has form char dest[n], src has length <= n and is null-terminated // After the function, dest should satisfy: // - If strlen(src)==n, dest is not null terminated // - If strlen(src) < n, dest[n-1] = dest[st...
Is this version of strncpy safe? Yes. It's as safe as strncpy is. So.... not safe. Are there any C/C++ functions that requires strncpy to fill all leftover bytes with '\0', or do they only need a null terminator? No function require it. Notes from Linux man-pages man strcpy: NOTES Some programmers consider strnc...
70,564,304
70,564,394
Global variable priority over local variable when global function called in scope of local variable c++
I just wanted to clarify a gap in my knowledge. Given the following code: I would have expected that "Hi" is printed, based purely on the fact that in the scope of foo, the definition of FuncA is overwritten and hence should be called. This does not happen as shown here https://onlinegdb.com/LzPbpFN3R Could someone ple...
As soon as you call a free function, you are no longer inside the class. And you have lost the special this pointer. A (rather C-ish) way could be: void FuncB(struct Foo* a) { // expect a pointer to a Foo object a->FuncA(); // call the method on the passed object } struct Foo { void FuncA() { ...
70,564,799
70,564,966
howt to automate reading input sample test case in c++
I'm coding Dijkstra algorithm and want to take a lot of test cases and no manual input allowed , I have two main files map.txt and routes.txt , i wanna take numbers as pairs , as shown in photossample test cases
You can redirect the input to stdin as follows: freopen("filepath.txt", "permission", stdin); filepath: It is usually the name of the given input file (usually, in contests, the name is problem-name.txt. permission: It is usually r or w. r means read which is used with input and w means write which is used with outp...
70,565,183
70,565,268
Friend function have no access to struct member declared in class template
Here is the situation: template <class T> class A { struct S { /* some data */ } S some_member; public: /* some methods */ friend bool B (S); }; bool B (S s) { //<-- ERROR "S was not declared in this scope" /* do something */ } What should I do, to have the program compiled correctly?...
While writing the function B's parameter you have to be in the scope of the class template A<> and, also specify "some type" like int(or float etc) as shown below: bool B (A<int>::S s) { //<-- Added change here return true; } You can use other types as well i have given example for int. Also, you will nee...
70,565,699
70,566,473
Is there a SFINAE-template to check if a class has no functions of any kind?
I want to check if a given class has only the following: Non-static data members Constructor(s) (default or user-defined) Destructor (default or user-defined) This type would be (at least visually declaration-wise) identical to a POD-type apart from the user-defined constructor and destructor. I've tried to find a te...
No, there's no such method. Consider the following: struct A { }; struct B { void UniqueFunctionName9814(); }; No SFINAE method can distinguish these, because you can't enumerate member function names, nor can you predict random function names. Hence B::UniqueFunctionName9814 can't be detected, and apart from B::Uniqu...
70,566,084
70,568,173
How to pass reference type to std::hash
I am creating a Template Cache library in C++-11 where I want to hash the keys. I want to use default std::hash for primitive/pre-defined types like int, std::string, etc. and user-defined hash functions for user-defined types. My code currently looks like this: template<typename Key, typename Value> class Cache { ...
In this call you provide the constructor of std::hash<Key> with key: return std::hash<Key>(key); You want to use it's member function, size_t operator()(const Key&) const;: return std::hash<Key>{}(key); Some notes: Hashing and caching are used to provide fast lookup and having a std::function object for this may slo...
70,566,097
70,773,835
How to plot gsl_vector in C++?
Is there a convenient way or a library to plot gsl_vector in C++? For example, if I have two gsl vectors, I would like to plot one on the x-axis and the other on the y-axis for the same figure.
After some research, I got to know that it is not directly possible to plot gsl_vector in C++. However, I coded a workaround (almost like the one suggested by bitmask) using gnuplot, which solved my problem. Therefore, I am posting an answer to my own question. Following is my solution: #include <stdio.h> #include <gsl...
70,566,233
70,566,337
Get projected value from std::ranges algorithms
I am using algorithms from std::ranges (max and max_element) with a projection. Is it possible for the result to also be the projected value? Currently I have to call the projection function again on the returned value. Example: Here I want the size of the longest string, but the algorithms return only the string or an...
You're using an algorithm (max/max_element) on the original range, which can't do anything but give you an element/iterator into the range. If you want just the projected values, do the projection (via a views::transform) to get the lengths first, and then find the maximum of that auto const lens = std::views::transfor...
70,566,491
70,567,232
How to bump the C++ standard from the CMake command line?
Currently I have a project that needs C++17, therefore in the CMakeLists.txt I have this line pretty early on: set(CMAKE_CXX_STANDARD 17) From the command line (cmake) once in a while I want to test that the project also compiles with C++20. (to avoid surprises). How can I choose to compile with C++20 from command lin...
The solution is to remove that set command and use target properties instead: # set(CMAKE_CXX_STANDARD 17) target_compile_features(myexecutable PUBLIC cxx_std_17) Then, setting -DCMAKE_CXX_STANDARD=20 on the terminal should work again.
70,566,615
70,566,692
c++ string template no matching function for call to basic_string<char>
I am writing common function to convert type T to string: when T is numeric type just use std::to_string when others use stringstream operator << when T is std::string just return T template <typename Numeric> string to_str1(Numeric n){ return std::to_string(n); } template <typename NonNumeric> std::string to...
When you write if(std::is_integral<T>::value){ return to_str1(t); }else{ return to_str2(t); } Then it is true that the if condition is either always true or always false at runtime, but it is still required that the two branches can be compiled. The first branch however doesn't work with T = std::string. If yo...