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,861,484
70,862,527
showing the full content of ImageType in DCMTK
I'm trying to read a number of Siemens DICOM images with DCMTK, some of which are mosaic images. I'm looking for a quick way to find those. What I can see with mosaic images is that this is specified in the ImageType tag, e.g. $ dcmdump ${im0} | grep ImageType (0008,0008) CS [ORIGINAL\PRIMARY\ASL\NONE\ND\NORM\MOSAIC] #...
Image Type (0008,0008) is a multi-valued attribute. That is, it may include several values which are separated by the backslash character. Note, that "officially", the backslash is not part of the attribute's value. It is a delimiter between several values of the attribute. This is what you have. So in terms of DICOM, ...
70,862,064
70,863,591
Friend class of template class problem (C++) (error: 'LinkedList' is not a class template)
I am trying to implement a generic Linked list in C++ and I get an error that I don't know how to deal with. Here is my Link class implementation (which is also generic): #ifndef LINK_H #define LINK_H #include <iostream> #include "typeinfo.h" #include "LinkedList.h" template <class T> class Link { public: //|-...
Simply add a forward declaration of LinkedList before the definition of the Link class like this: template<typename U> class LinkedList; // Now the definition as you have it above... template <class T> class Link { public: ... See here. BTW, you're missing a ; after your friend declaration in your first code blo...
70,862,456
70,862,498
Difference between data assignment in pointer and a variable
Why does the program exit with exception when i use the array variant instead of the pointer. int main() { // unsigned char data[1920 * 1080 * 4]; this causes the exception unsigned char* data = new unsigned char[1920 * 1080 * 4]; std::cout << "Hello World!\n"; }
Automatic storage duration (the commented case) has a limit of about 1Mb on current platforms. Dynamic storage duration (the uncommented case) allows for much larger contiguous blocks to be allocated. (In excess of 1Gb on current platforms). The C++ standard doesn't mandate specific limits.
70,862,819
70,862,876
Using a field of an abstract class as a default argument of a method (c++)
I wrote an abstract class called "List", which I basically use as an interface for other implementation methods of lists (such as dynamic array and linked list). Now, I have a method called "add", with 2 arguments, the first one is the data to add and the second is the position where to add. I want to set the default v...
You cannot use members as default arguments of methods. Instead, write an overload. It doesn't need to be virtual when it calls the virtual add(T,int): void add(T data) { add(data,m_size ); }
70,863,308
70,875,111
Given n points, how can I find the number of points with given distance
I have an input of n unique points (X,Y) that are between 0 and 2^32 inclusive. The coordinates are integers. I need to create an algorithm that finds the number of pairs of points with a distance of exactly 2018. I have thought of checking with every other point but it would be O(n^2) and I have to make it more effici...
There is one Pythagorean triple with the hypotenuse of 2018: 11182+16802=20182. Since all coordinates are integers, the only possible differences between the coordinates (both X an Y) of the two points are 0, 1118, 1680, and 2018. Finding all pairs of points with a given difference between X (or Y) coordinates is a sim...
70,863,429
70,863,802
Parsing text file with symbol
I cant parse all text from .txt file But when I run my code, I don't get what I wanted :( My code: int main() { /* inside "logMsg.txt" 1/ [111]{1}(text line from 111); 2/ [222]{2}(text line from 222); 3/ [333]{3}(text line from 333); */ ifstream textfile("logMsg.txt"); string log_line; string log_time...
I would recommend using regular expressions for this: The example below just parses each line using a given pattern. You may need to modify it, for instance, allowing whitespaces around certain fields. [Demo] #include <fmt/core.h> #include <iostream> // cout #include <regex> #include <sstream> // istringstream #inc...
70,863,728
70,863,789
What should I do with this error on input? Can you also suggest how to make my code better, I converted it from C into C++
There is an error in this line cin >> X >> Y; This is the function it belongs into void InputData(int *X,int *Y) { cout << "Enter 2 integer values: "; cin >> X >> Y; } Below is the whole code #include <iostream> using namespace std; void Message(); void InputData(int *X, int *Y); void OutputData(int X, int Y,...
cin >> X >> Y; ->cin >> *X >> *Y;
70,863,964
70,864,032
I want the user to input the day number as the value of the parameter of the called function using cin
So, as you see in the question I want to make the user input the value of the arguement daynum down when I call the function getday, and not me who enters it. However I can't seem to get it right. I have tried cin << getday(); but it's wrong I looked in the internet to get an idea I guess and I tried getday(cin); but s...
You have to create a temporary variable, fill it with user value using cin, and then pass it to your function: string getday(int daynum) { string dayname; switch (daynum) { case 0: dayname = "sunday"; break; case 1: dayname = "Monday"; break; ...
70,864,475
70,867,380
reading new line from file and writing to another file in C++ using streams. not reading new line
I am reading IO streams in C++ and have following code int main() { fstream output_file; output_file.open("cout.txt", ios::out); fstream input_file; input_file.open("cin.txt", ios::in); // backup existing stream buffers streambuf* cin_old_streambuf = cin.rdbuf(); streambuf* cout_old_...
While getline(cin, line); does retrieve the input from your other file line by line, if you want new lines when printing with cout << line; you should still follow the standard of adding either "\n" or endl; at the end of your cout lines. The last part of your code should look like this. getline(cin, line); cout << lin...
70,865,226
70,866,001
How to iterate over enumerators of an enum class?
Is there a way to initialize a container (e.g. std::unordered_set<char>) with the enumerators of an enum class? I have this class: #include <iostream> #include <unordered_set> class Foo { public: inline static const std::unordered_set<char> chars_for_drawing { '/', '\\', '|', '-' }; }; int main( ) { for ( ...
No there is no straightforward way. Something one often forgets: The range of the enums values is determined by its underlying type. The enumerators are just some named constants. Your enum: enum class AllowedChars : char { ForwardSlash = '/', BackSlash = '\\', VerticalSlash = '|', Dash = '-' }; helps ...
70,865,456
70,869,119
CMake: What formatting does execute_process() do?
I need to call the findstr Windows command (grep on Linux) from my CMakeList.txt. If I do this, it is working : execute_process( COMMAND findstr "NABO_VERSION " nabo\\nabo.h WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} RESULT_VARIABLE FINDSTR_RESULT ERROR_VARIABLE FINDSTR_ERROR OUTPUT_VARIABLE FIND...
So I created a test file called nabo\nabo.h with the following contents: #define NABO_VERSION "1.0.7" #define NABO_VERSION_INT 10007 Then at cmd, I wrote: > findstr "NABO_VERSION " nabo\nabo.h #define NABO_VERSION "1.0.7" #define NABO_VERSION_INT 10007 and got both lines back. Adding /c: is necessary: > findstr /c:"N...
70,865,483
70,879,278
Qt cross-platform mobile ADS support?
I have a mobile app developed in Qt. Is there a way to support ads with Qt? Thanks in advance!
There's a cool, newly released, first party Advertising library from Qt. To use it: be sure you have Qt 5.15.0 or higher installed (up to 6.2.2). Install Qt Digital Advertisement plugin from either the installer or from the Maintenance Tool of your already installed Qt environment. Copy the profile.dat and configMobil...
70,865,904
70,866,525
dynamic_cast downcasting: How does the runtime check whether Base points to Derived?
I am interested in understanding how, generally speaking, the runtime checks whether a base class actually points to a derived class when using dynamic_cast to apply a downcast. I know that each virtual table of a polymorphic class contains RTTI too (in the form of type_info pointers).
Every compiler is going to have slight differences in implementation, but I'm going to use MSVC as a reference as they easily supply the source with VS. You can view all of the details on how MSVC does it by going to your Visual Studio installation and going to /Community/VS/Tools/MSVC/${VERSION}/crt/src/vcruntime/rtti...
70,866,546
70,866,707
does malloc(sizeof(Class1)) allocate the same size of memory as new Class1?
For any class, say "Class1" Does cpp standard guarantee that malloc(sizeof(Class1)) allocate the same size of memory as allocated by new operator? new Class1
If the non-array new expression's allocation function call is neither omitted nor extended as explained below, it will call an operator new to allocate storage with a size argument exactly equal to sizeof of the object type. (But not for array new expressions.) However, a new expression's allocation might be extended t...
70,866,579
70,866,580
How to make a new Visual Studio C++ project aware of an existing shared project?
The new(er) Shared C++ Project template in Visual Studio is much easier to use than previous ways code sharing was tackled. Adding one to your solution is as simple as "Add -> New Project -> Shared Items Project," and voilà! Any code inside that project is visible to all your existing projects just as if it existed in ...
As it happens, there is a quick and simple way to remedy this problem. All that's needed is a single change to the project file. Open up the new project's .vcxproj file (as text) and find the tag that reads <ImportGroup Label="Shared"> (for a new project, this tag will likely be empty). Then, just add your shared proje...
70,866,681
70,867,446
How to run cuda cooperative template kernel
I am trying to unsuccessfully launch template kernel as cooperative kernel in CUDA C++ , what am I doing wrong error Error cannot determine which instance of function template "boolPrepareKernel" is intended I try to invoke kernel like below ForBoolKernelArgs<int> fbArgs = ...; int device = 0; c...
Here is a minimal example that will compile: $ cat t1954.cu template <typename TYO> struct ForBoolKernelArgs { TYO val; }; template <typename TYO> __global__ void boolPrepareKernel(ForBoolKernelArgs<TYO> fbArgs) { } int main(){ ForBoolKernelArgs<int> fbArgs; void *kernel_args[] = {&fbArgs}; cudaLaunchCoope...
70,866,692
70,867,005
What is member interpretation in Range-based for loop (since C++11)?
I read this documentation for a range-based for loop: The member interpretation is used if the range type has a member named begin and a member named end. This is done regardless of whether the member is a type, data member, function, or enumerator, and regardless of its accessibility. Thus a class like class meow { e...
The "member interpretation" refers to begin_expr and end_expr using members of the iterated type in contrast to using plain offsets for arrays or begin and end free functions. The array interpretation is off the table, because it is only used for arrays. Next consider that there is std::begin and std::end: Custom over...
70,866,834
70,867,528
How to get a bitmap from a hdc?
I can load a hbitmap into a hdc like this: Gdiplus::Color Color{ 255, 255, 255 }; hBitmap = NULL; Gdiplus::Bitmap* bitmap = Gdiplus::Bitmap::FromFile(L"home.png", false); if (bitmap) { bitmap->GetHBITMAP(Color, &hBitmap); delete bitmap; } ...
You can use GetCurrentObject() to access the HBITMAP (and HPALETTE) currently selected into an HDC. Alternatively, you can create a new HBITMAP of desired dimension and color depth, SelectObject() it into a new memory HDC, and then BitBlt()/StretchBlt() the source HDC into it. Either way, once you have an HBITMAP, you ...
70,867,837
70,870,772
getline error in C++ code to swap uppercase to lowercase and vice-versa of a user inputted string
I am learning C++ and I came across this error that I cannot seem to fix. The code should get a string from the user, then swap the uppercase characters to lowercase characters, and lowercase characters to uppercase characters: #include <iostream> #include <string> using namespace std; void swapCase (const string& s)...
Let me summarize comments: how would I assign a variable to str if I want to keep it as const? answer is: U can't assign nothing to const variables, u can only initialize const variables. In your case u can do the following (showing only posibility not recommend do that): string temporary_str; getline(cin, temp...
70,867,866
70,868,038
C++ Passing templated functions to function
I need to pass a templated function to a function. Until now I haven't found any great advices on google. This is what I tried: #include <iostream> #include <sstream> using namespace std; struct event { bool signal; }; template<typename T> void out_stream(T &stream, event &evt) { stream << evt.signal; } template...
For this particular case, you could help the compiler deduce T by calling doOperation with out_stream<std::stringstream>. Also, within doOperation, you need to use f instead of F. [Demo] #include <iomanip> // boolalpha #include <iostream> // cout #include <sstream> // stringstream struct event { bool signal{}; ...
70,868,003
70,868,701
Calling functions and passing arguments through map in c++?
I've been trying to figure out how I can use std::map to call functions and pass arguments to said functions based on a key. I'm translating a project I made in Python to C++, but I've been stuck on this, and I really don't want to resort to a mess of if-elses. The way I did that in Python was as so: return_operation =...
First off, you can't add custom types to the std namespace. Only specializations of existing templates. Second, you are using the wrong mapped type for the unordered_map. Try something more like this instead: class Calculator { private: typedef double (Calculator::*FuncType)(double, double); unordered_map<st...
70,868,044
70,868,615
How to link Cmake project in CXX Rust and use on Rust?
I did this in cxx: fn main() { cxx_build::bridge("src/main.rs") .file("src/something.cc") .flag_if_supported("-std=c++17") .compile("my_demo"); } I want to link something.cc with another C++ library, but still run everything on Rust. I thus want to call C++ code, from Rust, and still have i...
cxx can work with Cargo and C++ build systems. autocxx might also be useful.
70,868,249
70,868,954
Rpath/Runpath handle with dependent shared libraries in CMAKE
I will put you in context: I have 2 third party shared libraries: libA.so and libB.so. My program contains only calls to libA.so symbols. The libA.so internaly needs to call to libB.so. If I readelf LibA.so it has a RunPath pointing to a path from the third party developer that doesn't exsist in my system. My program b...
You can change RPATH with a tool named patchelf: sudo apt install patchelf patchelf --set-rpath \$ORIGIN libMyLibrary.so Note that $ORIGIN here means "search in the folder where this library located". You can also combine values like this: \$ORIGIN:\$ORIGIN/../lib. This is convenient if you want to keep unix-like inst...
70,868,297
70,870,762
Pathfinding in a lattice - help to understand example
I am working on a problem where I calculate the number of possible paths to a lattice of N * N possible options. There have been some mathematical answers that suggest a simple "combinatorics" answer, but I have no experience with combinatorics. Searching around I found this relatively short answer, but it does not m...
There are quite a few ways how you can arrive at the correct answer for this question, depending on how you approach it. I would highly recommend you to first try to solve the puzzle on your own & not to look at other solutions - that usually has the best learning effect. I'll only explain the logic behind the differen...
70,869,324
70,869,735
CL/cl.hpp: No such file or directory | NVIDIA GeForce
Good afternoon! I'm trying to run code in C++ that has the following line: #include <CL/cl.hpp> But launching the program gives this error: fatal error: CL/cl.hpp: No such file or directory What have I tried to do? Completely reinstalling mingw64 Uninstalled Visual Studio 2019 and installed Visual Studio 2022 Instal...
It is best to include the OpenCL headers in the same directory where the source code of your Visual Studio Project is. You then have to tell Visual Studio where these files are located. To configure the project and set the file paths, see this answer. You don't need to install CUDA at all. The OpenCL Runtime is include...
70,869,535
70,869,707
std::barrier is_nothrow_invocable_v<CompletionFunction&> shall be true error
I am trying to simulate a dice roll program, to be more specific get the number of rolls necessary to get n dices to be 6 at the same time. So this is a textbook example of fork-join model in order to simulate rolls simultaneously and then check result after each iteration. #include <iostream> #include <vector> #includ...
The issue is in the error message. Which is great, even cites exactly the part of the standard which has this requirement: [thread.barrier.class]/5: CompletionFunction shall meet the Cpp17MoveConstructible (Table 28) and Cpp17Destructible (Table 32) requirements. is_­nothrow_­invocable_­v<CompletionFunction&> shall be...
70,869,803
70,870,625
C++ - Code crashes when trying to sort 2d vector
I'm writing a code in C++ and it's always giving the same error: Segmentation Fault, but I don't know why this is happening. I've created a small program that gives the error. #include <vector> #include <iostream> #include <algorithm> using namespace std; int N = 17; vector<vector<int>> v; void func(vector<int>& x){ ...
std::sort requires irreflexivity. From [alg.sorting] in the standard: The term strict refers to the requirement of an irreflexive relation (!comp(x, x) for all x) However, the lambda returns true for comp(x, x). The fun thing is that the programs works with no error when N < 17. It's undefined behavior. It's unluc...
70,869,835
70,870,169
How to push objects to a static vector while in the contructor of a class in C++
I need to get in a vector the names of some cities as soon as they are created... In order to accomplish that I created a static vector for the class City, however when I try to compile my code I get the error error: lvalue required as unary '&' operand this->cities.push_back(&this); ...
this is already a City* pointer, so drop the & from &this. Also, don't forget to actually define the static vector object. Also, you should account for the class' copy/move constructors and destructor, to make sure you don't miss adding pointers, or leave behind dangling pointers. Try this: #include <iostream> #include...
70,869,846
70,869,859
How to delete/free a string literal?
I have a std::vector<const char*> which I populate by .push_back("something"). How to delete contents not including std::string's header? delete segfaults, and std::free needs void* and it "cannot initialize [..] with an lvalue of type 'const char *'".
String literals have static storage duration. You may not delete them using the operator delete. String literals will be alive until the program ends, You may delete what was created using the operator new. You can just erase all or selected elements of the vector or clear it entirely.
70,869,946
70,871,569
When not to use auto as described in Bjarne Stroustrup book: A Tour of C++
I was reading A Tour of C++ and got confused as to the reason to use auto. We use auto where we don’t have a specific reason to mention the type explicitly. ‘‘Specific reasons’’ include: • The definition is in a large scope where we want to make the type clearly visible to readers of our code. • We want to be expl...
The "range" of a variable in that sentence refers to the minimum and maximum values it can hold. For example, the range of a signed char is typically -128 to 127.
70,870,193
70,870,308
Introduce variable in a C++ constraint
Given a require block on a struct such as this one template<typename A, typename B, typename C> struct MyOtherTypeLevelFunction<A, B, C>; template<typename A, typename B, typename C> requires (MyConcept<MyTypeLevelFunction<A, B, C>>) && (MyOtherConcept<MyTypeLevelFunction<A, B, C>>) struct MyOtherTypeLevelFunc...
You can create a combined concept: template <typename F> concept MyCombinedConcept = MyConcept<F> && MyOtherConcept<F>; template<typename A, typename B, typename C> requires MyCombinedConcept<MyTypeLevelFunction<A, B, C>> struct MyOtherTypeLevelFunction<A, B, C> { using Output = MyTypeLevelFunction<A, B, C>::T; } ...
70,870,201
70,870,594
Hashing words in C++?
I have a text file that I read the data from and search the names inside to keep track of it. I want to use Hashing instead of Arrays for the speed of search, and I don't want to insert a name twice if it's already included in the hash. (I found some code about hashing but the example code was for numbers not for strin...
You can just use an unordered_set #include <string> #include <unordered_set> #include <fstream> std::unordered_set<std::string> file_to_unordered_set(const std::string& filename) { std::unordered_set<std::string> tbl; std::ifstream fs(filename); if (!fs) { throw std::runtime_error("bad file"); ...
70,870,562
70,871,142
Explaining output (inheritance, c++)
Consider the following program: using namespace std; class A{ private: int _a; public: A(int a): _a(a) {cout<<"A-ctor: a= "<<_a<<endl;} A(const A& other) : _a(other._a) { cout<< " A-copy ctor: _a= " << _a<< endl; } ~A() {cout << "A-dtor" << endl;} }; class ...
I would expect a compilation error since B does not have a copy-constructor But B does have a copy-constructor. Its copy constructor is implicitly defined. Why there is no compilation error here? Because the program is well-formed. But even if it has a copy constructor, I suppose the copy would be shallow, meaning...
70,871,299
70,871,583
Make the compiler deduce the parameter of a function before compilation
Here is an example of my problem. #include <stdio.h> //template<std::size_t A> <-- Tried to solve the problem by using template void func1(const int power){ const int length = 1 << power; int twoDArrayA[length][length]; for (int j = 0; j < power; j++) { /* Code */ } } int main() { fun...
You can do this with a template, but you've got the wrong syntax. It should be: template<std::size_t power> void func1(){ const std::size_t length = 1 << power; int twoDArrayA[length][length]; ... } int main() { func1<4>(); ... } Note that your variable length array (VLA) is legal C++ if length i...
70,871,732
70,871,784
How to use commas to split chars in a loop?
I'm writing a program in c++ and I'm trying to separate letters like this: "A,B,C" But it comes out like this, and I don't know why: ",A,B,C". Help? My code is below: #include <iostream> #include <ctype.h> using namespace std; int main() { char startChar='Z'; char stopChar='A'; whil...
When stopChar is C and startChar is A, this condition will be true and therefore a , will be printed in every iteration of the loop (including the first): if (stopChar > startChar) cout << ","; You can fix it by changing it to: if (chLoop != startChar) std::cout << ','; That is, only if chLoop is not startCha...
70,871,840
70,871,856
How to remove the leading 0 and the last 0 in this code?
I am attempting to write a program that asks for user input of a positive integer larger than 2. The program is supposed to output all the positive integers that are smaller than the user input and that are multiples of 3. However, when running my code I noticed there are two annoying 0’s that keep appearing and aren’t...
Let's walk through your code and explain it. There are 2 important parts that have cout: for (int i = 0; i < x; i += 3) { cout << i << " "; } What does this loop mean? Well Start i at 0 Go while i is less than x Increment i by 3 Print every i. The important part is 1. You are starting i at 0, you will print 0. T...
70,872,391
70,872,666
Unable to retrieve a static vector from inside a class
I want to get a vector from the class City, however I am not able to see any of those cities generated, in the vector cities being displayed... However I do know that they are being generated as I can see their names as well as the size being incremented being displayed in the constructor. Contructor for: Hong Kong 1 C...
You have to create a city object in main. Try passing all those constructors in main as a city object. Also, I compile your original code with vs c++17 and it throws an exception. int main() { City hongKong{ "Hong Kong" }, bangkok{ "Bangkok" }, macau{ "Macau" }, singapura{ "Singapura" }, londres{ "Londres" }, paris{...
70,872,795
70,872,841
what does the arrow operator means and how can be converted to python?
i am new to c++ and i know so much more python than c++ and i have to change a code from c++ to python, in the code to change i found this sentence: p->arity = std::stoi(x, nullptr, 10); i think for sake of simplicity we can use p->arity = x; /* or some whit pointers im really noob on c++ but i think this is not imp...
What I understand about the arrow operator from this post: An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. Since Python doesn't deal with pointers, this is not directly comparable. However, you can think of its usage a...
70,873,074
70,873,241
Using member function without taking address?
class C{ public: int i(){return 3;} }; void memfn(int (C::* const & func)()){} void fn(int (* const & func)()){} int main() { fn(&foo); //Works fn(foo); //Works memfn(&C::i); //Works memfn(C::i); //Doesn't Work } When passing a function pointer as a parameter, the address-of operator is optional on the fun...
There is an implicit conversion from global function references, or static member function references, or non-capturing lambdas, to function pointers. This is for capability with C. But such implicit reference-to-pointer conversions are not for non-static member functions (and capturing lambdas!), because they need an ...
70,873,103
70,873,404
push_back crashed when using std::vector if the type only defined copy constructor with c++11
The code like this: #include <iostream> #include <vector> struct Foo { int i; double d; }; class Boo { public: Boo() : fptr(nullptr) { std::cout << "Boo default construct..." << std::endl; } Boo(int i, double d):fptr(new Foo{i,d}) { } Boo(const Boo &rhs) :fptr(new Foo{rhs...
The problem is that in the copy constructor of Boo you're dereferencing a nullptr. This is because when you wrote: std::vector<Boo> vec(1); //this creates a vector of size 1 using Boo's default constrcutor This is what happens due to the above statement: The above statement creates a vector named vec of size 1 using ...
70,873,585
70,873,635
sqlite '=': cannot convert from 'const char [164]' to 'char *'
I am running the code example for sqlite from here to create a table in C++, here is the code: #include "../contrib/sqlite/sqlite3.h" static int callback(void* NotUsed, int argc, char** argv, char** azColName) { int i; for (i = 0; i < argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "...
The problem is your sql variable. It is a char* pointer, which is a pointer to non-const character data. But you are trying to assign it to point at a string literal, which is const character data (in this case a const char[164] array). Assigning a non-const character pointer to point at const character data is danger...
70,873,632
70,873,827
Moving array elements over one position
I have a homework assignment where we're supposed to create a list of integers, and allow the user to INSERT an integer at a given position in the list. The list should essentially move all integers over one position in the array, then insert the integer that the user input at the index they chose. So let's say I have ...
Based on your code, just change your insert function to this - Here we first shift the values to next index in the array and then perform insertion of respective element void *INSERT(int c, int n, int i, int a[]){ //Accepts count of array, users number, users index, and array for(int r = c-1; r >= i; r--) { ...
70,873,688
70,875,434
How to define the operator= for a unique_ptr wrapper class?
I am trying to create a wrapper class for the std::unique_ptr, for now it just needs to support the basic operations for the unique_ptr, but in the future this would have more functionalities. template<typename T> class Unique { public: Unique(std::nullptr_t) { pointer = nullptr; } template<typename ...Args> ...
Turns out, as @che.wang pointed out, I actually needed a Converting Assignment Constructor based on (2) from the unique_ptr reference like: template<typename U> Unique(Unique<U>&& other) { pointer = std::move(other.pointer); }
70,873,747
70,874,568
In this syntax, what is the actual type of auto?
In the C++17 for loop syntax for(auto [key, val]: students), what is auto replacing? If students was, for example std::map<int,char*>, what would be written if not auto? I don't understand what it even is taking the place of. [int,char*]?
type [a,b,c] is a structured binding, and those force you to use auto (possibly decorated with const and/or &/&&). But aside from that, auto expands to the same type it would expand to if [...] was replaced with a variable name. In for (auto elem : students) ... auto expands to std::pair<const int, char *>. In a struc...
70,873,915
70,874,275
Modifying class variables using functions during a combat do while loop C++
Feel free to let me have it for being a noob here as I have only been programming for about a month in my spare time haha... but I made the terrible decision to try making an RPG, which I have since redacted while I keep learning the basics, and am now trying the most condensed form of an RPG-style combat system I cou...
There are a few potential issues with your code. First, in your while loop, every time you write hero() or enemy() you create a new instances of the classes hero and enemy, respectively. That is also leading to the compiler error you received. Apart from the error, there is an other issue with that. Every new instance ...
70,873,962
70,874,076
What is time complexity of "isalnum(char)" in c++?
isalnum(char) is a method which tells us, whether a given character is alphanumeric or not. What is the time complexity of this small function? I have written a small subroutine : bool check(string s,int i) { if((s[i]>='a' && s[i]<='z') || (s[i]>='0' && s[i]<='9') || (s[i]>='A' && s[i]...
These functions are different, because isalnum takes int. If you ask about the actions they perform, they are also different. isalnum('\xdf'), default C locale, returns false isalnum('\xdf'), ISO-8859-1 locale, returns true check("\xdf", 0) always returns false. Time complexities in the both cases are similar, O(1). Y...
70,874,864
70,875,779
Eigen::Vector declare with max entries at compile time?
Is there a way to declare an instance of Eigen::Vector while specifying the max. number of elements at compile time? For the case of Eigen::Matrix it is possible to do it via Eigen::Matrix<int,Eigen::Dynamic,Eigen::Dynamic,Eigen::ColMajor,128,128> myMat; but I don't seem to find a way to do it for Eigen::Vector. Thank...
Eigen::Vector is just an alias template for an Eigen::Matrix of column size 1, without allowing to specifying an argument for the _MaxRows template parameter of the aliased Eigen::Matrix class template. Global matrix typedefs template<typename Type , int Size> using Eigen::Vector = Matrix< Type, Size, 1 > You co...
70,875,281
70,876,163
Automatically migrate JSON data to newest version of JSON schema
I have a service running on my linux machine that reads data stored in a .json file when the machine is booting. The service then validates the incoming JSON data and modifies specific system configurations according to the data. The service is written in C++ and for the validation im using https://github.com/pboettch/...
What you're asking for is something which will need to make assumptions to work. This is an age old problem and similar for databases. You can have schema migrations generated with many simple changes, but this is not viable if you wish to translate existing data automatically too. Let's look at a basic example. You re...
70,876,266
70,876,440
can't find overloaded method from inherited class template
This is the first time I am using class templates so please don't be to harsh if I made a simply mistake. I have a class template class A<class T>. It has a method init() that is pure virtual and therefore will be implemented separately in every derived class. What all these possible derived classes will have in common...
class A_der : public A<B_der> { void init() override; }; When you declare a function init in the derived class, it hides all things named init from the base class. This is just like when declaring something in an inner scope - it hides things with the same name from outer scopes. There are ways to import the hidde...
70,876,567
70,876,820
Any way to trick std::transform into operating on the iterator themselves?
So I wrote this code which won't compile. I think the reason is because std::transform, when given an iterator range such as this will operate on the type pointed to by the iterator, not the iterator itself. Is there any simple wrapper, standard lib tool, etc. to make this code work i.e. to store all the iterators of t...
Is there such a wrapper? Not in the standard. But it doesn't mean you can't write one, even fairly simply. template<typename It> struct PassIt : It { It& operator*() { return *this; } It const& operator*() const { return *this; } PassIt & operator++() { ++static_cast<It&>(*this); return...
70,876,692
70,876,838
why do ranges algorithms take rvalue reference as argument
if I take for example the ranges::fill algorithm: https://en.cppreference.com/w/cpp/algorithm/ranges/fill the signature is: template< class T, ranges::output_range<const T&> R > constexpr ranges::borrowed_iterator_t<R> fill( R&& r, const T& value ); And an example use: #include <algorithm> #include <vector> #include <...
Since R is a template parameter, R&& is not an rvalue reference, it is a forwarding/universal reference. Forwarding references Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to forward it by means of std::forward. Forwarding references...
70,876,924
70,876,959
C++: Why are arrays on the stack allocated after "normal" ints for instance, regardless of ordering in the code?
Performing some tests on how c++ compilers (in my case g++ on linux) behave when allocating local variables on the stack. Take a look at this simple code: #include <iostream> int main() { int prev = 10; int myArr[5] = {4, 5, 7, 2, 1}; int next = 10; return 0; } All of these variables are allocated on...
One would think that that segment of the stack looks like this: prev myArr next This order is not guaranteed. Some kind of optimization putting the larger int-array after the smaller 4byte ints or am i missing something? Yes, the compiler may arrange the objects as it likes. Order of objects on the stack is not spe...
70,876,966
70,877,510
Why is there an unnecessary or operation when inverting bytes?
I am really confused by this, however trivial it may be. Here's an example (which I tried on paper): uint16_t val = 32; //00000000 00100000 uint16_t swapped = val >> 8; //00100000 00000000 uint16_t swapped2 = val << 8; //00100000 000000...
As many has already stated in the comments, the >> and << operations are bitwise shifts, not bitwise rotations. See https://en.cppreference.com/w/cpp/language/operator_arithmetic. In the most recent standard (C++20) they've added the rotations as well: see rotr and rotl.
70,876,973
70,877,060
multiple initializations in for loop
I am trying to write a function to find the average of numbers at first i wrote code as double CPPLib::average_of_numbers(std::vector<int> &numbers){ double result = -1; if(numbers.size() != 0) { result = 0; for(int i=0;i< int(numbers.size());i++) { result += numbers[i]; ...
In your second example, you've actually declared two separate variables called result. The first is here at the top of your function. double result = -1; The other is here: for(int i=0,result = 0;i< int(numbers.size());i++) You've declared both a temporary int named result (in addition to i) who's lifetime and s...
70,876,975
70,877,051
Will there be a standard typelist?
Why isn't there a standard typelist in the C++ standard? I would think that something so useful for generic programming (as shown in reflection's ObjectSequence) would be a good candidate for standardization, instead of the myriad implementations around. Are there plans to add one?
N3416: Packaging Parameter Packs proposed a language typelist, but is dead in the water since a decade back. A parameter pack literal is a template-parameter-list (§14p1) surrounded by angle brackets, like <int, std::basic_ostream<char>, 7> To name a parameter list, we just typedef it, like typedef<signed char, short...
70,877,544
70,878,433
std::atomic - behaviour of relaxed ordering
Can the following call to print result in outputting stale/unintended values? std::mutex g; std::atomic<int> seq; int g_s = 0; int i = 0, j = 0, k = 0; // ignore fact that these could easily made atomic // Thread 1 void do_work() // seldom called { // avoid over std::lock_guard<std::mutex> lock{g}; i++; ...
Even ignoring the staleness, this is causes a data race and UB. Thread 2 can read i,j,k while thread 1 is modifying them, you don't synchronize the access to those variables. If thread 2 doesn't respect the g, there's no point in locking it in thread 1.
70,877,650
70,878,895
simple code that compile in c++17 produce error with c++20
I have a strange error returned by gcc/clang When I switch from std=c++17 to std=c++20. struct Matrix2 { double ptr[9]; // defaults Matrix2() = default; // constructor Matrix2(const Matrix2&) = default; // copy constructor Matrix2(Matrix2&&) = default;...
There was a change in the C++ standard between C++17 and C++20 for aggregate initialization. Have a look at aggregate initialization (cppreference) Look at the explanation section: since c++11, until c++20: no user-provided, inherited, or explicit constructors (explicitly defaulted or deleted constructors are allowed)...
70,877,684
70,878,700
Boost::filesystem::directory_iterator causes linker error after upgrade to v1.78.0
I want to use boost::filesystem in my project, and until recently this was possible (v1.65.1). A few days ago, I had to upgrade my boost installation to 1.78.0 and followed the instructions on the site to build the library from source. I executed the following lines: wget https://boostorg.jfrog.io/artifactory/main/rele...
The includes are compile time. The shared libraries are linked at link time. You didn't explicitly tell the to find the headers, nor did you tell the compiler where to locate the libraries. This means that the standard locations are used. Depending on your package manager there may be symlinks like: /usr/lib/x86_64-lin...
70,878,173
70,883,057
What is "MAX" referring to in the intel intrinsics documentation?
Within the intel intrinsics guide some operations are defined using a term "MAX". An example is __m256 _mm256_mask_permutexvar_ps (__m256 src, __mmask8 k, __m256i idx, __m256 a), which is defined as FOR j := 0 to 7 i := j*32 id := idx[i+2:i]*32 IF k[j] dst[i+31:i] := a[id+31:id] ELSE dst...
This pseudo-code only makes sense for assembly documentation, where it was copied from, not for intrinsics. (HTML scrape of Intel's vol.2 PDF documenting the corresponding vpermps asm instruction.) ... ENDFOR DEST[MAXVL-1:VL] ← 0 (The same asm doc entry covers VL = 128, 256, and 512-bit versions, the vector width o...
70,878,407
70,878,458
How can I template my print function on std::ostream?
So far, I have a function print: template < char Sep = ' ', class... Args > void print(Args&&... args) { ([](Args&& arg) { std::cout << arg << Sep; }(std::forward<Args>(args)), ...); std::cout << '\n'; } int main() { print("a", 'b', 3, 4.0, 5.0f, true); } I want to template it...
Use an ordinary template argument and pass the stream as parameter to the function: #include <iostream> template <typename stream, char Sep = ' ', class... Args > void print(stream& out,Args&&... args) { ([&out](Args&& arg) { out << arg << Sep; }(std::forward<Args>(args)), ...); s...
70,878,852
70,879,179
Is using the overloading << operator as push_back a good idea?
I've been practicing with operator overloading in order to comprehend it better and I came across using the << operator with vectors like this: void operator<<(std::vector<int> &vector, int value){ vetor.push_back(value); } Now I know that this isn't really a good idea and that I should avoid doing this but I'd li...
Now I know that this isn't really a good idea and that I should avoid doing this Your knowledge is correct. There are two issues with this: It's a bad idea to define operators that don't involve your own types. Technically, the standard doesn't guarantee that it won't add a global operator<<(std::vector<int> &, int)...
70,879,695
70,880,047
Fastest way to strip trailing zeroes from an unsigned int
Suppose we are trying to remove the trailing zeroes from some unsigned variable. uint64_t a = ... uint64_t last_bit = a & -a; // Two's complement trick: last_bit holds the trailing bit of a a /= last_bit; // Removing all trailing zeroes from a. I noticed that it's faster to manually count the bits and shift. (MSVC com...
On x86, _tzcnt_u64 is a faster alterative of _BitScanForward64, if it is available (it is available with BMI instruction set). Also, you can directly use that on the input, you don't need to isolate lowest bit set, as pointed out by @AlanBirtles in a comment. Other than that, noting can be done for a single variable. F...
70,880,512
70,899,769
Does reassignment of pointers acquired by reinterpret_cast from raw memory cause UB?
In our lecture we were discussing the inner possible implementation of std::list. The lecturer showed the approach where a dummy node is created to indicate the end of the list: struct Node { Node* prev; ... } Node* dummy = reinterpret_cast<Node*>(new int8_t[sizeof(Node)]); dummy->prev = ... /* last node */; They cla...
First, for your second line Node* dummy = reinterpret_cast<Node*>(new int8_t[sizeof(Node)]); by itself. new returns a pointer to the first int8_t object in the array of int8_t objects it created. reinterpret_cast's behavior depends on the alignment of the address represented by the pointer. If it is suitably aligned f...
70,880,526
70,880,707
Passing uniform_int_distribution as parameter (with state)
I'm trying to write some code that will use random generators but allow you to seed it (for reproducability). The code looks something like the following (trying to create a snippet that can be run) #include <cstdio> #include <functional> #include <random> class CarterWegmanHash {...
You can just create your distribution and mt19937 in main and capture them in a lambda: std::uniform_int_distribution<unsigned int> distribution(0, pow(2, n)); std::mt19937 mt(rd()); auto unif_rand = [&](){ return distribution(mt); }; Or with bind: auto unif_rand = std::bind(std::ref(distribution), std::ref(mt));
70,880,865
71,063,782
Crash in GStreamer qmlglsink pipeline dynamically rebind to different GstGLVideoItem
I've used one of existing qmlglsink examples to stream video feed from 4 IP Cameras. 4 Pipelines are created before engine load. for(int i = 0; i < maxCameras; ++i) { GstElement* pipeline = gst_pipeline_new (NULL); GstElement* src = gst_element_factory_make ("udpsrc", NULL); GstElement* parse = gst_element_...
Two possible solutions: set gst_element_set_state (pipeline, GST_STATE_NULL);, change sink widget to new item and start pipeline gst_element_set_state (pipeline, GST_STATE_PLAYING); use Qt 5 MediaPlayer with gst-pipeline as source. When visible set source and execute start(). When not visible reset source to empty (im...
70,881,511
70,881,609
Is there a way to make a concept that can represent a template parameter pack?
With C++20, we can write a concept and use it like so: template<typename T> concept ClassType = std::is_class_v<T>; template<ClassType T> void foo(); Is there a way to achieve this same syntax when using template parameter packs? We could obviously do it with requires: template<typename T, typename... Ts> concept Sam...
Yes, you can do this, which is functional equivalence to your example: #include <concepts> template<class T, std::same_as<T>... Ts> void foo();
70,881,575
70,881,706
Boost with CMakeLists on Visual Studio
I'm trying to run some code with boost, but i can't include any boost file, like "boost/timer/timer.hpp". My CMakeLists contains cmake_minimum_required(VERSION 3.10) project(Converter) find_package(Boost) include_directories(${BOOST_INCLUDE_DIRS}) LINK_DIRECTORIES(${Boost_LIBRARIES}) add_executable(Converter converter...
You are using a wrong non existing variable here. To set the include Boost directories to your project you need to use Boost_INCLUDE_DIRS, the case of the variable matters. And your link directories should be set to Boost_LIBRARY_DIRS. cmake_minimum_required(VERSION 3.10) project(Converter) find_package(Boost COMPONEN...
70,881,883
70,882,035
(C++) Getter and setter in a class not working as intended
I am trying to write a simple code where the getter and setter is used. Here is the test_class.hpp file #ifndef TEST_CLASS_HPP #define TEST_CLASS_HPP class test_class { private: int num; public: test_class(int num); ~test_class(); int& get_num(); void set_num(int& num); }; #endif Here is the tes...
void test_class::set_num(int& num){num = num;} What exactly is happening here? You assign num to itself. This code does nothing. What you really want is void test_class::set_num(int& num){ this->num = num; } Btw you would avoid this kind of errors if you declared void test_class::set_num(const int& num) (or even wit...
70,882,952
70,898,183
Can static member function without any argument access private attributes of a class?
I have following (simplified) ServerHandler.h file #include <WebServer.h> class ServerHandler { public: ServerHandler(); void createServer(); static void handlePage(); private: WebServer server; }; And ServerHandler.cpp file #include "ServerHandler.h" ServerHandler::ServerHandler() : server...
As I learn it is possible to use member functions thank to @hcheung, I researched how to do it and found. Requirement: typedef std::function<void(void)> THandlerFunction; void on(const Uri &uri, THandlerFunction handler); To use non-static member function I need to use binding. mServer.on("/control_servo", std::bind(&...
70,882,960
70,883,147
Using Enum to represent days
I want to represent a Weekday (Monday to Friday) as an enum but am not sure how to represent the data in c++. I have done some reading and have my enum class: enum Day{MONDAY=0, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY}; But I also need some sort of to_string method in order to print the days out when required. Currently ...
I usually use a table of structs: struct Enum_Entry { enum Weekday day; const char day_name[]; // or const char * day_name; }; and then I have a conversion table: Enum_Entry conversion_table[] = { {MONDAY, "Monday"}, //... {FRIDAY, "Friday"}, }; One nice thing about the above table is that the en...
70,883,061
70,883,167
How to determine the return type of a function in template
I am trying to write a class similar to std::function, just to learn how it works but I am having problem determining the return type of the function. I found this from one of the answers here on stack overflow. I am trying to do something similar but It does not work and I do not know why. template< class Fx > class f...
Since Fx is supposed to be a function type, not a function pointer type, so the specialization should be declared as: template< class R, class... A> struct return_type<R(A...)> { using type = R; }; Other issues: Change using ReturnType = return_type<Fx>::type; to using ReturnType = typename return_type<Fx>::type;...
70,883,592
70,883,714
Using an array from main in a recursive function
As part of a problem, I need to create a recursive function on a string. Part of it is based on the nth element of Fibonacci. The thing is that I need to get n ( the number of elements ) as an input, and only then I can create the array. But I also need to create a recursive function that has to use the array. I though...
Is there any way I can use that specific array in a function in c++? Yes. Pass the array as an argument, using some form of indirection. Typically, this would be done using a parameter of type span. cin >> n >> k; int fibo[n+1]; This isn't allowed. The size of an array variable must be compile time constant in C+...
70,884,182
70,884,290
Tic-tac-toe using classes, compute victory condition
I was trying to make a program for Tic-tac-toe between 2 players, using a class. But my is_victory function is always returning false. Why so? //header file : tic_tac_toe.h class Game { public : Game(); void insert(int , char); void print() const; bool is_empty(int) const; bool is_victory() cons...
if(pntr[0] == pntr[1] == pntr[2]) return true; The condition A == B == C will be evaluated as (A == B) == C. The expression (A == B) will result in false (0) or true (1), and from the initialization of pntr we can see that C will never be equal to 0 nor 1. Therefore, the expression as a whole always evaluates to false...
70,884,233
70,884,660
OpenGL get currently bound vertex buffer and index buffer
I'm currently working with OpenGL in C++, and I'm trying to debug by identifying what the currently bound vertex buffer and index buffer are. I have three functions. GLint getBoundVAO() { GLint id = 0; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &id); return id; }; GLint getBoundVBO() { GLint id = 0; //...
See the "Parameters" section here. The symbolic constants used for binding the buffers match the ones used for glGet* (but with a _BINDING suffix). For the vertex buffer object, use: glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &id); For the index buffer, use: glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &id);
70,884,432
70,885,515
How to get UniquePtr<EnumMember> on the Rust side? (CXX crate)
Using the cxx crate: https://crates.io/crates/cxx I have the following struct on Rust: #[cxx::bridge] pub(crate) mod ffi { enum SizeType { BYTE, WORD, DWORD, QWORD, } unsafe extern "C++" { //... } } which is also mapped on C++. How do I get UniquePtr<SizeType...
Try adding: impl UniquePtr<SizeType> {} See https://github.com/dtolnay/cxx/blob/a95eca61029b458998c1c5463481307af5643ba5/macro/src/expand.rs#L1408 and https://github.com/dtolnay/cxx/blob/a95eca61029b458998c1c5463481307af5643ba5/tests/ui/impl_trait_for_type.stderr.
70,884,494
70,907,955
QML wrapped TableView element behaves different from non-wrapped one
I'm having some troubles getting the QML type TableView to behave correctly when wrapping it inside another item. The problem is that creating a reuseable type basically forces one to use an Item wrapper to have the *HeaderView types in the same .qml file. Here is the rather simple code, a test-model for some data can ...
Apparently it wasn't a good idea to use anchors.fill: parent when trying to attach the *HeaderViews. Once I got rid of that line and simply anchored all views to each other (horizontal to top, vertical to left) it works. Item { implicitWidth: 600 implicitHeight: 250 TableView { id: tableView ...
70,884,514
70,885,149
clang-format indentation of class fields and methods, opening curly braces for functions and enums
My clang-format produces code like this: enum class SomeEnum{ VAL1, VAL2, VAL3 }; class SomeClass { public: void someMethod(); private: int m_field; }; void someFunc() { // ... } But I want it to be like this: enum class SomeEnum { VAL1, VAL2, VAL3 }; class SomeClass { public: ...
AllowShortEnumsOnASingleLine: false # is available since clang-format 12. IndentAccessModifiers: true # is available since clang-format 13. BraceWrapping: AfterFunction: false
70,884,737
70,887,379
Microsoft Bond deserialization without knowing underlying schema
I am looking at some network requests that are happening on my machine, and I recognize some as using the Microsoft Bond data serialization format. I want to deserialize the content of the request, but I do not have the schema that was used to create its content. I know that with the ProtoBuf compiler, there is a way t...
Thanks to some insights from Christopher Warrington, I was able to piece together the methodology through which a Bond-encoded Compact Binary content piece can be "unpacked" into its component pieces: var ib = new Bond.IO.Unsafe.InputBuffer(File.ReadAllBytes("response_data.bin")); var cbr = new CompactBinaryReader<Bond...
70,884,905
70,885,043
QSqlQuery is not binding values
I am performing queries against a MySQL database, and use code similar to below throughout my app. But for some reason the update below says 0 rows affected, when it should be 1. On digging deeper I discovered my bindValue commands don't seem to have any effect. QSqlQuery* query = new QSqlQuery(m_db) ...
QSqlQuery::executedQuery() won't show you the bound values, because the idea of bound values is that they never become part of the query itself (which completely eliminates the problem of escaping them). What you see is the actual query submitted to the database. The bound values are submitted to the database alongside...
70,885,405
70,886,084
C++ client socket sends original file and file size, Java client always get 8 bytes more. Even after force limiting to -8 bytes file is unreadable
For a while, I am troubled with this issue. Using a snippet of C++ code, which I found here, and in my opinion should do a good job actually sending exact amount of data, I guess the problem is in the Java code or something unknown. Also, when sending simple "Hello World" data, transfer is done correctly. I would be gr...
The C++ code is sending the file size before sending the file data (good), but is not doing adequate error handling (bad), and it is NOT sending the file size in an platform-agnostic format (bad). Not that it matters, because the Java code shown is NOT even attempting to read the file size before reading the file data ...
70,885,587
70,890,955
What happens when I read a file into a string
For a small program, seen here here, I found out that with gcc-libstdc++ and clang++ - libc++ reading file contents into a string works as intended with std::string itself: std::string filecontents; { std::ifstream t(file); std::stringstream buffer; buffer << t.rdbuf(); filecontents = buffer.str(); ...
Thanks @user4581301 and @PeteBecker for their helpful comments making me understand the problem. The question stems from a wrong mental model of std::string, or more fundamentally a wrong model of char. This is nicely explained here and here. I implicitly thought, that a char holds a "character" in a more colloquial se...
70,886,218
71,176,625
Torchscript/C++ jit::trace model - Accessing layers parameters
I have a model I trained in python, traced using torch.jit.trace, and load into C++ using torch::jit::load. Is there a way to access the last layer to pull the value for the models required output depth (for example, if it is a Conv2D layer going from 16 -> 2, I want to predefine a tensor for a depth [b,d->2,x,y] of 2)...
Not the most elegant way of solving this, but the most straightforward was just passing a dummy tensor through and accessing the shape. Another way I did try was accessing the parameter list and looking for "softmax", unfortunately I couldn't guarantee everyones model will spell it the same way when searching for this....
70,886,369
70,887,400
How to efficiently scan 2 bit masks alternating each iteration
Given are 2 bitmasks, that should be accessed alternating (0,1,0,1...). I try to get a runtime efficient solution, but find no better way then following example. uint32_t mask[2] { ... }; uint8_t mask_index = 0; uint32_t f = _tzcnt_u32(mask[mask_index]); while (f < 32) { // element adding to result vector removed, ...
This is quite hard to optimize this loop. The main issue is that each iteration of the loop is dependent of the previous one and even instructions in the loops are dependent. This creates a long nearly sequential chain of instruction to be executed. As a result the processor cannot execute this efficiently. In addition...
70,886,928
70,901,168
Default empty usage of methods of uninstantiated class
In my system I have many callbacks which contains calling for method of classes, that are not instantiated according to some configurations values, and when they are not initalized I want the calling to them to do nothing, instead of rasing a seg fault. For example I have some InitManager class that in it's constructor...
Thank you, OP, for editing your question. You have done a good job, the issue is now clear. I would suggest a 'wrapper' class for CloudClient - let's call it CloudClientWrapper, which holds a pointer to a CloudClient instance (which might be nullptr) as a member variable. CloudClientWrapper can then be responsible fo...
70,887,004
70,888,738
How to check the CRC of the function in C++
Is it possible to count the CRC of code in the memory of the function in the runtime? I have a function that compares user's password with the secret password. If I check the CRC of all commands in function, I will be able to understand if the code of the function was overwritten in disassembler. For now, I've tried us...
No, there is no portable way to find or access the compiled function code during execution. If code can be modified maliciously, then the code checking the code can also be modified maliciously to not detect changes, making the exercise entirely pointless. Lastly, a CRC is easily spoofed, so the code could easily be mo...
70,887,045
70,888,141
Difference between _mm256_extractf32x4_ps and _mm256_extractf128_ps
The intel documentation for _mm256_extractf32x4_ps and _mm256_extractf128_ps read very similar. I could only spot two differences: _mm256_extractf128_ps takes a const int as parameter, _mm256_extractf32x4_ps takes an int. This should not make any difference. _mm256_extractf128_ps requires AVX flags, while _mm256_extra...
Right, the int arg has to become an immediate in both cases, so it needs to be a compile-time constant after constant propagation. And yeah, there's no reason to use the no-masking version of the C intrinsic for the AVX-512VL version in C; it only really makes sense to have _mm256_mask_extractf32x4_ps and _mm256_maskz_...
70,887,350
70,887,630
Why second spin in Spinlock gives performance boost?
Here is a basic Spinlock implemented with std::atomic_flag. The author of the book claims that second while in the lock() boosts performance. class Spinlock { std::atomic_flag flag{}; public: void lock() { while (flag.test_and_set(std::memory_order_acquire)) { while (flag.test(std::memory_or...
Reading a memory address does not clear the cache line. Writing does. So in a modern computer, there is RAM, and there are multiple layers of cache "around" the CPU (they are called L1, L2 and L3 cache, but the important part is that they are layers, and the CPU is at the middle). In a multi-core system, often the out...
70,887,967
70,888,044
Pointer confusion causing "no matching function call for std::vector"?
I have a C++ class that has a datamember: private: std::vector<std::vector<int>> *edges; Then in my constructor, I do the following: //rows and columns are dynamically set in constructor edges = new vector<vector<int> >(rows*columns, vector<int>()); edges[0].push_back(1); When running my program, I get error: no ...
Here's an example of loading a 2d vector: std::vector<std::vector<int>> board; for (int row = 0; row < 4; ++row) { std::vector<int> row; for (int column = 0; column < 4; ++column) { row.push_back((row * 4) + column); } board.push_back(row); } The above code initializes a 2d array, 4x4, with a uni...
70,889,063
70,916,588
Should Lippincott functions be declared noexcept?
EDIT: Another way to ask this question, in perspective, is to ask: Should Lippincott functions "catch all"? Should Lippincott functions be declared noexcept?, does it matter? After all, a version of this function in which all exceptions are captured, by definition cannot produce an exception. However, in all the exam...
Not all catch (...) executions come from a C++ exception. It is typically advisable to rethrow the exception in any catch-all block. This would imply that lippincott should not be noexcept and also just not have the catch-all block. Specifically, in the ABI commonly used for C++ outside of Windows, forced unwinding may...
70,889,426
70,894,566
Windows Explorer integration look like in SolidWorks PDM
I looking for information about integration to Win Explorer in generally and about add custom column in particular. I'm already found some about Cloud Sync Engines, but it's only for Win 10 and newer, when i need to support Win7. I found some about Property Handlers, but it's can't be used for all file types at once. I...
Shell file browsers are composed of two parts, the browser (Tool bar, address bar, details pane and navigation tree) and the view (file list). There is very little you can customize in the browser. The view however can be anything you want when you implement a name space extension. To do this you must create a DLL that...
70,889,823
70,890,222
C++ std::find_if on iterator in reverse order
In the following code, is there an elegant way to find it_end? #include <iostream> #include <algorithm> #include <vector> #include <iterator> #include <type_traits> template <class Iterator, class U = typename std::iterator_traits<Iterator>::value_type> void process(Iterator begin, Iterator end) { // first nonzero...
use std::reverse_iterator. #include <iostream> #include <algorithm> #include <vector> #include <iterator> #include <type_traits> #include <list> template <class Iterator, class U = typename std::iterator_traits<Iterator>::value_type> void process(Iterator begin, Iterator end) { // first nonzero auto it_begin =...
70,890,463
70,917,303
Count of total Numbers With 3 set Bits only in a range
I recently come across a question , Question statement is like this : For given value of L and R, We have to find the count of number X, which have only three-set bits in it's binary representation such that "L ≤ X ≤ R". Expected Time Complexity: O(log(63^3)) Expected Auxiliary Space: O(1) Link - https://practice.geek...
The idea behind the code is fairly simple. We generate binary numbers by taking set bits. In this question three set bits have been asked, so we will make three variables and run three while loops. For example, numbers are asked --> 11 to 19 we take i = 1 j = 2, k = 4 and start the loops. We make temp as OR of - i j a...
70,890,728
70,891,490
Does fully specialized template function violate ODR with a regular function?
I just realized this snippet compiles safely without any warnings on g++ and clang. (given --std=c++14 --Wall) #include <iostream> template <typename T> void foo(const T& a, const T& b) { std::cout << "1. Template version called.\n"; } template <> void foo(const int& a, const int& b) { std::cout << "2. Templa...
Short answer: No it does not violate ODR and yes it is guaranteed to call the regular function, as long as you use an C++ standard compliant compiler. When calling foo, the compiler first makes a list of candidate functions, by looking up the name foo. On of the candidates is the regular function. It also goes through ...
70,890,802
70,890,851
how to allocate memory int pointer array inside a function and delete the allocated memory in main.cpp
I am trying to allocate memory to a pointer to an array using a non-template type argument. But, I am getting a run time error at delete ptr in the main function. #include <iostream> using namespace std; template<typename T, int SIZE> void createArray(T** arrPtr) { *arrPtr = new T[SIZE]; for (int i = 0; i < S...
Within the function instead of this statement (*arrPtr[i]) = i + 1; you need to write (*arrPtr )[i] = i + 1; And in this for loop the original pointer ptr is being changed. for (int i = 0; i < size; i++) std::cout << *(ptr++) << " "; As a result in this statement delete ptr; there is used an invalid address of ...
70,890,848
70,900,975
Singleton with read-only and write access
I have a class T and want a single global object of that class given by accessor functions like T const& read_singleton() and T& modify_singleton(). The object should be instantiated at first use of one of these functions by the default constructor of T and the usage of the functions should be thread-safe. What is a (g...
It's easy enough to write these functions: T& modify_singleton() { T static t{}; return t; } T const& read_singleton() { return modify_singleton(); } This is the Meyers singleton pattern and can also be implemented as static functions of T, in case you have control over its implementation and want to make...
70,892,070
70,893,017
Check if vector have no cube values of another element
I have the following algorithm, can somebody help me solve this? I just need an explanation. "A vector a[] with n integer elements is cube-repetition-free if no element is the cube of another element, i.e., there are no indices i,j such that a[i] = a[j]3 . Propose an O(n*log(n))-time algorithm in order to decide whethe...
O(n) solution: Add each element v[i] of the vector to a hash set. For each element v[i] check whether v[i] * v[i] * v[i] is in the set. O(n*logn) solution: Sort the vector v. Pointers start = 0 and end = 1. While end < n do the following: if v[start] * v[start] * v[start] equals v[end] then the vector is not cube-r...
70,892,352
70,896,742
CEF - Get html in std::string
Can someone please suggest an example for CEF - how to load an HTML page and put it in std::string? I looked at the documentation of the CEF, but unfortunately I could not figure out how to do it.
Here's the function you can use: https://bitbucket.org/chromiumembedded/cef/src/7b0bb931b19cb192b1a0cb1838e639a4ad9fb6e3/include/cef_frame.h#lines-123 #include "include/cef_frame.h" /// // Retrieve this frame's HTML source as a string sent to the specified // visitor. /// /*--cef()--*/ virtual void GetSource(CefRefPtr...
70,892,584
70,915,762
av_seek_frame seek only every 12th frames
I use ffmpeg video player in my graphic aps. Now I need to implement correct way to start video with specific frame (not only with first). I found good example here and at first thought, that it works for me perfectly: bool seek(uint64_t frame) { int64_t timeBase = (static_cast<int64_t>(_pContext->time_...
You need to seek to the previous key frame and decode until you have the frame that you want. You can't seek to ANY frame as the decoder will not decode properly the requested frame. You can find a detailed discussion and code here
70,893,366
70,896,068
ambiguous overload with ostream
I'm stuck with this why trying to overlap ostream of std::array in c++. (error: ambiguous overload for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream'} and 'const char [2]') here is my script: #include <bits/stdc++.h> using namespace std; template<typename T> ostream& operator <<(ostream& out...
This forces the overload to take only std::array, which should solve your ambiguous overload problem: template<typename T, std::size_t N> ostream& operator <<(ostream& out, const std::array<T, N> &arr) { bool pre = false; for(auto& i : arr) { if(pre) out << ' '; pre = true; out << i;...
70,893,993
70,896,507
Compile error when using QUERY like in documentaion described
I'm following the documentation and got an error during compilation following example: https://oatpp.io/docs/components/api-controller/#query-parameters-mapping Visual Studio 2017 is complaining about C2839:invalid return type 'type' for overloaded 'operator ->' and C2232 '->' : left operand has 'class-key' type, use '...
Documentation is outdated, solution is: OATPP_LOGD("Test", "age=%d", *age);