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
69,765,484
69,766,659
Parallel sieve of eratosthenes produces wrong output based on number of threads
This is the approach I'm using for parallelization: p = Process ID, N = total number of processes, n = input size Each process is assigned n/N numbers, ranging from index p*n/N to (p+1)*n/N-1. When process 0 finds a prime number, all its multiples are marked in parallel. Finally, each process counts the number of prim...
I figured it out. It had nothing to do with parallel execution, I just had a calculation error when computing the bounds. This is the correct formula for computing lower bound: #define LOWER_BOUND(p, N, n) p == 0 ? 2 : p * (n / N) Notice the paranthesis around n/n.
69,765,682
69,765,729
Successor of INT_MAX and INT_MIN
I have 2 questions, Is 1e9 less than INT_MAX value from the header file climits? Is -1e9 greater than INT_MIN value from the header file climits? and if I need to use in my program, some big positive number or smallest negative number, I use INT_MAX or INT_MIN in general but when there's some constraints in some cases ...
Is 1e9 less than INT_MAX value from the header file climits? It can be. It isn't necessarily. It depends on the target system. Is -1e9 greater than INT_MIN value from the header file climits? Same as above. Since int isn't guaranteed to be sufficient, you should use at least long type, or the more specific aliases ...
69,766,412
69,766,538
How to ensure template parameter is non-const and non-reference
Often (most of the time?) when creating types with template type parameters you want to ensure the type parameter is filled in with a non-reference, unqualified (non-const, non-volatile) type. However, a simple definition like the following lets the user fill in any type for T: template <typename T> class MyContainer {...
I'd use a concept for this. template <typename T> concept cvref_unqualified = std::is_same_v<std::remove_cvref_t<T>, T>; template <cvref_unqualified T> class MyContainer {...};
69,766,466
69,870,171
Cython: Import definitions from .pyx file
I have 1 Cython .pxd file and 1 Cython .pyx file, the pyx file contains a cdef class: # myclass.pyx (compiled to myclass.so) cdef class myclass: pass Now is the .pxd file of another feature # another.pxd (with another.pyx along) from libcpp.vector cimport vector import myclass # This line is funny, change 'myclass'...
It should be clearly described this way: myclass.pyx is compiled into .so file But there are 2 kinds of stuff in a .so file Python definitions: Can be imported only with 'import' Cython definitions: Can be imported only with 'cimport' The problem is import myclass in another.pxd won't import myclass because it is ...
69,766,887
69,767,011
Declaration of class inside header file without initialization
I want to declarate a class object of Class B inside of Class A in a header file, like: // test.h class A { public: B b; }; but lets say B has no default Constructor and the required parameters are not known yet (in header file). Which possibilities in c++ exist to declarate a class instance in another class...
Your example lacks any declaration of B, so you will get a compiler error. You must either add or include B's declaration, or you will need to forward declare it, e.g. class B; class A { public: B b; // Compiler error }; However, this will still not work, since A needs to know the space to set aside for B. You m...
69,767,069
69,767,144
Forwarding a function to std::thread via a lambda expression
I'm working through the notes here to understand an example async function implementation. Attempting to compile the below code #include <future> #include <iostream> #include <thread> #include <chrono> #include <ctime> #include <type_traits> int f(int x) { auto start = std::chrono::system_clock::now(); std::t...
To get result type of result_of you have to access type: std::promise< typename std::result_of<Function(Args...)>::type > outer_promise;
69,767,320
69,767,405
std::array and std::tuple in memory order
I'm testing a small code fragment and I'm surprised the same representation of 4 bytes as put into std::array and std::tuple yield different in-memory layouts #include <iostream> #include <tuple> #include <array> struct XYZW { uint32_t x; uint32_t y; //std::array<uint8_t,4> z; std::tuple<uint8_t, uint8_t, uint...
std::array has a layout specified by the standard, but std::tuple does not, and can be anything the implementation wants. So it's expected that they may differ, but of course they may also happen to choose the same layout, on some compilers/versions/platforms - there's just no guarantee. In practice one of the easiest ...
69,767,789
69,775,621
RichEdit doesn't show pictures
I created a simple RTF-document in WordPad, here is the screenshot: It seems, that all format things of RTF work properly except pictures, which replaced by empty string. Here is RichEdit screenshot: I tried both .bmp and .png. I also tried different version of RichEdit libraries: Riched20.dll and Msftedit.dll. Insid...
To insert a bitmap in to richedit, see this example (InsertObject(HWND hRichEdit, LPCTSTR pszFileName)) Otherwise, the bitmap in WordPad's rtf files is save as numbers in decimal format. To read that, IRichEditOleCallback interface is needed. Create a new file called "cole_callback.h" as follows: #include <richole.h> ...
69,768,913
69,771,855
Does using different Boost versions affect serialization and deserialization?
I'm working on some project in C++ where I'm using Boost for binary serialization and deserialization. Serialization feature is already present with Boost version 1.61 I made my whole deserialization add on feature using Boost version 1.77 and now I'm facing problem while reading binary files. So, my question is how do...
There is backwards compatibility. But it requires the archive headers to be present so the library can detect the version support required for de-serialization. Without the header, there's no way to tell, so the library must assume it's the most current version. Removing that should work, see it live: save in 1.61.0: ...
69,769,335
69,850,267
Targetting Windows 8.1 with Windows 10 SDK in C++
we currently build our C++ Code with Visual Studio 2017 and we were required to have our binaries run on Windows 7 as well until only recently. Hence our settings in C++ projects for the Windows SDK version to be used is "8.1" and by defining _WIN32_WINNT=0x601 as a preprocessor macro, we target Windows 7 as a platform...
The comment from Minxin Yu is the answer to this question. This discussion points to the Windows SDK page that clearly states that the current Win10 SDK allows for targetting Windows 7 SP1 and Windows 8.1.
69,769,487
69,770,632
c++ replace values in linked list by changing pointers
Having a problem with linked list. Need to create a method, which will replace data in list, by not creating a new element but by changing pointers. For now I have such method: void replaceValues(Node* head, int indexOne, int indexTwo) { Node* temporaryOne = NULL; Node* temporaryTwo = NULL; Node* temp ...
I assume that with "replace" you actually mean "swap"/"exchange". Some issues: The argument head should be passed by reference, as one of the nodes to swap may actually be that head node, and then head should refer to the other node after the function has done its job. The node before temporaryOne will need its next ...
69,769,489
69,769,674
C++: read int from binaryfile
I have pixels from an image which are stored in a binary file. I would like to use a function to quickly read this file. For the moment I have this: std::vector<int> _data; std::ifstream file(_rgbFile.string(), std::ios_base::binary); while (!file.eof()) { char singleByte[1]; file.read(singleByte, 1); ...
You could make this faster by reading the whole file in one go, and preallocating the necessary storage in the vector beforehand: std::ifstream file(_rgbFile.string(), std::ios_base::binary); std::streampos posStart = file.tellg(); file.seekg(0, std::ios::end); std::streampos posEnd = file.tellg(); file.seekg(posStart)...
69,769,633
69,771,522
C++ Sorting Algorithm Returns in the Quintillions When Given 0
I'm trying to write my first sorting algorithm in C++, I'm relatively new to it so this might be an endeavor beyond me but I thought I could handle it. When given the input 0 this code returns numbers such as 701635989630, 6560204700, and 1.8*10^19. This doesn't make sense to me at all, nor the people I have asked IRL....
C++ Sorting Algorithm Returns in the Quintillions When Given 0 Sorting algorithms sort things. They don't, as a rule, return integers. uint64_t descendingOrder(uint64_t a) This is a function that does three things: convert an integer into an array of digits sort the array of digits convert the sorted array of digit...
69,769,750
69,769,879
How can I determine, if a templated class is a sublass of another templated class, as the templates might differ?
Consider the following class structure: template <typename TType> struct Base {public: virtual ~Base() {} }; template <typename TType> struct Child : Base<TType> {}; template <template<typename> class Node, typename TType> bool type(Node <TType>* node){ return dynamic_cast<Base<TType>*>(node) == nullptr; } int ma...
You might use overload: template <typename T> constexpr std::true_type IsBaseT(const Base<T>*) { return {}; } constexpr std::false_type IsBaseT(const void*) { return {}; } Demo That assumes accessible, non ambiguous base. And result is based on static type. So you can turn that into a traits: template <typename T> st...
69,769,815
69,769,950
How XOR Assignment operator ^= is utilized to reverse an array in c
i encountered to this function void reverseArray(int *a,int n) { for(int i=0,j=n-1;i<j;i++,j--) { a[i]^=a[j]^=a[i]^=a[j]; } } which is reversing a given array but I can't wrap my mind around how does this reverse an array, isn't Xor operator only returns the non-common bits. so what's the logic behind this to reverse ...
The purpose of the expression a^=b^=a^=b is to exchange the values of a and b. It becomes more clear if we split it up (where a_0 and b_0 are the original values of a and b): First assignment, a^=b makes a_1=(a_0^b_0). Second assignment, b^=a makes b_1=(b_0^a_1)=(b_0^(a_0^b_0))=a_0 Third assignment, a^=b makes a_2=(a_...
69,770,000
69,781,346
Count of binary numbers from 1 to n
I want to find the number of numbers between 1 and n that are valid numbers in base two (binary). 1 ≤ n ≤ 10^9 For example, suppose n is equal to 101. Input: n = 101 In this case, the answer is 5 Output: 1, 10, 11, 100, 101 -> 5 Another example Input: n = 13 Output: 1, 10, 11 -> 3 Here is my code... #include <iostre...
Details: In each step, if the digit was one, then we add 2 to the power of the number of digits we have. If the number was greater than 1, then all cases are possible for that number of digits, and we can also count that digit itself and change the answer altogether (-1 is because we do not want to calculate the 0). #i...
69,770,785
69,770,898
How to cycle through smart pointer to a class with custom iterator
I have a smart pointer to a class with custom iterator. I need to iterate through it and couldn't find any examples. struct SomeContrainer { int a; } struct ListClass { std::vector<SomeContrainer>::iterator begin() { return m_devs.begin(); } std::vector<SomeContrainer>::iterator end() { return m_devs.end();...
you need to dereference it void DoSomeWorkOtherList( const ListPtr_t& list ) // void(const unique_ptr<ListClass>&) { for( auto const & dev : *list ) // <-- how to iterate other list ??? {} } Not necessary for the code in question, but you probably also want to provide const version of begin and end. std::vector...
69,770,834
69,770,999
Is it possible to call Class member constructor inside class constructor?
I would like to be able to initialize a class member in one of N ways (in this examples N=2) based on a condition that is recieved via the class constructor as in the code that follows, but the MainObject's initialization seems to be only local to the (container) class' constructor. I wonder what are the best-practices...
I am interpreting the question as "how to perform non-trivial logic before/during the member initialization list". A good way to go about that is to delegate the work of converting the constructor parameter of the outer object into the child object to a utility function: // in ContainerObject.cpp #include <stdexcept> ...
69,770,854
69,772,106
Redefining a handle ptr of void* to handle ptr to struct* (C/C++ mixcode) for access
I have C/C++ mix code and want to pass around a struct that contains a reference to a class. Because of this, I can't declare this struct in the header file of the C++ component (because class is defined in source file of C++ component) but only in the source file. The main script in C however has to reference that str...
The usual way to do this is to use an undefined struct. In its most basic form: void foo(struct the_config_struct *arg); // OK even though 'struct the_config_struct' wasn't defined! // surprisingly this is also allowed in C++ You can also make a typedef: typedef struct the_config_struct *config_handle_t; void foo(conf...
69,771,109
69,771,250
C++ Reverse Array of std::vector of two elements
I would like to ask how can I fastly, without copying of elements reverse the array, that will always consists only from 2 std::vectors. The CGAL_Polyline is also a vector that contains points. Currently I am doing reverse like this (works for now but I do not know if this is a correct way): std::vector<CGAL_Polyline> ...
Use std::swap: std::vector<CGAL_Polyline> m[2]; ... std::swap(m[0], m[1]); This will move the contents of the vectors without copying (C++11 and later. Before that it's allowed to copy). If pre-C++11 (and if that's the case upgrade your compiler!) you can use std::vector::swap: std::vector<CGAL_Polyline> m[2]; ... m[0...
69,771,112
69,771,644
Factory for a template class with enum template parameter
Suppose I have enum class Colour { red, blue, orange }; class PencilBase { public: virtual void paint() = 0; }; template <Colour c> class Pencil : public PencilBase { void paint() override { // use c } }; Now I want to have some factory function to create painters PencilBase* createColourPencil(Col...
Firstly, you need to know how many colors are there: enum class Colour { red, blue, orange, _count, // <-- }; After you know the number, you can create an array of function pointers of this size, each function creating the respective class. Then you use the enum as an index into the array, and call the...
69,771,416
69,771,502
Is it safe to cast a class to a derived class that just adds additional functions?
I have a class that contains a lot a data. Depending on the situation I need to output this data in different ways. I want the output routines for each of those situations separated and I want to keep the base class clean of that. Is it absolutely safe to cast to a derived class that does NOT add any data members but j...
No, this isn't safe. The behaviour of the program is undefined. Static casting to a derived type is safe only when the dynamic type of the object is that derived type (or a further derived type).
69,771,634
69,772,235
IEEE 754 Addition of two 32-bit floating point numbers (-1 and 2^(-50) )
Consider the following piece of C++ Code: #include <iostream> #include <cmath> using namespace std; int main() { cout.precision(1000000000); float a,b,c; a = 1; b = -1; c = pow(2, -50); cout << "a = " << a << endl; cout << "b = " << b << endl; cout << "c = " << c << endl...
The IEEE 754 standard specifies 1 sign bit, 7 exponent bits and 24 bits for the mantissa. When performing addition, the mantissas of each number get normalized, so 2^-50 is 1 shifted right by 50 bits relative to 1. This causes it to fall outside of the 24 bit mantissa used for the result. You should try repeating your ...
69,771,907
69,775,848
c++ create a global unique id that is not a UUID type
In other languages, such as Go, there are a myriad of libraries that can be used to create a globally unique ID string (using elements such as nanosecond time, machine id, process id, random bytes...) However, in C++, the only real choice seems to be UUID (such as that from Boost) I am looking to use a globally unique ...
Please note that when I say "as many chars", I am referring to the string representation of a UUID So, perhaps use your own representation. You didn't specify a whole lot. Keep in mind that time-clustering might lead to security vulnerabilities¹. I'd assume UUIDv4 standard, meaning 16 bytes. Let's use the encoding fr...
69,772,243
69,773,170
How i can get all substring of size k of string?
I don't know where is the error in my code ? can someone help me to fix it . My code : #include<bits/stdc++.h> using namespace std; #define ll long long void solution() { string s; ll k; cin >> s >> k; for(int i=0; i<=s.length()-k; i++) { for(int r=k-1; r<s.length(); r++){ cout << s.substr...
I have no idea why you need a nested for loop. Why isn't this just simply: void solution() { string s; ll k; cin >> s >> k; for(int i = 0; i <= s.length() - k; i++) { cout << s.substr(i, k) << endl; } }
69,772,513
69,772,650
C++ what happens when 0 is assigned to class variable in constructor
I'm trying to create a smart pointer and stumbled over the code below. Since I'm pretty new to C++, its syntax is yet something I have to get used to. Below you can see the most important part of the code where RC is the reference counter class with a member variable called count (of type int). The function addRef incr...
For historical reasons, 0 is equivalent to nullptr, which means "a pointer that does not point to anything". In modern code, you should always use nullptr, never 0. Is this the way to go or are there "better" best practices? Putting aside concerns about what is being executed, the most idiomatic way to write the same...
69,772,624
69,773,221
Next higher number with same number of set bits and some bits fixed
I'm trying to find a way to, given a number of bits that need to be set, and a few indexes of bits that should remain fixed, generate the next higher number with the same number of set bits, that has all the fixed bits in place. This is closely related to https://www.chessprogramming.org/Traversing_Subsets_of_a_Set#Sno...
Solution 1 (based on "Snoobing the Universe") One solution is to define a value corresponding to the "fixed bits" and one corresponding to the "variable bits". E.g. for bits {2, 5, 6}, the "fixed bits" value would be 0x64 (assuming bits are counted starting from 0). The "variable bits" is initialized with the smallest ...
69,772,694
69,772,726
Why is the output "0x7ffffcf9a010"?
#include <iostream> #include <string> using namespace std; int main() { string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"}; cars[0] = "Opel"; cout << cars; return 0; } Why is it returning 0x7ffffcf9a010 when I output it?
Yes, it will output that, the strange number you see is the address of the starting of the first element of the array, cars is implicitly converted to a pointer. By itself, it's an array rather than a pointer. You want to do this, #include <iostream> #include <string> using namespace std; int main() { string cars[...
69,772,803
69,772,873
Why do i need to give input twice in order for the code to run
I am writing a simple bit of code to get a piece of text outputted a certain amount of times accoring to user input, however when running in terminal, i need to type in the number twice (so e.g. : 5 [enter] 5 [enter], then the text would be output 5 times). Just wondering why this is and how to fix this, many thanks. #...
You read into x two times, so you need to enter it twice. You can fix this by removing one of the cin >> x's. e.g.: #include <iostream> using namespace std; int main() { int x; int i; cout << "How many times do you want me to say [London Town], Numbers only" << end; while (true) { cin >> x; ...
69,772,900
69,773,187
How do I replace spaces with std::regex_replace between markers using non-capture groups?
I'm trying to eliminate whitespaces in a string with a regular expression. From the following snippet: std::string in = "abc> <def\n" "xyz> \n"; std::regex re = R"((?:>)\s+(?:<)|\s+$)"; std::string out = std::regex_replace(in, re, "(newcontent)"); I'm expecting out to contain abc>(newcontent)<de...
If the > and < are captured, they can be written back. This way there are no assertion compatibility issues. (>)\s+(<)|\s+$ replace $1(newcontent)$2 https://regex101.com/r/dOjUlw/1
69,773,453
69,773,563
Template operator() specialization for a special type?
I have a Vector class that is template based. I have a unit conversion template that is based on Scott Meyers Dimensional Analysis in C++. I'm not going to list it as it is complex, unless the problem can't be solved without those details. I'm using the casting operator for when I need to pass the data to outside funct...
if constexpr to the rescue. operator Point3D() { if constexpr (std::is_same_v<std::remove_cvref_t<T>,Unit>){ return Point3D(x.as<T>(),y.as<T>(),z.as<T>()); }else{ return Point3D(x,y,z); } }
69,773,594
69,775,201
C++ combine maps of enums
Let's imagine I have some class hierarchy for a game. Like this: PhysicalObject is parent of BaseUnit is parent of BaseArcher and so on... And each hierarchy level adds its own stats. Any PhysicalObject - has speed and size. Any BaseUnit - hit points. I want it to be used as enums, so: enum class PhysicalObjectStats { ...
I don't see the point of map and enum whereas regular member seems to do the job: struct PhysicalObject { int speed = 0; int size = 0; }; struct BaseUnitStats : PhysicalObject { // or composition: // physicalObject PhysicalObject; int hitpoints = 0; }; For your StatsHolder class: template<class StatsEnum> ...
69,773,745
69,773,857
LDFLAGS not read in Makevars.win when building an Rcpp package
Short and sweet: I'm writing an Rcpp package that uses zlib and sqlite. In the following Makevars.win file, I set Compiler flags and try to set some targets. PKG_CPPFLAGS=-I. -I./lib/sqlite/ -fopenmp -march=native -g -O2 -msse2 -fstack-protector -mfpmath=sse\ -DRSQLITE_USE_BUNDLED_SQLITE \ -DS...
There are a lot of things going on there we need to decompose. First off, you managed to have SHLIB use your enumerated list of object files. Good! I recently had to the same and I used a OBJECTS list. I think you may get lucky if you stick the -fstack-protector into PKG_LIBS because the PKG_* variables are there for...
69,774,068
69,774,122
Why use thread_local inside functions?
I thought functions are thread safe if they don't modify non-local data. My assumption is correct according to this answer. But, recently I came across this code, int intRand(const int & min, const int & max) { static thread_local std::mt19937 generator; std::uniform_int_distribution<int> distribution(min,max);...
The random number generators of the standard library (including the std::mt19937 used in the example) may not be used unsequenced in multiple threads. thread_local guarantees that each thread has their own generator which makes it possible to call the function unsequenced from multiple threads. I thought functions are...
69,774,178
69,774,875
Boost process open process in new window (Windows)
I'm trying to design a program that uses workers processes - which are just a different program written in C++. I start a worker process like so: auto worker = boost::process::child("./worker.exe"); worker->detach(); The issue is, is that the worker processes are outputting information to the same command line window ...
ITNOA As you can see in Boost::process hide console on windows, you can create new mode for creating process. CreateProcessA function system call, Show yourself to how to create new process with new console, by helping creation flags: CREATE_NEW_CONSOLE (thanks to Using multiple console windows for output) you can writ...
69,774,751
69,779,226
Cppcheck ignores -i and checks all files after clean build
My project has pretty complex structure. It looks something like this: App/ Inc/ Src/ OtherDir/ ManyOtherDirsInc/ ManyOtherDirsSrc/ OtherDirs/ThatAre/Inside/OtherDirs/Inc build/ I am building it using CMake with extra compile_commands.json. In order to run CppCheck I am using VsCode task that runs this ...
The problem was that .h files where still checked, despite -i flag. Solution: --supress-lists=suppressions.txt suppressions.txt *:/home/Projects/Full/Path/* Important note! path in suppressions MUST be full, relative doesn't work for some reason. It is kinda problematic for a project with multiple devs. Some script t...
69,775,181
69,775,715
How can a unqualified-id contain a unqualified-name in a function call?
In C++ draft ISO(N4901/2021) 6.5.4 (Argument-dependent name lookup) we have: When the postfix-expression in a function call (7.6.1.3) is an unqualified-id, and unqualified lookup (6.5.3) for the name in the unqualified-id does not find any (1.1) — declaration of a class member, or (1.2) — function declaration inhabiti...
I can't figure out a example of an unqualified-id that contains a unqualified name(with the two being different). The wording doesn't say «unqualified name». And seem to miss the word «component» before «name». Here is an example: namespace N { struct S { }; template<typename> void f(S); } void g() { ...
69,775,319
69,775,373
c++ char array to char pointer in struct
I have a struct containing a char pointer and I have a char array containing data. I would like to have the data within the char array copied to the char pointer. I have tried strcpy and strncpy but I get a seg fault on both, when trying to copy the data over. I cant figure out what I am doing wrong. struct struct Mess...
You first need to allocate memory to copy your data. Or use strdup that will do it for you
69,775,383
69,775,445
C++ Forwarding on variadic values which are not rvalue references
Consider: template <typename... Args> void foo(Args... args) { bar(std::forward<Args>(args)...); } template <typename... Args> void foo2(Args&&... args) { bar(std::forward<Args>(args)...); } I understand the perfect rvalue references forwarding in case of foo2, but what is the purpose of forwarding the variad...
It's not the same thing. In this template <typename... Args> void foo(Args... args) { bar(std::forward<Args>(args)...); } Args will never be deduced to be a reference (foo(Args...) means foo's taking the arguments by value, not by reference); on the other hand std::forward<T>(t) is nothing more than static_cast<T...
69,775,421
69,775,634
no operator "<<" matches these operands recursive tower of hanoi error
I'm new to c++ and working on a recursive towers of hanoi project. I have it completely done except for one small error. The second << in "cout << "Number of moves " << count; is giving me the error "no operator "<<" matches these operands". I understand it has something to do with count, but I am uncertain on how to f...
The variable count is defined local to the function toh, so you can return the count value which can be assigned to a variable called count inside main, allowing you to use it in the line cout << "Number of moves " << count;. It should look like this: #include <stdlib.h> #include <time.h> #include <iostream> #include ...
69,775,849
69,776,619
how to group many radio buttons into 3 groups in C++?
My goal is to create 5 groups of radio buttons (i know it contradict with the title but you still get the point) for user choice using only Win32 API (so no window form here). I tried using a combination of groupbox and SetWindowLongPtr but it still not working as expected (note that im using GWLP_WNDPROC as the index)...
Make sure you handle WM_DESTROY otherwise window won't close properly. The radio buttons, all child dialog items, and all child windows should be created in WM_CREATE section of parent window. They need the HWND handle from parent window. SetWindowLongPtr(.. GWLP_WNDPROC ...) is an old method used for subclassing. Your...
69,775,973
69,776,755
Why cout<<++i + ar[++i]; and cout<<ar[++i]+ ++i; give different output?
I have read about undefined behaviour. This Link says a[i] = a[i++] leads to undefined behaviour. But I don't understand why the output of int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int i = 0; cout << arr[++i] + ++i << " " << i; is 3 2 and the output of int arr[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int i = 0; c...
Firstly - a[i] = a[i++] is well-defined since C++17. The sequencing rules were considerably tightened in that revision of the Standard, and the evalution of the right-hand side of an assignment operator is sequenced before the evaluation of the left hand side, meaning that all side-effects of the right-hand side must b...
69,775,993
69,776,254
ncurses how to use setcchar function
Currently using WSL2, C++20, -lpanelw -lncursesw, #define NCURSES_WIDECHAR 1, #include <panel.h>. I'm trying to figure out how to create cchar_t types using the setcchar() function. The function requires a location to store the cchar_t struct specified in the parameter const cchar_t *wcval. I couldn't find any tutorial...
I was able to solve this problem through this approach: cchar_t ptr; setcchar(&ptr, L"", 0, 0, nullptr);
69,776,246
69,801,624
vs code is throwing #include error on macOS monterey it worked fine on BigSur
I updated to macOS monterey yesterday and my vs code is not compiling any code since then. It is throwing these errors : #include errors detected. Please update your includePath. Squiggles are disabled for this translation unit (/Users/ishudhariwal/contest.cpp). cannot open source file "endian.h" (dependency of "iost...
Try installing Xcode Command-line Tools. Most probably this will solve the issue. Try the following. Go to https://developer.apple.com/download/all/ Login or sign up Look for: "Command Line Tools for Xcode 13.x" in the list of downloads then click the dmg and download. Install it.
69,776,250
69,776,276
heap corruption when free() struct pointer after memcpy
I'm writing a generic sorting function with C using Visual Studio 2019. I made an generic insertion sort function with prototype: void insertion_sort(void* const arr, size_t left, size_t right, size_t width, _Cmpfun cmp) where _Cmpfunc is typedef as typedef int (*_Cmpfun) (const void*, const void*); To test this func...
width = sizeof(ELEMENT) sizeof(ELEMENT), using back-of-the-envelope calculations, should be be in the neighborhood of about 30 bytes. That's how big your ELEMENT is. char* top_ptr = (char*)malloc(sizeof(width)); Since width is a size_t, sizeof(size_t) will be either 4 or 8, depending upon whether you're compiling 32 ...
69,776,441
69,776,483
comparing one array element with the next element to find what is the biggest element
I'm trying to find a way to iterating while comparing the element with the next element to find what is the biggest element in the array. But, the output i want keep repeating as much as the loop run. int main(){ int array[4]; for ( int i = 0; i < 4; i++){ cin >> array[i]; } for (int i:array){ ...
You can use the following program to find the biggest element in the array. Note that there is no need to use two for loops as you did in your code snippet. #include <iostream> int main() { int array[4] = {1,10, 13, 2}; int arraySize = sizeof(array)/sizeof(int);//note that you can also use std::size() wit...
69,776,623
69,776,693
How to link to libraries downloaded with Homebrew in Visual Studio Code?
I just downloaded GTKMM using Homebrew but I don't know how to link to it with Visual Studio Code. I have a c_cpp_properties file as well as a tasks.json (Both C/C++ settings files) that I can use to link to files with. Do I link to the downloaded package directly (opt/Homebrew/Cellar/gtkmm) or do I need to link it to ...
You may install pkg-config and it will make the life of a developer sweeter: brew install pkg-config pkg-config --cflags --libs gtkmm The last command shows the required compiler and linker flags for using gtkmm.
69,776,674
69,776,982
USB Barcode Scanner with C++ Console Program
I know this isn't exactly a programming question, but it is related: I'd like to know if USB barcode scanners can scan a barcode and type the results as if it was a keyboard. The reason for this is that I would like to make a C++ console application that will take the input of the scanner using cin or getline, but that...
All the barcode scanners I've dealt with have emulated a keyboard. (In fact, a more common question seems to be how to distinguish scanner input from keyboard input. For example, see How do I tell if keyboard input is coming from a barcode scanner?) Having the scanner add <ENTER> to the end of the barcode is a common c...
69,776,915
69,777,189
the sum of 1 + a + a^2 + _ _ _ + a^n
here is my code: #include <iostream> using namespace std; int main() { int s = 1, i, n, m; double a; cin >> a >> n; while (n <= 0) { cin >> n; } m = a; for (i = 1; i <= n; i++) { s += m; m *= a; } cout << s << endl; return 0; } here was the start...
m *= a;. m is an int type, while a is a double type #include <iostream> // using namespace std; is bad, so don't use it int main() { // there's no need to declare a variable but leave it uninitialized. double a{}; int n{}; std::cin >> a; while (n <= 0) { std::cin >> n; std::cin...
69,777,007
69,777,081
How to concurrently send data to multiple servers using C++ socket programming?
I deployed one program onto several servers (suppose the server IPs and the ports providing the service are 192.168.1.101:10001, 192.168.1.102:10001, 192.168.1.103:10001, 192.168.1.104:10001). They are all listening requests using the Linux socket apis and can finish the task independently. Now, I want to concurrently ...
Not sure this is the only problem, but given what you shared, the main thread is not waiting for the worker threads to finish their tasks. Per this answer: When the main thread exits, do other threads also exit?, the process will be terminated when the main thread returns from main(). Proposed fix: int main() { // ...
69,777,418
69,777,419
How to deal with 'Template' and 'Docstring' simultaneously in C++
What is the standard order of writing a class definition with associated template and docstring, to make it recognisable by the IDEs ? Is it: <docstring> <template> <class declaration/ definition> Or: <template> <docstring> <class declaration/ definition>
The standard way of ordering template and docstring is as follows: Docstring Template Class declaration / definition Example: /** * Class of Traveling Salesman Problem : Ctor :- * @param nov: order of Graph (|V|) * @param startVertex: Starting Vertex for Hamiltonian Traversal * @param costMatrix (optional): accepts...
69,777,430
69,777,462
How do you declare functions with predefined arguments?
I want to know how do u declare a function with definite arguments. It's said to be good practice to put the function declaration at the beginning , before the main() function and then its definition, but in this case the compiler gives me an error, becase it's like if it doesn't see the formal arguments. #include <ios...
here is the way to initialise the function args to default values. You dont need to pass default args in defination. They should be given only in the declaration itself. #include <iostream> using namespace std; void function(int i=1, char a='A', float val=45.7); int main() { function(); return 0; } void function...
69,777,653
69,777,906
OpenCV FAST Algorithm creating skewed keypoints on only part of an image
I'm trying to use OpenCV's FAST corner detection algorithm to get an outline of an image of a ball (Not my final project, I'm using it as a simple example). For some reason, it only works on a third of the input Mat, and stretches the Keypoints across the image. I'm not sure as to what could be going wrong here to make...
Most keypoint detectors use grayscale images as input. If you interpret the memory of a bgr image as grayscale, you will have 3 times the number of pixels. Y axis is still ok if the algorithm uses the width-offset per row, which most algorithms do (because this is useful when subimaging or padding is used). I don't kno...
69,777,742
69,777,894
How can I delete a binary tree with O(1) additional memory?
I was wondering if it's possible to delete a binary tree with O(1) additional memory, without using recursion or stacks. I have managed to write the naive, recursive postorder traversal solution (which uses stack memory): void deleteTreeRec(Node *root) { if (root == NULL) return; deleteTreeRec(root->left); del...
During the deletion the existing nodes of the binary tree can be used as a singly linked list: The nodes always using the left "link" is seen as the linked list. To delete all nodes you simply repeat the following steps: find the tail of the "linked list" if right is non-null, move it to the end of the "list" store th...
69,778,634
70,109,507
SFML blending mode to interpolate colors with alpha
Assume I have a C_1 = (255, 0, 0, 127) filled sf::Texture and a sf::RenderTexture filled with C_2 = (0, 0, 0, 0). Then I call render_texture.draw(texture); The result given by sf::BlendAlpha is a texture filled with (127, 0, 0, 127), but my goal (for the small graphics editor app I'm writing) is blending those two co...
The solution I ended up with: writing your own blend mode with glsl and using shaders. This way you can create and formulas without the need to think about how to bring it to sfml, because it already supports shaders, that can be easily passed to any draw call.
69,778,684
69,779,046
How can I resolve this one or more multiply defined symbol found error?
What is the bug in the following project? main.cpp #include "template_specialization_conflict_test.hpp" int main() { std::cout << utils::my_template_function(0.555); std::cout<<utils::my_template_function<double>(0.555); return 0; } template_specialization_conflict_test.hpp #ifndef UTILS__UTILS__UTILS__UT...
How can I fix this? You could solve this by adding/using the keyword inline for the specialization so the specialization would look like: //note the keyword inline in the below specialization template <> inline double my_template_function<double>(double parameter) { std::cout << "function specia...
69,779,369
69,782,699
c++ smart pointer c'tor design explaination
When I read the code: DefaultSPStorage() : pointee_(Default()) {} DefaultSPStorage(const DefaultSPStorage&) : pointee_(nullptr) {} template<class U> DefaultSPStorage(const DefaultSPStorage<U>) : pointee_(nullptr) {} explicit DefaultSPStorage(const StoredType& p) : pointee_(p) {} I feel confused ...
DefaultSPStorage() is a template class, eg: template<typename T> class DefaultSPStorage { ... }; The third templated constructor takes a DefaultSPStorage<U> instance whose template parameter can be different than the DefaultSPStorage instance that is being constructed. IOW, this allows constructing a DefaultSPStor...
69,779,958
69,780,016
How does cin read strings into an object of string class?
Reading some documentation online I found that istream class was part of C++ long before the string class was added. So the istream design recognizes basic C++ types such as double and int, but it is ignorant of the string type. Therefore, there are istream class methods for processing double and int and other basic ty...
This is possible with the use operator overloading. As shown in the below example, you can create your own class and overload operator>> and operator<<. #include <iostream> class Number { //overload operator<< so that we can use std::cout<< friend std::ostream& operator<<(std::ostream &os, const Number& n...
69,780,791
69,781,135
How to store values in the boost multi_array container?
I'm struggling to access the values and store them in boost multi_array container. I've tried to access the elements using the indexing methods ([] and .at()), but throws error: no matching function for call to 'boost::multi_array<float, 2>::data(int)', however I can print the data (see the code) but do not have any id...
You can choose. Store it? array_2d_t frame = read_frame(filename, 1); Access an element? // access individual elements: float ele = frame[0][3]; // or with index list: std::array<int, 2> indices{0,3}; ele = frame(indices); Or, as you seem to want, provide a flat view of the array: boost::multi_array_ref<float, 1> s...
69,780,970
69,781,122
Cant's pass a 2D array to a function in C++
I was following internet tutorials on this topic, but I have the following situation: I have a function with the following signature: void func(long& rows, long& columns, int array[][columns]); and I'm trying to use the function like this: int matrix[5][4] = {0, -1, 2, -3, 4, -5, 6, -7, ...
Have you actually defined func in your program? The following source code compiles and works fine for me #include <iostream> #define ROW 5 #define COLUMN 4 void func(long &rows, long &columns, int array[][COLUMN]); int main() { int matrix[ROW][COLUMN] = {0, -1, 2, -3, 4, -5, 6, -7, ...
69,781,174
69,782,479
Using the value _T("") and CString variables
This might sounds simple but I want to know if one way is actually more efficient. Example one: CString strName = _T(""); CString strName = CString(); Example two: if (strFilterText == _T("")) if (strFilterText.IsEmpty()) Is there any negative impact is using _T("") in this way? And if so, why?
CString has different constructors and operator overloads, it is prepared for different scenarios. It's a complicated class but in general, such classes work like this: Use default constructor CString() (initializes for _T("")): CString s1 = CString(); CString s2; //same as above, shortcut CString ...
69,781,565
69,781,616
In template<class It> function where It is an iterator, can I make It::value_type work for both vector::iterators and array::iterators?
I have been writing some functions that take a template called It, which should be an iterator. Then I use the It::value_type for some functionality. This has been working for most containers I have tried but fails for std::array. If I do use an std::array I get the error error: ‘long unsigned int*’ is not a class, str...
Use iterator_traits template <class It> void print_accumulate(It first, It last) { typename std::iterator_traits<It>::value_type result{}; // use iterator_traits while (first != last) { result += *first; ++first; } std::cout << result << "\n"; }
69,783,060
69,783,115
Getting a warning when I use a class within a class in C++
#include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; class Course{ public: string name; int pars[]; Course(); }; class Runs{ public: Course course; <- Error int scores[]; Runs(); }; I am trying to use the classes to read lines from a badly formatted fi...
int pars[]; This is not a valid C++ class member declaration. In standard C++ the sizes of all arrays must be defined at compile-time as a constant, fixed size. Your compiler implements a non-standard C++ language extension that allows this class member declaration in order to use it in a particular way. However you c...
69,783,203
69,786,586
Examples of when PUBLIC/PRIVATE/INTERFACE should be used in cmake
I was reading about the cmake keywords PUBLIC, PRIVATE, INTERFACE and came across this paragraph here in the cmake docs. Generally, a dependency should be specified in a use of target_link_libraries() with the PRIVATE keyword if it is used by only the implementation of a library, and not in the header files. If a depe...
Let's first deal with PUBLIC and PRIVATE: Let's say you're writing a tool with a Qt GUI. You this GUI is supposed to allow you to dynamically add elements to the GUI using plugins. Furthermore the user should be able to activate and deactivate the plugins via settings and the same plugins need to be activated on future...
69,783,463
69,783,499
OpenCV Both RANSAC and LMeDS making an essential matrix of size 0
I was trying to use the findEssentialMat function to produce an essential matrix and kept getting an empty matrix, even with very low probability and high threshold values. I made reproduceable code that tries to compute the essential matrix from a still image, and I still get no essential matrix. I'm not sure why this...
It looks like the findEssentialMat function does not work with a focal length of 0, setting it to 1 fixed the issue!
69,783,903
69,783,972
How to calculate the average score in struct function of C++?
This is the question that I was aasigned. https://i.stack.imgur.com/efRFk.png And this is my coding. This is my first time asking question here so I dont really know how to paste my coding here. https://i.stack.imgur.com/QCOBG.png I really hope someone can help me out. Thank you.
You can use the below shown program as a starting point(reference). In your program you were creating an ordinary(nonmember) double named average while according to the assignment average should be a data member as shown below. Second, there is no need to create a separate variable called sum because you can use variab...
69,784,052
69,784,273
How to implement a variable multidimensional array using int** array = new int*[n];?
I tried this approach but I am getting error when I cout <<vararr[i][j]<<endl; The problem I am trying to solve- hackerrank my code- #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int* variablesizedarr(int size){ int* arr= new int [size]; for...
Thanks to @nathanpearson I was able to find the error in int* variablesizedarr(int size){ int* arr= new int [size]; for(int i=1;i<size;i++){ cin >>arr[i]; } /*I believe the problem is when I return the arr array*/ return arr; } Here the initialization of i should be 0, not 1. I know it...
69,784,441
69,784,456
Why dereferencing is not required in pointer array?
In the code that is written below, when reading from cin, we should use the * operator before arr[i]. But without that, this code works perfectly. Why is that? Similarly, we don't use * when we write to cout with pointer arrays. For instance, consider a multi-dimensional pointer array on the heap - cout << vararr[i][j]...
we should use the * operator before arr[i] No, that'd be an error. From cppreference: The built-in subscript expression E1[E2] is exactly identical to the expression *(E1 + E2)except evaluation order (since C++17), that is, the pointer operand (which may be a result of array-to-pointer conversion, and which must poi...
69,784,664
69,784,673
Remove format specifiers from printf
I want to use printf to output a text. If I want to print a text which has previously entered by the user and may contain a %, the output is a garbled mess. This is propably due to % being a format specifier in printf, but no value/argument is given. For example: std::string inputString = "% Test"; printf(inputString....
prints always takes a format string as the first parameter. You cannot change that. However, you can use it to specify that it should just print a string passed as the second argument as is. std::string inputString = "% Test"; printf("%s", inputString.c_str()); Note that, while there is no restriction of what char arr...
69,784,861
69,784,909
If a string is an array of char, how do you convert it into an array of interger
I kept getting an error with this loop. If there are something i missed, please help. Thank You! int main(){ string hasil; int cod[5]; hasil = "99999"; for(int i = 0; i < 5; i++){ cod[i] = stoi(hasil[i]); } for(int i = 0; i < 5; i++){ cout << cod[i] + 1; }
std::stoi() takes a std::string, not a char. But std::string does not have a constructor that takes only a single char, which is why your code fails to compile. Try one of these alternatives instead: cod[i] = stoi(string(1, hasil[i])); cod[i] = stoi(string(&hasil[i], 1)); string s; s = hasil[i]; cod[i] = stoi(s); ch...
69,785,049
69,786,799
Errors from valgrind (Treap)
Valgrind throws errors in this program when implementing the Treap data structure. Can't figure out how to fix this. Tried to write a destructor, nothing changed. The rest of the code is not included for simplicity. The error is in this part of the code. #include <iostream> #include <fstream> using namespace std; ifst...
Explicit use of operator new and delete (or new[] and delete[]) is consider a bad practice (since C++11 is in use). It is recommended to use RAII pattern. In your case everything can be handled by use of std;:vector. class decTree { private: int treeSize; std::vector<vertex> vertexs; std::vector<pvertex>...
69,785,393
69,785,665
Recursion Function over a Range of Inputs
A newbie learning C++ here. Im currently practicing the concept of calling a recursive function between a range of inputs by utilizing a for loop and am running into a "segmentation fault : 11" error. The attempted code and the error Im facing is posted below. Now I know this error is most likely is a result of me not ...
The posted math formula is basically g(2 * x) = F(g(x)) It can be rewritten as g(x) = F(g( x / 2 )) So, to fix recFunc, you have to: Evaluate g at x/2. This is the recursive call to recFunc, but with x / 2 as argument. Assign the returned value to variable, like val. Return F(val). Meaning, apply the posted formu...
69,785,567
69,785,632
Why is a qualified name required after the second level of inheritance?
I ran into a problem, that I somehow managed to solve, but still would like to understand the language and the reasoning behind it. I have the following system of three classes: File class_a.hpp #pragma once class A { public: A(); }; File class_b.hpp #pragma once #include "class_a.hpp" class B : A { public: ...
Among other things that are inherited, there are injected-class-names. You can think of them as of hidden type aliases: class A has something like using A = A; in it, pointing to itself. And remember that class inheritance is private by default. Since B inherits from A privately, C can't access the contents of A, which...
69,786,470
69,786,523
How to get frequency of std:vectors in C++?
I have 5 vectors. I want to check how many times these vectors exist. I used the following code to compare if 2 vectors are equal, but now I have more than 2 vectors. I want to compare all these 5 vectors together and count how many times each vector exists. How can I do it? The output should be: (0,0,1,2,3,0,0,0) = 2 ...
You can use std::map counting the number of occurences of each vector: #include <map> #include <vector> #include <iostream> using vec = std::vector<int>; int main(){ vec v1={0,0,1,2,3,0,0,0}; vec v2={0,0,1,2,3,4,0,0}; vec v3={0,0,2,4,3,0,0,0}; vec v4={0,0,1,2,3,0,0,0}; vec v5={0,0,6,2,3,5,6,0}; ...
69,786,627
69,789,266
Get the last token out of wchar_t*
I have a wchar_t* in my C code, that contains URL in the following format: https://example.com/test/...../abcde12345 I want to split it by the slashes, and get only the last token (in that example, I want to get a new wchar_t* that contains "abcde12345"). How can I do it? Thank you?
In C, you can use wcsrchr to find the last occurence of /: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <wchar.h> int main(void){ wchar_t *some_string = L"abc/def/ghi"; wchar_t *last_token = NULL; wchar_t *temp = wcsrchr(some_string, L'/'); if(temp){ temp++; last_token = malloc((...
69,786,633
69,786,995
How to colorize console background with COLOREF RGB code?
Here I ask you : How are we supposed to colorize the console background with only the COLOREF datatype as a parameter? The most common way of colorizing background is by using windows header function system("color --") However, this way is not possible, and I am tasked to find out if we can colorize the console backgro...
[NEW ANSWER (edit)] So @IInspectable pointed out the the console now supports 24-bit full rgb colors so i did some research and managed to make it work. This is how i solved it: #include <Windows.h> #include <string> struct Color { int r; int g; int b; }; void SetBackgroundColor(const Color& aColor) { ...
69,786,737
69,786,982
Confused why FD_SET crashes with a large value like 536872413?
there is a crash stack in iOS14.2 (arm64): * thread #1245, queue = 'com.xxx.xxx.sdt (QOS: UNSPECIFIED)', stop reason = EXC_BAD_ACCESS (code=1, address=0x175ce5548) frame #0: 0x000000010bac2548 XXXApp`RecvWithinTime(int, char*, unsigned long, sockaddr*, unsigned int*, unsigned int, unsigned int) [inlined] __darwin_fd_s...
Given the additional information, you cannot call FD_SET with an invalid file descriptor. -1 is not a valid file descriptor (no open file will ever have that value). An fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with a value of fd that is negative or is equal to or larger than FD_SETSIZE will result...
69,787,525
69,788,188
How to insert multiple variables inside c++ std::system()?
I'm trying to add multiple variables inside the std::system function. By using .c_str on the end it only accepts one variable. system(("riverctl map normal " + modkey + " " + i + " set-focused-tags " + decimal).c_str);
This code "riverctl map normal " + modkey calls operator+ on two things: "riverctl map normal " and modkey. Which operator+ this is depends on the types of the two operands of +. You want it to call operator+ which concatenates strings; if any of the two first operands is a string (std::string), the first + will do th...
69,787,557
69,788,799
Time complexity of 3 nested loops with a condition
What is the time complexity (big O) of this function ? and how to calculate it ? I think it's O(N^3) but am not sure. int DAA(int n){ int i, j, k, x = 0; for(i=1; i <= n; i++){ for(j=1; j <= i*i; j++){ if(j % i == 0){ for(k=1; k <= j; k++){ x += 10; ...
The complexity is O(n^4) But not because you blindly drop unused iteration. it's because when you consider all instruction, O(n + n^3 + n^4) = O(n^4) int DAA(int n){ int x = 0; for(int i=1; i <= n; i++) // O(n) for(int j=1; j <= i*i; j++) // O(1+2+...n^2) = O(n^3) if(j % i == 0) // O(n^3) same as l...
69,787,566
69,787,911
Making a factorial program faster?
I've been trying to submit this to a website with programming lessons, but the judge keeps telling me that this program takes too long to execute :/ Problem Statement: Write a program that reads a non-negative integer n from the standard input, will count the digit of tens and the digit of ones in the decimal notation...
Since only the last 2 digits of n! are needed, any n >= 10** will have a n! with 00 as the last 2 digits. A short-cut is to test n: This takes the problem from O(n) to O(1). int factorial = 0; if (n < 10) { int factorial = 1; for(int j=n; j>1; j--) { factorial *= j; } factorial %= 100; ...
69,787,667
70,036,610
Is generating unique ID from template template parameters UB?
I am trying to generate unique IDs from template template parameters. I tried this function inline size_t g_id = 1; template<template<typename> typename T> inline size_t GetID() { static size_t id = g_id++; return id; } it works fine until used with alias templates template<template<typename> typename T> inli...
There is no UB here. The template GetID is instantiated once for each unique template argument, but GCC wrongly treats the alias templates as the template they alias itself, because they are equivalent here, as Davis Herring pointed out. I think the simplest general solution is to pass the argument types in the alias t...
69,787,816
69,789,047
Why is std::ifstream closing by itself?
I'm reading an ascii file this way:name1|name2|name3|name4|name5|name6|name7||||||||||name8|||name9 It consists in a bunch of names separated by the '|' char, some of the slots are empty. I'm using the following code to read the list of names: #include <iostream> #include <fstream> #include <vector> #include <string> ...
The expression strerror(File.rdstate()) is not meaningful. The expression File.rdstate() returns an integer which represents the bits of the state flags of the stream. This is not an error code. However, the function strerror expects an error code. Therefore, calling strerror(errno) or perror(nullptr) may be more meani...
69,788,364
69,788,494
C++ algorithm to sum contiguous blocks of integers
Given a block size N and a vector of integers of length k * N which can be viewed as k blocks of N integers, I want to create a new vector of length k whose elements are the sums of the blocks of the original vector. E.g. block size 2, vector {1,2,3,4,5,6} would give a result of {3,7,11}. E.g. block size 3, vector {0,0...
If you can use the range-v3 library, you could write the function like this: namespace rv = ranges::views; namespace rs = ranges; auto sum_blocks(int block_size, std::vector<int> const & input) { return input | rv::chunk(block_size) | rv::transform([](auto const & block) { return rs:...
69,788,990
69,789,104
How to add a myOwn-background image to QPlainTextEdit?
For example, if you create a simple plaintextedit, the background is just white. How do I change white background with my own image?
In design edit, you can set the styleSheet in properties of QWidget. In c++ code you can set the background using QSS, for example, setting ‍‍‍‍background-image: URL("path/image.png");: myWidget->setStyleSheet("background-image: URL('path/image.png')");
69,789,272
69,789,388
Why is the code after my for loop being ignored?
I don't think you'll need to know the context of the problem to answer this question, but I'll give it just in case. -In the past N weeks, we've measured the amount of rainfall every day, and noted it down for each day of the week. Return the number of the first week of the two week period where there were the most da...
The second loop has an overflow. You first defined v[weeks] and then the second loop goes from [0, weeks[ but you are retrieving the next week with v[i + 1]. I don't know exactly what are you are trying to achieve, but if you do for(int i = 0; i < weeks - 1; i++) { ... } it executes properly.
69,789,570
69,793,968
WebAssembly: thread-safety and C/C++ local variables
I'm trying to understand the WebAssembly memory model, specially from the perspective of: what kind of risks I'm exposed to when sharing linear memory between WebAssembly instances? The basic memory model that all C/C++ => wasm tutorials gives us is as follow (the stack starts as __heap_base - 1 and grows downwards): +...
In a multi-threaded setup, each thread will get its own stack into the shared memory. The stack pointer (the creation of it seems to be done by LLVM createSyntheticSymbols) is placed into a WebAssembly global variable. Currently these globals are used as a thread-local storage. That means that each thread has its own g...
69,789,646
69,789,827
Generic task wrapper
Let's say this is how I dispatch a task to the gui thread: void DispatchToGuiThread(std::function<void(void)> task); I want a generic GUIDispatchedTask class that turns this: // foo takes some arguments and must be run in the gui thread auto guiDispatchedTask = [] (A a, B b, C c, D d) { DispatchToGuiThread( [a ...
You can also do it with generic lambda. template<typename F> auto GUIDispatchedTask(F f){ return [=](auto&&... args){ DispatchToGuiThread([=]{f(args...);}); }; }
69,789,768
69,790,452
atmega328 ctc mode timer
So i wanted to make a timer on the atmega328p µC using the CTC Modus. The idea was, that every 10milliseconds when the interrupt function is called , in that function i schould increase a variable millisekunden by 10. and once it reaches 1000 it schould be printed out . The datasheet can be found here: https://ww1.micr...
You forgot to globally enable interrupts. Add sei() at the end of setup()
69,789,787
69,789,916
gdb catch throw, this thread
My binary (generated from C++) has two threads. When I care about exceptions, I care about exceptions thrown in one of them (the worker) but not the other. Is there a way to tell gdb only to pay attention to one of the threads when using catch throw? The gdb manual (texinfo document) and googling suggest to me that t...
Is there a way to tell gdb only to pay attention to one of the threads The catch throw is really just a fancy way to set a breakpoint on __cxxabiv1::__cxa_throw (or similar), and you can make a breakpoint conditional on thread number, achieving the equivalent result. Example: #include <pthread.h> #include <unistd.h> ...
69,790,128
69,790,207
Unknown type name error when inserting into unordered_map
I have a single file called main.cpp where I am trying to declare an unordered_map as shown below. std::unordered_map<std::string, std::set<int>> firstSets; I then try to insert a new (key, value) pair into the map as follows. std::string decl = "decl"; std::set<int> declFirstSet = {VOID_TOK, INT_TOK, FLOAT_TOK, BOOL_...
Your std::make_pair is wrong. To get closer you need a std::set<int> instead of the std::set. But what you really want is to just let to compiler make it for you: firstSets.insert(std::make_pair(decl, declFirstSet)); or use an easier syntax: firstSets[decl] = declFirstSet; EDIT AFTER UNDERSTANDING THE PROBLEM...
69,790,315
69,790,423
Passing class member object - SFML draw()
It seems like a very weird situation. I just want to draw a sf::Text object that is handle outside the main loop (in another class). I show you only the essential. This code works (it draws other things that are handle directly in the main) and so it compiles. Main : int main() { //we handle the creation of the window...
This TextManager textManager(); //My class that don't work... is function declaration, not construction of object. Should be: TextManager textManager; //My class that don't work... By sf::Text myText("Not drawn on the screen :-(",font); you define a local variable called myText the same as your data member. So,...
69,791,065
69,791,686
Constrainted auto std::convertible_to with initializer list
Hello stackoverflow people, I'm recently trying to learn c++20 constrainted auto as function parameters to reduce the boiler plate code. I have a class template that is a wrapper for some data types, like std::int64_t, bool, double, std::string, will probably add more in the future, and it has a function that takes the...
Your problem is C++ is deducing data_t using both 1st and 2nd arguments. If they disagree, no cookie. template<typename data_t> void bind(Wrapper<data_t>& a_data, std::type_identity_t<std::initializer_list<data_t>> a_valueList) this blocks deduction in 2nd argument.
69,791,500
69,794,346
How to convert float to fixed point (higher precision) in C++
I'm trying to implement my own fixed point arithmatic in C++ to (later) do higher precision calculations. I was thinking something like class FixedPoint { int intPart; unsigned long long fracPart[some number]; } I think it should work if I - for example for addition - first add two fracPart[some number]'s and if they ...
Forget decimal. Use powers of 2. Your first fractional part should contain bits with the value 2^-1, 2^-2, ... 2^-64. The nice thing about floating point is that you can easily scale your values by powers of two. In other words, subtract the integer part, then multiply with 2^64, then take the next integer part, and so...
69,791,947
72,644,910
How to set environment variables in CMake so that they can be visible at build time?
On macOS 12, I tried to set some environment variables in CMakeLists.txt file like this. # Add environment variables set(ENV{VK_ICD_FILENAMES} /Users/username/VulkanSDK/macOS/share/vulkan/icd.d/MoltenVK_icd.json) set(ENV{VK_LAYER_PATH} /Users/username/VulkanSDK/macOS/share/vulkan/explicit_layer.d) But I quickly realiz...
Maybe what you want is CMAKE_XCODE_ATTRIBUTE_<an-attribute> https://cmake.org/cmake/help/latest/variable/CMAKE_XCODE_ATTRIBUTE_an-attribute.html
69,792,027
69,844,128
CMake, Qt6 - module "QtQuick.Controls" is not installed
I'm currently working on learning QtQuick, and I've been running into a variety of issues, but this is the first one I've been unable to solve so far. For background, I'm using MVSC, Visual Studio 2019, CMake, and Qt6. ​ Upon running my very basic program, I'm getting the error module "QtQuick.Controls" is not installe...
Qml files should not be linked in the qt_add_executable. In Qt6, use qt_add_qml_module(nameHere URI gui VERSION 1.0 QML_FILES gui/main.qml) See the documentation here: https://doc-snapshots.qt.io/qt6-dev/qt-add-qml-module.html
69,792,059
69,792,420
WS_EX_LAYERED with SetParent() doesn't show the window
I have this one problem I just can't solve. I'm trying to make a window from my application that is transparent (using flags WS_EX_TRANSPARENT | WS_EX_LAYERED) a child to another window, which is not transparent. When I don't use the call SetParent( my_window, target_parent_window ) with my_window having the WS_EX_LAYE...
https://learn.microsoft.com/en-us/windows/win32/winmsg/window-features To create a layered window, specify the WS_EX_LAYERED extended window style when calling the CreateWindowEx function, or call the SetWindowLong function to set WS_EX_LAYERED after the window has been created. After the CreateWindowEx call, the laye...
69,792,106
69,792,285
Confusing about char* in c++
test code: #include <iostream> using namespace std; int main() { const char* b="str"; cout << b << endl; cout << *b << endl; cout << &b << endl; cout << *(&b) << endl; return 0; } result: str s 0x7ffdf39c27f0 str I run my code on the web runoob online compiler Why I get these results...
To understand what the code outputs, you need to understand that C++ output streams (objects with a type such as std::ostream) and therefore objects (such as std::cout) have a number of overloads of operator<<(). The overload that is called depends on the type of argument provided. I'll explain your second example, ...
69,792,207
69,792,428
Iterating through an array of objects C++
I am trying to iterate through an array to objects to set different attributes of those objects. The attributes of my objects may change over time. My code as a simplified example: // MyClass.h class MyClass { /* class definitions */ }; extern MyClass object; // MyClass.cpp #include MyClass.h /* Constructors, Destru...
There are several mistakes in your given code snippet. You can correct them as i have shown below. I have added comments wherever i have made changes. MyClass.h #ifndef MYCLASS_H #define MYCLASS_H // MyClass.h class MyClass { /* class definitions */ public: MyClass() = default; }; extern MyClass object[20]; //declare ...
69,792,281
69,795,105
static_assert evaluates non constant expression
Why does it working? #include <cstdio> template<auto x> struct constant { constexpr operator auto() { return x; } }; constant<true> true_; static constexpr const bool true__ = true; template<auto tag> struct registryv2 { // not constexpr static auto push() { fprintf(stderr, "%s\n", __PRETTY_FUNCTION__); ...
static_assert evaluates non constant expression Nope, it most certainly does not. Constant evaluation has a strict set of conditions to is must obey in order to succeed. For starters: [dcl.dcl] 6 In a static_assert-declaration, the constant-expression shall be a contextually converted constant expression of type boo...
69,792,467
69,808,694
Memory check on macOS 12 Monterey?
Valgrind is not compatible with macOS 12 now, and I tried to add compile flag -fsanitize=address, but got link error: Undefined symbols for architecture x86_64: "___asan_init", referenced from: _asan.module_ctor in main.cpp.o "___asan_version_mismatch_check_apple_clang_1300", referenced from: _asan.modu...
Are there any patches via macports or brew that allow you to install Valgrind on macOS 12? It's all a question of resources. I think that I'm the only active Valgrind dev that uses macOS, but my focus is on FreeBSD. It's a bit of a pity that Apple (market cap of $2.4 trillion at the time of writing) can't commit some r...