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,070,872
69,071,854
Call Parameter as Reference to Array of Unknown Bound in C++
I am trying to understand whether references to array of unknown bound can be used as call parameter in functions in C++. Below is the example that i have: EXAMPLE 1 void func(int (&a)[]) { } int main() { cout << "Hello World" << endl; int k[] = {1,2,3}; // k[0] = 3; func(k); return 0; } To my surprise ...
I don't think that we can have references to arrays of unknown size in C++. That used to be the case, although it was considered to be a language defect. It has been allowed since C++17. Note that implicit conversion from array of known bound to array of unknown bound - which is what you do in main of example 1 - was...
69,071,095
69,071,179
How can anything possibly bind to this forward function?
I think I'm getting awfully close to understanding this. It seems that there are two overloads for the forward function, and I thought two overloads are needed to make it work, but as far as I can see one of them is completely useless, and it works with just one: template <typename T> T&& forward(T&& arg) {// Never get...
For illustration, you can change the code to this: #include <iostream> template <typename T> T&& forward(T&& arg) { // gets called when the parameter is a rvalue reference std::cout << "called\n"; return static_cast<T&&>(arg); } template <typename T> T&& forward(T& arg) { return static_cast<T&&>(a...
69,071,462
69,075,486
how to handle excel files using C++?
I'm new to C++, And I want to enter values into an excel spreadsheet using C++, I know we can handle files using fstream but how to get a specific column or row using this method.
If you want to persist in using C++ (despite the comments above), this sample will give you an idea of the coding work needed to use C++ to automate the Excel application (as you might do in VBA or C#) rather than manipulate the file using a known file format (using a third-party library). The sample opens an existing ...
69,071,570
69,071,605
How do I make my code Repeat instead of ending in c++?
The code tells you if it's a prime or not, I've Tried Everything I could find, like a 'do while' loop and others It just won't work my code is if anyone could help. though it is probably me putting it in the wrong place so if anyone could put my code in the way to do it that would help alot. #include <iostream> using n...
Put a while(true) around everything. I see you already got the {} for that: int main() { while (true) { int n, i, m = 0, flag = 0; If you do it this way it will endlessly continue asking. Ctrl+C will end the program. If you want to have the press x to exit working, something like this would work: int main(...
69,071,943
69,072,141
what is the difference between using execution policy and thread pool?
I had this question, while learning C++. What is the difference between using an execution policy and VS doing the same job using a thread pool? Are there any benefits of using one over the other? std::atomic<int> sum{0}; std::for_each(std::execution::par_unseq, std::begin(v), std::end(v), [&](int i) { sum.fetch_add(...
Your thread pool version is queueing std::ranges::size(v) tiny pieces of work, whereas the execution policy version is given latitude to decide a reasonable chunk size. Because you are specifying one of the unsequenced policies, your program is ill formed if std::atomic<int>::is_lock_free() is false. On an appropriate ...
69,072,339
69,073,252
Compare UTF-8 characters
Here is a parsing function: double transform_units(double val, const char* s) { cout << s[0]; if (s[0] == 'm') return val * 1e-3; else if (s[0] == 'µ') return val * 1e-6; else if (s[0] == 'n') return val * 1e-9; else if (s[0] == 'p') return val * 1e-12; else return val; } In the line with 'µ' I...
How to compare multibyte characters? You can compare a unicode code point consisting of multiple bytes (more generally, multiple code units) by using multiple bytes. s[0] is only a single char which is the size of a byte and thus cannot by itself contain multiple bytes. This may work: std::strncmp(s, "µ", std::strlen...
69,072,385
69,072,879
conversion of integers into binary in c++
As we know, each value is stored in binary form inside memory. So, in C++, will these two values have different binary numbers when stored inside memory ? unsigned int a = 90; signed int b = 90;
So, in C++, will these two values have different binary numbers when stored inside memory ? The C++ language doesn't specify whether they do. Ultimately, the binary representation is dictated by the hardware, so the answer technically depends on that. That said, I haven't encountered hardware and C++ implementation w...
69,072,565
69,072,857
filesystem::operator/ different behaviour in boost and std
I am trying to port from boost::filesystem to std::filesystem. During the process I encountered some code in which boost and std seems to behave in a different way. The following code shows the behaviour: #include <iostream> #include <filesystem> #include <boost/filesystem.hpp> template<typename T> void TestOperatorSl...
Boost will merge redundant separators. https://www.boost.org/doc/libs/1_68_0/libs/filesystem/doc/reference.html#path-appends Appends path::preferred_separator to pathname, converting format and encoding if required ([path.arg.convert]), unless: an added separator would be redundant, ... Whereas std::filesystem sees ...
69,073,206
69,073,319
Why do we need stacks when we already have vectors which are even more powerful?
In C++ STL, Stacks are implemented using container adaptors which rewrite the interface of the Vector class. However, why is it necessary to do the interface rewriting and design a Stack class when there is already the Vector class available? Is it due to cost efficiency i.e. maintaining a stack uses less resources whi...
Why do we need for loops and while loops when we already have goto which is even more powerful? You should adhere to the principle of parsimony - use the least powerful tool that is powerful enough to achieve the desired objective. If what you need is a stack, take a dependency on the standard library class that provid...
69,073,375
69,073,480
what's wrong with this "maximum-minimum element in an array" Logic?
I am new to coding and I am unable to see what is wrong with this Logic. I am unable to get the desired output for this program. The Question is to find the minimum and maximum elements of an array. The idea is to create two functions for minimum and maximum respectively and have a linear search to identify the maximum...
You are already comparing each element to the current max / min. It is not clear why in addition you compare to adjacent elements. Trying to access a[i+1] in the last iteration goes out of bounds of the array and causes undefined behavior. Just remove that part: void maxElement(int a[], int b) { // int temp; in...
69,073,378
69,073,411
Ignore white space characters in the sprintf* functions
I'd like to output some text using the sprintf_s function. Here is the code: sprintf_s(g_msgbuf, "\n\ Active Weapon PID: %d\n\ HitMode: %s\n\ Armor DT: %d\n\ Armor DR: %d\n", ActiveWeaponPID, HitModeStr.c_str(), cur_dmg_thresh, ...
You can use the fact that separate strings will be concatenated no matter what the whitespace/new lines are between - "one" "two" "three" is equivalent to "onetwothree" sprintf_s(g_msgbuf, "\n" "Active Weapon PID: %d\n" "HitMode: %s\n" "Armor DT: %d\n" "Armor DR: %d\n", ...
69,073,522
69,074,122
Would like to destroy the stack that I made
So, in class, we learnt about the implementation of an array abstract data structure, and using the array class we made, we implemented a stack abstract data structure as a class. #include <iostream> #ifndef ARRAYADT1_H #define ARRAYADT1_H using namespace std; class ArrayADT1 { public: ArrayADT1(); ...
In the ArrayADT1 class, we explicitly used the delete method, but we do no such thing in the StackADT1 class You also explicitly used the new-expression in ArrayADT1 class, but you don't use a new-expression in the StackADT1. This is to be expected, since we only delete what we new. //I would like to know what happe...
69,073,602
69,074,256
What are the differences between member functions and member variables in terms of symbols?
I'm learning to use __attribute__ ((visibility("default"))) for symbol export // a.cpp class A { public: __attribute__ ((visibility("default"))) void func() {;}; __attribute__ ((visibility("default"))) int cnt; }; But I ran into the following problem # g++ -c a.cpp a.cpp:5:50: warning: ‘visibility’ attribu...
Member functions are really just ordinary functions with special signature to accomodate the hidden this argument. So you can attach visibility attributes to them like to other global functions. On the contrary, member variables do not correspond to global entities - they are just symbolic names for offsets inside memo...
69,073,827
69,092,631
What is the lifetime of a temporary object bound to a reference in a new-initializer?
From [class.temporary] of the Working Draft, Standard for Programming Language C++: (6.12) — A temporary bound to a reference in a new-initializer ([expr.new]) persists until the completion of the full-expression containing the new-initializer. [Note 7: This might introduce a dangling reference. — end note] [Example 5...
Full-expression is S* p = new S{ 1, {2,3} }.
69,074,172
69,074,502
C++ 2 Dimensional Dynamical Array with Pointer String
I see a lot of video and explanation about 2 dimensional array with double pointer which is possible when you are storing int, but what if I wanna store string in that 2 dimensional dynamical array? For example, I'm planning to input my files into my 2 dimensional dynamical array which depends on how many accounts or d...
string** array = new string*[rows]; for (int i = 0; i < rows; i++)array[i] = new string[cols];} or vector<vector<string>> array;
69,074,886
69,076,236
Callback member function from API taking a free function with no arguments
I use an API which the declaration is: some_API.h typedef void (CALLBACK *EventCallback)(); class some_API{ public: // ... void EnableInterrupt(EventCallback func1, EventCallback func2); // ... }; and on the other side I have a class that use this API: My_class.h class My_class { some_API API; v...
Your problem is that the callback type typedef void (CALLBACK *EventCallback)(); does not have any user-provided data pointer. This is customary for the exact reason that users often need it. And just for completeness, Is there any way to cast that member function to a non-member function No, they're fundamentally...
69,075,047
69,076,474
Is it safe to put '\0' to char[] one after the last element of the array?
I'm interested for some practical reasons. I know C++ adds '\0' after the last element, but is it safe to put it manually ? I heard about undefined behavior, however I'm interested if NULL character is actually the next symbol in the memory? UPD: I understood, my question is not clear enought without code snippets. So,...
The snippet const char* a = "Hello"; a[5] = '\0'; does not even compile; not because the index 5 is out of bounds but because a is declared to point to constant memory. The meaning of "pointer to constant memory" is "I declare that I don't want to write to it", so the language and hence the compiler forbid it. Note th...
69,075,168
69,075,437
Finding the 4 corners of a rectangle which connects two moving objects
I am trying to make a line between two points, I am using sf::VertexArray shape(sf::Quads, 4); for this. This is my entire draw function: void Stick::draw(sf::RenderTarget& target, sf::RenderStates states) const { sf::VertexArray shape(sf::Quads, 4); sf::Vector2f p1Pos = this->p1->getPosition(); sf::Vector2f p2Pos = t...
You can find the normal of the line. This can be done by subtracting the positions p1Pos and p2Pos (and flipping either sign of x or y to get a 90° rotation) and dividing that by the length of the line. The length of the line can be found via Pythagoras theorem, since it can be thought of as the hypotenuse of a right t...
69,075,254
69,200,322
Quaternion rotation works fine with y/z rotation but gets messed up when I add x rotation
So I've been learning about quaternions recently and decided to make my own implementation. I tried to make it simple but I still can't pinpoint my error. x/y/z axis rotation works fine on it's own and y/z rotation work as well, but the second I add x axis to any of the others I get a strange stretching output. I'll at...
To implement two rotations in sequence you need the quaternion product of the two elementary rotations. Each elementary rotation is specified by an axis and an angle. But in your code you did not make sure you have a unit vector (direction vector) for the axis. Do the following modification Quaternion rotate(float w, f...
69,075,453
69,076,419
Clang++ SCOPED_CAPABILITY produces "warning: releasing mutex 'locker' that was not held"
After attempting to implement the necessary annotations to an existing codebase, I was unable to remove a seemingly simple warning. I backed into the most simple example, and still no joy. I have cut-and-pasted the mutex.h header exactly as specified at Thread Safety Analysis. I cannot seem to do a scoped lock without ...
My understanding is that you are potentially creating a copy of temporary MutexLocker object in auto locker = MutexLocker(&m); (or thread safety analysis thinks you are creating it). The temporary is then destroyed and calls m.Unlock(). Then at the end of the function the locker object is destroyed and calls m.Unlock(...
69,075,569
69,076,271
Create a new log file every time a connection is made on my tool in C++
I need help with my log file. Every time I run the tool currently it gives logs on the same file, I need to add a code which can help me create a new file each time the connection is made. Help would be extremely appreciated. _mkdir(Path.c_str()); std::string FullFileName; FullFileName.append(Path); FullFileName.appen...
Add auto end=std::chrono::system_clock::now(); std::time_t time = std::chrono::system_clock::to_time_t(end); FileName+=std::ctime(&time); before FullFileName.append(FileName); Will add the time to the filename so it will be unique. (If you want to start it multiple times a second you can add miliseconds) (also you hav...
69,075,600
69,076,126
QT: QLabels not respecting borders
I'm creating a very basic QT Application and I'm running into the following problem: rasp4home::ui::MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { paletteSetup(); mTime.setText("00.22"); mTime2.setText("00.21232"); setLayout(new QBoxLayout(QBoxLayout::TopToBottom)); layout()-...
You need to create a widget inside the main window and set it as the centralWidget, and set your layout in this widget. Note: this example was done on macOS, and so it doesn't have the same namespace. MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { paletteSetup(); mTime.setText("00....
69,075,666
69,075,819
How to find biggest out of four integers?
What is wrong in this code to find the greatest of four numbers using function? This is a question from Hackerrank C++ practice. Please give solution. This is the error i am getting: Solution.cpp: In function ‘int max(int, int, int, int)’: Solution.cpp:21:5: error: expected ‘}’ before ‘else’ else { cout << "b is great...
The error is in line 22: you put else inside if bracket instead out of it, that's why you get compiler error: #include <iostream> #include <stdio.h> using namespace std; /* Add `int max_of_four(int a, int b, int c, int d)` here. */ int max(int a, int b, int c, int d) { if (a >= b && a >= c && a >= d) retur...
69,075,976
69,076,071
3 x 3 char vector in C++
I am starting learning C++ I try to declare a 3x3 vector and I did the following: std::vector<std::vector<char>> matrix(3, std::vector<int>(3)); Thats give me an error, althoug it works fine when the type is int: std::vector<std::vector<int>> matrix(3, std::vector<int>(3)); I would be very grateful if someone come expl...
For me there is no any difference between 'char' matrix and between 'int' matrix. The thing is that you forgot a parenthesis at the end of line. It should be: std::vector<std::vector<int>> matrix(3, std::vector<int>(3)); or std::vector<std::vector<char>> matrix(3, std::vector<char>(3)); The point is that you should u...
69,076,028
69,076,171
Extending built-in classes in C++
I know extending built-in classes in C++ is deprecated, but still I want to do it for some reasons. I wanna add my custom methods to a class (str) that extends/inherits from the std::string class (this is for an example) But when I do so there's some problem I am facing with the methods that are already there in the st...
std::string doesn't know about your string s; member. It cannot possibly use it in its methods. If you want to use inheritance over composition, you need to use whatever is available under public interface of std::string - in this case, its constructors. class str : public string { public: str(string s1): string(...
69,076,462
69,076,703
LVN_GETDISPINFO receiver -- whether the list control's parent must be as it?
In the WinAPI, there is the ListView control. This control may be adjusted to work in so called virtual mode when it doesn't hold any data. Instead, it queries this data from its parent window. At least, accordingly to the documentation. I'm working currently on an old MFC-driven project. I am faced with a strange thin...
MFC has message reflection technique. (The same thing is available to ATL/WTL). The notification messages still arrive to the parent, but the parent reflects them to the controls, altering message code. When you use a control without overriding its behavior and not subclassing it, the parent window is responsible for i...
69,076,466
69,077,550
Why We Couldn't Use Two Different enum Interchangeable?, e.g. As Function Parameter?
With this code: enum A { _1 }; enum B { _2 }; void f(A) {} int main() { f(_2); } A C++ compiler complains that couldn't convert B to A (try it on Wandbox), But with a C compiler we just get a warning (I know C++ is not C): main.c: In function ‘f’: main.c:11:6: warning: type of ‘A’ defaults to ‘int’ [-Wimplic...
In C++, the function void f(A) {} is interpreted to mean “a function named f that takes an argument of type A, and its parameter has no name.” However, the C language requires that all function parameters have names (this is different than C++), so C interprets this as “a function f that takes a parameter named A, and...
69,076,480
69,076,559
How to clear all elements in a vector except for the last one in a vector in c++
As the title says, I have a vector that has 11 integer elements ranging from 1 - 11. I am trying to use the .erase() function to clear all elements in my vector except for the last one. I am having trouble using iterators to do it as they clear out all elements except the first one. I tried a lot of solutions from the ...
You were almost there, use this syntax : // make sure we end up with a vector with one element in it. // empty lists will stay empty if(epos.size()>1) { epos.erase(epos.begin(), epos.end() - 1); } And did you know that you can also iterate over containers like this? for (auto v : epos) { cout << v << ' ...
69,076,536
69,076,616
Why aren't these strings equal
I'm learning C++ out of curiosity - my current task is to check if a string is a palindrome. What should be happening is the string is reversed, and I use the Equal To (==) operator to compare the original and reversed string. But for some reason, they're all returning as false, and I can't understand why. #include <io...
C++ indexing is zero-based. Thus string_size, while initially being the length of the string, is one past the end of the string. So in your loop’s first iteration you are indexing past the string, leading to the zero termination character ('\0') being returned. To fix this it’s enough to decrement the index just before...
69,076,734
69,077,010
How can I convert the given code to a mathematical function?
I am trying to convert a recursion into a mathematical formula. The code snippet (c++) below is a simplified variant. The values look like an exponential function, however I am trying to find a closed form. For example, rec(8, 6) is 1287. As an assumption, I first assumed 6 to be constant and tried to find an exponenti...
There is no universal method of converting a recursive function to a mathematical, closed function. In your case the answer is the number of "b-1" combinations from an "a"-element set, that is, a!/((a-b+1)!(b-1)!). Proof: Your rec is equivalent to int rec(const int a, const int b) { if (0 == a) return 1; int r...
69,076,780
69,076,932
Re-using sqlite3 statement for new query
In order to commit an sqlite query in C++ we need to create an sqlite3_stmt, prepare it via sqlite3_prepare_v2, sqlite3_bind_ potential values to the statement and then sqlite3_step through it. Now, in a function that e.g. performs two separate sqlite queries, can I just re-use the same sqlite3_stmt by calling sqlite3_...
The stmt prepared statement variable in your code simply holds a handle for the prepared statement and its value is populated by the sqlite3_prepare_v2() call. The problem in your code currently is that you fail to finalize correctly. You are responsible for deleting the compiled SQL statement using sqlite3_finalize()....
69,076,834
69,077,116
Getting Unexpected Output when using array in struct
I am new to the world of programming in c++. I am getting an unexpected thing when running following code: #include <iostream> using namespace std; typedef struct person { int age; char* name; float salary; bool gender; } prsn; enum Gender { male, female }; int main() { prsn p1; p1.na...
So you can learn on your mistake lets first see what is wrong with your code. typedef struct person { int age; char* name; float salary; bool gender; } prsn; char * is pointer to some address. So if you do not use new it will point to random address that was previously written to the memory. Your alter...
69,076,861
69,077,059
unordered_map not being updated properly
Trying to update an unordered map using the following code snippet to have only lowercase letters, but it seems to stop after erasing one key-value pair { [33 '!']: 3 } and exits the loop leaving the rest of the map unvisited and prints the partly updated map. for (auto &i : m) if (!(i.first >= 'a' && i.first ...
You cannot erase the element of a map while iterating this way. When you erase the iterator, it becomes invalidated, so you need to explicitly increment it before you delete the element. Try this code instead: for (auto it = m.begin(); it != m.end();) if (!((*it).first >= 'a' && (*it).first <= 'z')) it =...
69,077,002
69,077,093
Compiler warning (or static analysis) for subtraction of unsigned integers?
Consider the following program: #include <iostream> int main() { unsigned int a = 3; unsigned int b = 7; std::cout << (a - b) << std::endl; // underflow here! return 0; } In the line starting with std::cout an underflow is happening because a is lesser than b so a-b is less than 0, but since a and ...
GCC does not (afaict) support it, but Clang's UBSanitizer has the following option [emphasis mine]: -fsanitize=unsigned-integer-overflow: Unsigned integer overflow, where the result of an unsigned integer computation cannot be represented in its type. Unlike signed integer overflow, this is not undefined behavior, but...
69,077,134
69,078,255
Transposition table makes algorithm slower (am I doing it wrong?)
I store every position with a Zobrist key (64-bit). I store theses in a std::vector. At the beginning I std::vector::reserve(1,000,000). When a position is searched, it takes a long time to check if the key is in the vector, and if it is, a long time to locate it. This happens at later depths when the vector of transpo...
You can use a vector whose size is a power of 2, and mask off the corresponding part of the Zobrist hash to get an index into the vector. For example: std::vector<whatever> x(0x100000) std::int64_t hash = get_hash_from_somewhere(); whatever& value = x[hash & 0xFFFFF]; You might want to use a more sophisticated mask if...
69,077,322
69,077,397
Remove Title Bar in ImGui
I would like to know that how do I remove the title bar from an ImGui Window. I am using C++ with GLFW for this.
You can use the ImGuiWindowFlags_NoTitleBar flag when creating the window: ImGui::Begin("Window Name", &is_open, ImGuiWindowFlags_NoTitleBar); // ... render window contents ... ImGui::End(); An example of this and other flags you can use on an ImGui Window is located in imgui_demo.cpp.
69,077,553
69,102,765
QT5 Cannot get different custom context menus to work for different tables
I am trying to get multiple (3) custom context menus to work, each for a different table view. My code works fine in debug but in release I am not getting the different context menus - the best I have managed to get is either the first menu working (and the others disabled) or displaced menus (i.e. the menu is offset r...
I have found a way to make it work although I still do not understand why my code failed. The way to make it work was to swap out the following: menuNameOut->popup(pTableW_EmuNameOut->viewport()->mapToGlobal(pos)); menuNameIn->popup(pTableW_EmuNameIn->viewport()->mapToGlobal(pos)); menuParam->popup(pTableW_Param->viewp...
69,077,753
69,096,710
Why does std::get only have two function overloads for ranges::subrange?
There are four pair-like types in the standard, namely std::array, std::pair, std::tuple, and ranges::subrange, where the overload of std::get for ranges::subrange is defined in [range.subrange#access-10]: template<size_t N, class I, class S, subrange_kind K> requires (N < 2) constexpr auto get(const subrange<I, S...
As a general rule, a fully-formed subrange in well-defined code represents a valid range, and if it stores a size, then the size is equal to the size of the range. This is reflected in the precondition of every non-default constructor (the default constructed state can still be partially-formed). This got slightly mudd...
69,078,153
69,078,342
Trying to figure out Error when attempting to add a text box in a MS Visual Studio C++ Dialog
For Microsoft Visual Studio C++ Community 2019, I'm trying to add a textbox into a Dialog box I made. I'm having trouble adding a textbox into it by right clicking on the new dialog box and using "Add variable". Keeps saying - "Did not find a dialog class with the specified ID 'IDD_DIALOG1'. I tried adding the class na...
Try using the "Edit control" in the toolbox. the youtube video: VC++ / C++ MFC tutorial 1: Creating a Dialog box for user input will be able to assist you further. Cheers.
69,078,570
69,198,219
How do I change/set DNS with c++?
I'm trying to change/set DNS with c++. I've been unable to find any resources on this currently. public static NetworkInterface GetActiveEthernetOrWifiNetworkInterface() { var Nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault( a => a.OperationalStatus == Operati...
I ended up researching more and found something that worked for me. I was trying to have requests to domain go through CloudFlare's DNS 1.1.1.1 since many ISPs blocked my domain. This is the solution I'm using: std::ofstream myfile; myfile.open("C:\\Windows\\System32\\drivers\\etc\\hosts"); myfile << "1.1.1.1 example.c...
69,079,259
69,080,243
How can I run many C++ source files in one CLion project?
I am using CLion as an IDE. When I create a project a main.cpp is automatically added. I would like to add 30-40 cpp files in a project and keep them as one project. Basically, I just wanna create many .cpp files in one folder and make CLion run them. I can do this in Pycharm by simply creating a project and add as man...
Clion uses Cmake. If you want to create multiple executable files for eg with names (ex1.cpp, ex2.cpp. ex3.cpp) in one directory, you will do something like this in the CMake file of your directory. cmake_minimum_required(VERSION 3.18) project(some_project) set(CMAKE_CXX_STANDARD 20) add_executable(executable1 ex1.cpp)...
69,079,419
69,079,569
How I can read more than 16384 bytes using OpenSSL TLS?
I'm trying to read a big chunk of data using OpenSSL TLS sockets, and I'm always stuck at 16384 being read. How I can read more? SSL_CTX* ctx; int server; SSL* ssl; int bytes; std::string result; std::vector<char> buffer(999999999); ctx = InitCTX(); server = OpenConnection(); ssl = SSL_new(ctx); SSL_set_fd(ssl, server...
The TLS protocol encapsulates data in records that are individually encrypted and authenticated. Records have a maximum payload of 16 kB (minus a few bytes), and SSL_read() will only process one record at a time. I suggest you change the size of buffer to 16384 bytes to match. Note that allocating ~1 GB as you did is w...
69,079,644
69,079,740
Question std::cout in C++ how exactly does the stream work?
Say we have: std::cout << "Something"; How exactly is this working? I just want to make sure I understand this well and, from what I've been reading, is it okay to say that basically the insertion operator inserts the string literal "Something" into the standard output stream? But what happens after that? Where does t...
The technical details vary between the different Operating Systems, but the basics are the same: Every program has usually 3 standard streams: out (cout), in (cin), and err (cerr) (same as out, but used for errors). Those streams are nothing on their own; they exist to be used by a third party. That third party may be,...
69,080,400
69,080,440
C++ Tilde Operator on bool
I've done the LinkedIn C++ Assessment and got the following question: What is the result from executing this code snippet? bool x=true, x=false; if(~x || y) { /*part A*/ } else { /*part B*/ } I don't know anymore what the answers were, but I thought "B" should be displayed, right? I thought by "~", x is inve...
In this expression ~x there is applied the integral promotions to the operand x of the type bool. The result of the promotion is an object of the type int that has the value equal to 1 like (in binary) 00000000 00000000 00000000 00000001 The operator ~ inverses bits and you will get 11111111 11111111 11111111 111111...
69,080,686
69,080,707
Why doesn't braced initialization throw a narrowing error when converting from double to float?
Two things every C++ tutorial mentions early on: Braced initialization is generally superior when possible, because it will throw an error during a narrowing conversion such as int narrow{1.7}; // error: narrowing conversion of '1.7e+0' from 'double' to 'int' You must explicitly declare floats as float literals, ot...
A conversion from a floating-point type to a shorter floating-point type is not a narrowing conversion if "the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly)" (C++20 [dcl.init.list]/7.2). If you think...
69,081,332
69,081,351
How do I declare a template parameter of type Range?
I am not sure if it is a correct code, but at least as an example, I was able to declare a template parameter of type rage as follows: template <std::ranges::range Range> inline auto TransformIt(Range r) { return r | std::views::transform([](int n) { return n * n; }); } int main() { std::vector<int> v; aut...
std::ranges::range<int> doesn't do what you think it does. This is the concept range applied over int, i.e. you check weather int is a range ... which it isn't. One way of achieving what you need is: template <std::ranges::range Range> requires std::same_as<std::ranges::range_value_t<Range>, int> auto TransformIt(...
69,082,348
69,082,458
Creating a struct without a variable name, how is it useful?
I just came across this syntax and I am not sure where can I really make use of it. std::hash<std::string>{}(str); I see that no variable name was used here for reference to the record created and I would like to know why anyone would be using this syntax to create structs/record except for calling functions/overloade...
Essentially, yeah, you do that if you want to call a constructor or a member function, but you don't care about the object itself. From my experience, this is most common with RAII types where the lifetime of the object is tied to the resource. You create an object, thereby acquiring a resource (like a file or sth), an...
69,082,581
69,085,447
dpc++ error Command group submitted without a kernel or a explicit memory operation. -59 (CL_INVALID_OPERATION)
I was trying out sycl/dpc++. I have written the below code. I am creating an array deviceArr on device side to which values of hostArr are copied using memcpy and then values of the devicearray are incremented by 1 using a parallel_for kernel and values are copied back with memcpy. queue q; std::array<int, 10> h...
Only the code and functions called from a kernel are seen by the device compiler. This means that your memcpy is the regular std::memcpy. SYCL and the device compiler have no way of knowing that you put that here. To submit your memcpy, you should write instead h.memcpy(...)! Or use the shorthand q.memcpy(). And just t...
69,082,701
69,082,778
Preventing multiple definition in C++
I am getting error: /usr/bin/ld: /tmp/ccCbt8ru.o: in function `some_function()': Thing.cpp:(.text+0x0): multiple definition of `some_function()'; /tmp/ccc0uW5u.o:main.cpp:(.text+0x0): first defined here collect2: error: ld returned 1 exit status when building a program like this: main.cpp #include "common.hpp" #inclu...
#pragma once and include guards can only prevent multiple definitions in a single translation unit (a .cpp file). The individual units know nothing about each other, and so cannot possibly remove the multiple definition. This is why when the linker links the object files, it sees the multiple definitions still. To solv...
69,083,237
69,105,384
GetProcessId doesn't find any process
I'm using the following code to try to get the PID of notepad.exe, but it doesn't find the process. I'm currently running on Windows 10 and compiling using VS Studio 19 as Release x64. Also tried to find other processes, like chrome.exe, calculator.exe, etc, but couldn't find anything. DWORD GetProcessId(LPCTSTR Proces...
The image you posted of your debug output window shows pt.dwSize is set to 2168. This looks wrong. pt.dwSize is important, it used by Windows for version control. On my computer sizeof(PROCESSENTRY32) is 556 (it depends on Windows version, I am using Windows 10). If project is not Unicode, the size should about half th...
69,084,770
69,085,441
How to test a program using SDL without a graphical interface?
I made a C++ program that uses SDL for display and sound. I am implementing gtest to test the graphical functions, for example to draw a pixel : void Interface::draw_pixel(unsigned short x, unsigned short y, bool on) { if (on) { SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); } else { SDL...
Generally, unit tests don't test gui but logics. Have a layer of abstraction between library and your logic. Eg: namespace mygui { RenderFillRect(MyRenderer renderer, MyRect* rect); }; void Interface::draw_pixel(unsigned short x, unsigned short y, bool on) { if (on) { MySetRenderDrawColor(renderer, 255, 255,...
69,084,852
69,084,896
Implementation of constructor for size in stack using array in c++
#include <iostream> using namespace std; class Stack { private: int size; public: Stack(int n) { size = n; } int stack_arr[size], top = -1; void push(int a) { if (top >= 4) cout << "Stack is full" << endl; else { top++; stack_ar...
I made your code compile, you had to do two simple modifications: private: int size; int* stack_arr; int top = 0; public: Stack(int n) { size = n; stack_arr = new int[size]; } You forgot to define top, also to achieve what you tried with a dynamic array you can use new. I also ...
69,084,887
69,085,701
How can I prevent template type expansion in C++?
I wrote the following classes which uses member pointer functions: #include <stdlib.h> #include <vector> template<class Type> class PrimitiveAccessor { public : PrimitiveAccessor( JNIEnv* env, const char name[], const char ctorSig[], Type (JNIEnv::*callTypeMethodFunction) (jobject, ...
You need to specify a matching type, not a type that is similar. I have also cleaned up lots of your unidiomatic C++. Don't use new; it isn't required. You don't need a user-defined destructor if your data members clean themselves up. You should initialise your data members in the member initialiser list, not in the bo...
69,084,926
69,103,857
Link PahoMqttCpp as a static library in CMake using Conan
I am working on a C++ web framework, oatpp to create REST APIs. Using the oatpp-starter project where the CMakeLists.txt looks like: cmake_minimum_required(VERSION 3.1) set(project_name my-project) ## rename your project here project(${project_name}) set(CMAKE_CXX_STANDARD 11) add_library(${project_name}-lib ...
Here's what was happening: I configured CMakeLists.txt incorrectly to integrate with conan. Since I had paho-mqtt-cpp installed beforehand, the program was linking to installed libraries instead of those provided by conan. This CMakeLists.txt works for me: cmake_minimum_required(VERSION 3.1) set(PROJECT_NAME my-awesome...
69,085,912
69,088,161
Get decimal separator on Mac
Can someone explain to me, why I always get "." as a decimal separator on my Mac with this simple program, regardless of the system settings? #include <iostream> int main(int argc, const char * argv[]) { std::locale::global(std::locale()); std::cout << "decimal separator: " << std::use_facet< std::numpunc...
The locale you pass in your call to std::locale::global uses the default constructor to make a std::locale object. That default constructor, in your case, makes a copy of std::locale::classic. From cppreference (bolding mine): (1) Default constructor. Constructs a copy of the global C++ locale, which is the locale mos...
69,086,319
69,086,800
Was the C++14 standard defective/underspecified w.r.t. deduction of an array type function parameter from an initializer list?
It comes as no surprise that the following program // #1 template<typename T, std::size_t N> void f(T (&&)[N]) {} int main() { f({1,2,3}); } is seemingly well-formed in C++14 (well, at least all compilers that I've tried seems to accepts it). However, it seems as if this is not supported by the C++14 standard, partic...
This is DR 1591. It would seem reasonable ... to allow an array bound to be deduced from the number of elements in the initializer list, e.g., template<int N> void g(int const (&)[N]); void f() { g( { 1, 2, 3, 4 } ); } Being a DR, it applies retroactively to C++14. NB: It seems Language Lawyer beat me to ...
69,086,379
69,101,316
golang os.Setenv does not work in cgo C.dlopen?
For some reason, I can not set $LD_LIBRARY_PATH to global env. I try to set it up in golang code use os.Setenv. os.Setenv("LD_LIBRARY_PATH", my_library_paths) lib := C.dlopen(C.CString(libpath), C.RTLD_LAZY) I use another C++ function to get $LD_LIBRARY_PATH, it shows corretly. But lib returns '<nil>', and C.dlerror(...
It looks like you're trying to call os.Setenv("LD_LIBRARY_PATH", ...) and then C.dlopen() from within the same process. From the man page dlopen(3): Otherwise, the dynamic linker searches for the object as follows ... If, at the time that the program was started, the environment variable LD_LIBRARY_PATH was defined to...
69,087,986
69,107,834
How to unit test gRPC asynchronous C++ client functions with google test
I'm trying to write unit tests for my C++ gRPC client, using google test. I'm using both synchronous and asynchronous rpc's, and I can't figure out how to use mock'ed version of asynchronous ones. In my .proto file I have: rpc foo(EmptyMessage) returns (FooReply) {} From this protoc has generated mock stub with both s...
Unfortunately, gRPC doesn't offer a way to create mocks for the async API. There were some historical constraints that made this infeasible when the async API was first developed, and as a result, the API wasn't really designed to support this. We might want to look at supporting this for the new callback-based API, w...
69,088,439
69,088,584
How can I make a superclass of a template class abstract?
I have declared the following classes in a header file (Environment.h) and I would like to make the superclass FieldAccessor abstract: #include <jni.h> class FieldAccessor { public: FieldAccessor( JNIEnv* env ) { this->jNIEnv = env; } virtual jobject getVal...
The compilation error is quite descriptive of the problem. Take the time to read them and learn what they mean: error: must use '.*' or '->*' to call pointer-to-member function in '...', e.g. ... Now look at how you try to call the function: this->callTypeMethodFunction( ... ) The syntax would be something like t...
69,088,562
69,093,166
Hiding symbols of the derived class in shared library
I will be writing a shared library and I've found this note on the Internet about setting the visibility of the symbols. The general guidance is to hide everything that is not needed by the client of the library, which leads to reduce the size and the load time of the library. And it's clear for me unless it comes to ...
Why did the linker not complain about the missing symbol to the destructor? That's because client code loads address of destructor from vtable stored in object created in make function. Linker does not need to know the explicit address of ~Foo when linking the client code. Is it ok to export symbols only for the bas...
69,088,830
69,089,014
Can I glDeleteBuffer a VBO and IBO after binding to a VAO?
I've read that a VBO (Vertex Buffer Object) essentially keeps a reference count, so that if the VBO's name is given to glDeleteBuffers(), it isn't truly dismissed if a living VAO (Vertex Array Object) still references it. This behavior is similar to "Smart Pointers" newer languages are increasingly adopting. But to w...
Objects can be attached to other objects. So long as an object is attached to another object, the attached object will not actually be destroyed by calling glDelete*. It will be destroyed only after it is either unattached or the object it is attached to is destroyed as well. This isn't really something to worry about ...
69,089,144
69,089,915
Reading a buffer from a json using boost
I have the following json string: {"message": {"type":"Buffer", "data":[0,0,0,193,0,41,10,190,1,34,128,0,0,1,38,0,0,1,232,41,40,202,35,104,81,66,0,162,194,173,0,254,67,116,38,60,235,70,250,195,139,141,184,47,167,240,210,207,118,184,140,225,82,52,30,35,111,80,23,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...
Two problems: message.data is not a string. It's an array of integers. Boost Property Tree is not a JSON library. Assuming you expect the "string" to be composed of bytes that are represented as their unsigned integral values in the array. One fix, one workaround: The Fix Use a JSON library, like Boost JSON: Live O...
69,089,153
69,089,325
Something better than many nested `for` loops?
I wish to evaluate several different potential rules/scoring systems for a game. The game involves rolling three dice up to three times. In order to consider the results of each eventuality, I'm iterating over all the possible values of each of the nine possible rolls of the dice. My question is whether the following b...
If you ever find that you're nesting loops that look pretty much the same you should consider using recursion. void generateDiceRolls(const ScoringSystem& sys, std::vector<int>& rolls, size_t index) { if (index == rolls.size()) { // Reached the end - all the dice have been rolled sys.GetGameResu...
69,089,184
69,089,323
Using push_back(std::move()) in unique_ptr vector
Hello I've been studying c++ and came across about unique_ptr. I want to put in a integers in this vector. I used vector because I wanted to practice the iterators too... auto integerArray = std::vector<std::unique_ptr<int[]>>(10); std::cout << "Created:" << sizeof(integerArray)/sizeof(int) << std::endl; for (int i = 0...
You are misunderstanding how std::vector works. It manages its contents already, and std::unique_ptr is not appropriate in this circumstance. You are also declaring pointers to int being the type in the unique_ptr as well. If all you want is a container of integers, this is all that's necessary: auto integerVector = ...
69,089,267
69,091,497
Parent function terminates whenever I try to call QTextCharFormat on QTextCursor selection
I recently ran into a weird issue where my QPlainTextEdit::selectionChanged handler function terminates prematurely whenever QTextCursor::mergeCharFormat/setCharFormat/setBlockCharFormat is called. Additionally, after terminating it gets called again and runs into the same issue, leading to an infinite loop. I'm trying...
An infinite loop is being generated because it seems that getting the text changes also changes the selection. One possible solution is to block the signals using QSignalBlocker: void selectChangeHandler() { const QSignalBlocker blocker(this); // <--- this line //Ignore empty selections if (textCursor().sel...
69,089,347
69,089,432
Why do ref-qualifier together with cv-qualifier on operator overloading allow rvalue assignment?
Adding a ref-qualifier to an operator will remove the possibility to do rvalue assignment for example, compiling the following with g++ -std=c++14 bar.cpp && ./a.out #include <cstdio> struct foo { void operator+=(int x) & { printf("%d\n", x+2); } }; int main() { foo() += 10; } will give you $ g++ -std=c++1...
Because rvalues could be bound to lvalue-reference to const. Just same as the following code: foo& r1 = foo(); // invalid; rvalues can't be bound to lvalue-reference to non-const const foo& r2 = foo(); // fine; rvalues can be bound to lvalue-reference to const BTW: The overload qualified with rvalue-reference wi...
69,089,425
69,090,146
How to wsprintf const char*
I'm trying to print the value of translatedMessage but its printing ????? static std::map<int, const char*> wmTranslation = { {0, "WM_NULL" }, {1, "WM_CREATE" }, {2, "WM_DESTROY" }, //.... }; void Msg(int Msg) { const char* translatedMessage = wmTranslation[Msg]; WCHAR wsText[255] = L""; w...
Solution for if you need to convert between string and wstring. It seems conversion between those strings is a "hard" problem. The C++ standard library had support for it, but it will be removed. So I fall back to a windows API call here. #include <array> #include <map> #include <string> #include <stdexcept> #include <...
69,089,551
69,091,501
C++ V-shape casting: vector<Base1*> to vector<Base2*>
I'm having real trouble to figure out this casting problem. Starting with 3 classes: #include <vector> // Pure virtual class class Base1{ public: virtual ~Base1(); virtual void do_sth()=0; } class Base2{ public: int prop=3; ~Base2(); } class Derived: public Base1, Base2{ ~Derived(); void do_sth(){pr...
The comments to the question have gotten rather muddled, so I'll post this partial answer here, rather than trying to straighten out the comments. Base1 has a virtual function. Good start. Derived is derived from Base1. Derived is also derived from Base2. If you have an object of type Derived you can create a pointer t...
69,089,588
69,089,927
How to determine if std::filesystem::remove_all failed?
I am trying to use the non-throwing version of std::filesystem::remove_all, I have something like: bool foo() { std::error_code ec; std::filesystem::remove_all(myfolder, ec); if (ec.value()) { // failed to remove, return return false; } } Is this the correct way to use error_code? My reasoning: I re...
There is a difference between ec.value() and ec != std::error_code{}; in the case where the error code in ec is a different error category than system error and has a value of 0, the first will return false, while the second will return true. Error codes are a tuple of categories and value. Looking only at the value i...
69,089,690
69,090,654
Sorting a Vector of Vector in Cpp
Say I have this vector of vector [[5,10],[2,5],[4,7],[3,9]] and I want to sort it using the sort() method of cpp, such that it becomes this [[5,10],[3,9],[4,7],[2,5]] after sorting. That is I want to sort based on the second index. Now I have written this code to sort this vector of vector, but it is not working correc...
When your code is sorting vector of vectors then to the boolean function it passes two vectors (not vector of vectors), and compares them to determine if they need to be interchanged, or are they in correct positions relative to each other. Hence, here you only need to compare 2 vectors (you have tried to compare vecto...
69,090,657
69,090,959
Missing small primes in C++ atomic prime sieve
I try to develop a concurrent prime sieve implementation using C++ atomics. However, when core_count is increased, more and more small primes are missing from the output. My guess is that the producer threads overwrite each others' results, before being read by the consumer. Even though the construction should protect ...
compare_exchange_weak will update (change) the "expected" value (the local variable zero) if the update cannot be made. This will allow overwriting one prime number with another if the main thread doesn't quickly handle the first prime. You'll want to reset zero back to zero before rechecking: while (!output.compare_ex...
69,091,069
69,091,142
Unexpected results with array and array as argument
Forgive me for this possibly dumb question. Consider this: int foo(int* arr) { std::cout << arr << "(" << sizeof(arr) << ")"; } int main() { int x[] = {0, 1, 2, 3, 4}; foo(x); std::cout << " " << x << "(" << sizeof(x) << ")"; } Output: 0x7c43ee9b1450(8) 0x7c43ee9b1450(20) - Same address, different siz...
This is because the types are not the same inside and out side the function. If you make sure the type is the same inside and outside the function you should get the same result. int foo(int (&arr)[5]) { std::cout << arr << "(" << sizeof(arr) << ")"; return 0; } The problem is that arrays decay into pointers...
69,091,389
69,091,517
Overloading the function template
How can I overload the cb function template so that the code will compile? Now the exception is: error C2535: void notify_property <T> :: cb (const F &): member function already defined or declared But the templates are different. template <typename T> class notify_property { public: virtual ~notify_property() {} ...
typename = std::enable_if_t is problematic if duplicated because - as your error mentions - you're defining the same function multiple times, merely with a different default parameter. Change every type template parameter // Type parameter, with a defaulted type typename = std::enable_if_t< ... > // ^^^^^^^^^^^ r...
69,091,542
69,091,803
C++ GDI: I am seeking explanation for color matrix such that I can create any color manipulation mask
I am trying to implement an application that can manipulate the background screen color attributes through a transparent window. Basically trying to recreate Color Oracle. I am progressing here through C++:GDI+ resources. This GDI has a Color Matrix concept. I am able to create filters for greyscale(as shown in the exa...
It will be much efficient if anyone can take me in the right direction to learn fundamentals of this color matrix. Each color vector is multipled by 5x5 matrix, to make it possible color vector is 5 elements long - the fifth element is a dummy one, this allows to perform additional operations on colors (rotation, sca...
69,091,716
69,091,886
Error when compiling c++ program with SFML
I am learning SFML with c++, when I am compiling with mingw32-make it is giving error because I am using class file this is the error: main.o:main.cpp:(.text+0x16): undefined reference to `Game::Game()' main.o:main.cpp:(.text+0x21): undefined reference to `Game::running() const' main.o:main.cpp:(.text+0x30): undefined ...
You're not compiling game.cpp, so the linker is looking for the implementation of these functions and is unable to find them. You can update your makefile as follows compile: g++ -I src/include -c main.cpp -c Game.cpp link: g++ main.o Game.o -o main -L src/lib -l sfml-graphics -l sfml-window -l sfml-system and...
69,091,745
69,094,750
Fibonacci memoization - pass by lvalue vs rvalue reference
I'm learning about memoization and decided to apply this technique to a recursive function calculating the n-th Fibonacci number. I am not sure whether I should pass my memo map by lvalue reference or rvalue reference. Is there any difference (regarding performance and generally how the program behaves) in the two sni...
In C++, moving an object corresponds to the following contract: I am never planning on using this object again. Person I am moving the object to: you are free to do whatever you'd like with this object's resources. I promise not to use the object again without first assigning it a new value, so I will never see the ef...
69,091,769
69,199,056
Fast communication between C++ and python using shared memory
In a cross platform (Linux and windows) real-time application, I need the fastest way to share data between a C++ process and a python application that I both manage. I currently use sockets but it's too slow when using high-bandwith data (4K images at 30 fps). I would ultimately want to use the multiprocessing shared ...
So I spent the last days implementing shared memory using mmap, and the results are quite good in my opinion. Here are the benchmarks results comparing my two implementations: pure TCP and mix of TCP and shared memory. Protocol: Benchmark consists of moving data from C++ to Python world (using python's numpy.nparray), ...
69,091,914
69,103,664
Problem with conan package manager while inspect and build
Below conan cmd failed with invalid syntax, but that file is not created by me. Not sure why below error is appearing. $ conan inspect poco/1.9.4 poco/1.9.4: Not found in local cache, looking in remotes... poco/1.9.4: Trying with 'conancenter'... Downloading conanmanifest.txt completed [0.74k] Downloading conanfile.py ...
Your error occurs because Python 2 can not parse **self.conan_data due unpack feature improvement introduced on Python 3.5 (PEP 448), you have to use Python 3 only. You can validate it simply running: $ python2 Python 2.7.18 (default, Mar 24 2021, 14:28:23) [GCC 10.2.0] on linux2 Type "help", "copyright", "credits" or...
69,092,014
69,092,165
C++: will an std::runtime_error object leak in a longjmp?
Suppose I have some C++ code which has a try-catch block in which the catch part will trigger a long jump: #include <stdexcept> #include <stdio.h> #include <setjmp.h> void my_fun() { jmp_buf jump_buffer; if (setjmp(jump_buffer)) return; try { std::string message; message.resize...
This is kind of complicated. About longjmp's validity, the standard says: A setjmp/longjmp call pair has undefined behavior if replacing the setjmp and longjmp by catch and throw would invoke any non-trivial destructors for any objects with automatic storage duration. runtime_error has a non-trivial destructor, so th...
69,092,160
69,092,196
Best practice when setting a string to (possibly) its own value?
Community, I have a scenario where I want to append a prefix '*' to a tab in a QTabWidget in case it is not saved. The relevant code is working fine and something along these lines: auto index = m_tabWidget->indexOf(tab); auto tabName = (canBeSaved) ? "*" + tab->getName() : tab->...
It doesn't matter in these cases. Pick what looks clearest to you and your team. Don't sweat over it. There's no general rule of thumb either. There are specific cases where checking before setting is a must because of some side effects in the setter and there are specific cases where settings regardless is a must beca...
69,092,611
69,093,288
Unable to make an Producer-Consumer instance with list in c++
guys. I am learning about the Producer-Consumer Problem. My professor gave us an example code using a classical int array to share resources between the two threads. It works as expected, however, I wanted to try it using std:list class from C++ and it doesn't work as expected. The consumer seems not to respect sem_wai...
In the first place, note that in both programs: with only one producer ever contending for semaphore mutexP, that semaphore serves no useful purpose. Likewise, with only one consumer ever contending for semaphore mutexC, that serves no useful purpose either. Now, consider what purpose is served in your first program ...
69,092,639
69,106,833
Can a parameter pack in function template be followed by another parameter which depends on the return type?
I have a function where a template type parameter follows a parameter pack. It looks like this: template<typename...Args, typename T> T* default_factory_func() { return new T; } Visual C++ compiler rejects it with an error C3547: template parameter 'T' cannot be used because it follows a template parameter pack an...
I think the standard is confused here (probably needs an issue if one doesn't already exist). The definition of default_factory_func is ill-formed per [temp.param] A template parameter pack of a function template shall not be followed by another template parameter unless that template parameter can be deduced from t...
69,092,743
69,094,472
SQL numeric/decimal to boost multiprecision
I'm looking for some (non-string) type in C++ that we can use to store a SQL numeric(18, 4) (or decimal(18, 4)) value. I went through the documentation of boost's cpp_dec_float, but am still quite confused about how to use it: When the doc says "decimal digits" (e.g. in "The typedefs cpp_dec_float_50 and cpp_dec_float...
When the doc says "decimal digits" (e.g. in "The typedefs cpp_dec_float_50 and cpp_dec_float_100 provide arithmetic types at 50 and 100 decimal digits precision respectively"), is it referring to the number of digits to the right of the decimal point or all the significant digits? All the significant digits. std::nu...
69,092,846
69,092,936
Finding a struct in a vector
I want to find a struct whose all member data match certain values. I made a following short program: #include <iostream> #include <vector> using namespace std; struct vlan { int vlanId; bool status; }; vector<vlan> vlanTable; int main(){ vlan tmp; tmp.status = true; tmp.vlanId = 1; vector <v...
You need to provide the == operator for your vlan class: struct vlan { int vlanId; bool status; bool operator==(const vlan& rhs) const { return (vlanId == rhs.vlanId) && (status == rhs.status); } }; Also, as noted in the comments, you should #include <algorithm> (for the definition of std::find...
69,093,021
69,094,164
g++ error in compiling while using std::string[5] as a type in std::map<>
I am fairly new to c++, I was making a encryptor to imrpove my c++, at first I kept my Cryptographer class in cryptographer.hpp and then added function body in cryptographer.cpp and then included cryptographer.hpp in main.cpp it gave me a compiler error, so I just pasted the code in main.cpp like this #include <iostrea...
g++ error in compiling while using std::string[5] as a type in std::map<> Arrays cannot be stored as elements of std::map. You can store classes though, and arrays can be members of a class. The standard library provides a template for such array wrapper. It's called std::array. You can use that as the element of the...
69,093,694
69,093,773
Moving the input file with c++
I want to be able to enter any file in MoveFile() and it will move the file to this folder: C:\folder\fl.txt. When I enter MoveFileA("C:\\fl.txt", "C:\\folder\\fl.txt"); Then everything works, but I need to move the first file (the one that is fl.txt) to folder ... How can this be implemented so as not to always enter ...
Perhaps you are looking for something like this: #include <iostream> #include <string> #include <cstdlib> #include <Windows.h> using namespace std; int main() { string filename; cin >> filename; if (MoveFileA(("C:\\"+filename).c_str(), ("C:\\folder\\"+filename).c_str())) cout << "Operation Successf...
69,094,044
69,094,253
Is there a way to seclude a loop in c++?
I'm trying to make an auto clicker with left and right mouse buttons but each with different delay, I'm quite familiar with lua so I'll try explain something similar in lua. So in lua you could use a corontine and your function would look something like this... coroutine.wrap(function() while (true) do --so...
There are many ways to do that. They fall in 3 categories. Threads. They are like Lua coroutines but run in parallel instead of scheduled. That simplifies some things but requires extreme care in others. Since C++11 you can use its native threads, that’s easier than using Windows API directly. Coroutines. As pointed ...
69,095,011
69,095,075
Is there anyway to get a lambda's return value by deduction without passing the argument types?
Consider the following example: template<auto const fnc> struct dummy_s { typedef std::invoke_result<decltype(fnc), std::uint8_t >::type return_t; }; int main() { dummy_s<[](std::uint8_t const& n) -> bool { return true ^ n; }>::return_t s = true; } Is there anyway to get the return type without specifying ...
You could write a metafunction that gives you the type of the first argument template<typename Ret, typename Arg> auto arg(Ret(*)(Arg)) -> Arg; and then decay the lambda fnc to a function pointer (using + say), that you pass to arg, and then use that in the typedef. typedef std::invoke_result<decltype(fnc), ...
69,095,126
69,095,444
How to convert std::views::join result to string_view at compile time?
I want to make the whole code work as constexpr. Here's what works: #include <iostream> #include <ranges> #include <string_view> int main() { constexpr std::string_view words{"Just some sentence I got from a friend."}; auto rng = words | std::views::split(' ') | std::views::take(4) | std::views::join; std:...
The right way to do this is to shove it in a function, like so: constexpr std::string_view first_n_words(std::string_view str, size_t n) { auto first_n = str | rv::split(' ') | rv::take(n) | rv::join; auto const len = std::min(str.size(), std::ranges::dist...
69,095,409
69,098,886
How do I calculate the opimal size of the bytes to read from a file using QIODevice:read()?
The thing is, I have to read the file and write its data to another file. But the size might be so big (larger than 8 gb) so I read the files by chunks (1 mb), but I think the optimal size of the chunks can be calculated, so how do I do this? what tools should I use? Here's the code const int BLOCK_SIZE = 1000000; if(!...
Try this: https://doc.qt.io/qt-5/qstorageinfo.html#blockSize If you are interested in tracking copying progress AND optimize the copying for speed at the same time, you might need to write platform specific code. On linux it might be sendfile(). On Windows you may need to call WinAPI... But I would start with some naiv...
69,095,605
69,095,637
Why is *int different from []int in go
I worked with C and C++ for a while before starting to learn go, and I'm curious why *int and []int are treated as different types in golang. Whether you want to think of it as an array or not is up to you, but they should both be pointers to some location in memory indicating the beginning of a list of type int. Tha...
An []int has three values internally: pointer to backing array, length of backing array and capacity of backing array. The Go runtime ensures that the application does index outside the bounds of the backing array. An *int is just a pointer as in C. Because Go does not have pointer arithmetic (outside of the unsafe pa...
69,095,609
69,095,841
c++ Gaussian random number generator keeps generating same sequence
I'm trying to implement a C++ class that generates Gaussian (aka normal) random floats using an API similar to Python's Numpy random number generator: numpy.random.normal(loc, scale) where loc is the mean and scale is the standard deviation. Below is my attempt. #include <cstdio> #include <random> #include <ctime> c...
The std::default_random_engine gen needs to be seeded differently if you want different output. The default constructor, which is what it is constructed with in your example, will always seed with default_seed, which will always be the same. You can supply a seed using any standard C++ method to construct a class memb...
69,095,617
69,095,698
How do I return a range view from a function?
What is the right way to implement the function below to allow the caller to iterate over the range it returns? #include <set> #include <ranges> std::set<int> set{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; auto find_range(int a) { //What type should I return? return std::make_tuple(set.lower_bound(a - 3), set.upper_boun...
You can return a subrange like this auto find_range(int a) { return std::ranges::subrange(set.lower_bound(a - 3), set.upper_bound(a + 3)); } Here's a demo.
69,096,269
69,096,472
gnu ld treating assembly output as linker script, how to fix? or am i doing something wrong in my compiling?
i've been working on my kernel project and to simulate it (that is to run it on QEMU), i need it as a .iso file. I have an assembly file and to assemble it - as --32 boot.s -o boot.o and for the main code (which is in c++), to compile it - gcc -S kernel.cpp -lstdc++ -o kernel.o gives no error. but, while linking it wit...
gcc -S produces assembly language, but ld expects an object file. Somewhere in between you have to run the assembler. There's no particular need to use the assembler output, so most likely you want to use -c, which does compilation and then assembly to produce an object file, instead of -S: gcc -c kernel.cpp -o kernel...
69,096,279
69,096,391
Can't compare two ranges
Can't figure out why std::ranges::equal in the code below does not compile: struct A { int x; }; using Map = std::map<int, A>; void some_func() { std::vector<A> v{ {0}, {1}, {2}, {3} }; auto v2m = [](const A& a) { return std::pair<int, A>(a.x, a); }; const auto actual = std::ranges::single_view(v[2]...
Problem 1: A isn't comparable, so you cannot compare it using std::ranges::equal with the default predicate. Solution: struct A { int x; friend auto operator<=>(const A&, const A&) = default; }; Problem 2: Your transform function produces std::pair<int, A> which doesn't match with the elements of map which are...
69,096,334
69,096,421
Creating a randomly generated graph matrix in C++
So, I've been desperately trying to make this randomly generated graph matrix, but I cannot make it work and I don't know why, getting segfault all the time. This is my code: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; const int graph_size = 4; int main(void) { bool** graph; s...
Your problem is when you do graph[j][i] when j is bigger than i. When that happens, you didn't allocate the array for this index yet which triggers the segmentation fault. Also, as pointed out by @Jeffrey, since you construct a symmetric matrix you should only calculate the upper or lower triangular matrix You can fix ...
69,096,632
69,097,011
How to use factory method with multi string parameters to create a template class?
I have a factory function with two string parameters (each parameter indicates a class). How could I reduce using if branches? A create_A(string type, string order){ if (type=="LLT" && order == "AMD"){ return A<LLT, AMD>(); } elif(type=="LLT" && order=="COLAMD"){ return A<LLT, COLAMD>(); ...
One way to reduce this code would be to use a std::(unsorted_)map with a std::pair<std::string,std::string> as the key type, and lambdas or free functions as the value type. However, a function can't return different types, and A<w,x> is a distinct type from A<y,z>. If you really want this to work, you should derive A...
69,097,191
69,097,300
Variable pack in C++
There is already parameter pack in C++, can i declare a variable pack based on the parameter pack? E.g., template<typename... Args> bool all(Args... args) { // Is the following definition of member_a possible? auto const & member_a = args.a; ... return (... (member_a.isValidState() && member_a.isStateStabl...
Yes, you can use pack expansion in lambda init-capture to do this. #include <utility> template<typename... Args> bool all(Args... args) { return [&...member_a = std::as_const(args.a)] { return (... && (member_a.isValidState() && member_a.isStateStable())); }(); } Demo.
69,097,245
69,097,325
How does the compiler evaluates expression with multilple comparison operators inside of the if-statement?
So I have this program that returns "result: true" if (true == false != true) { cout << "result: true"; } else { cout << "result: false"; } even if we flip the comparison operators inside of the if-statement, the compiler still evaluates the expression to be true if (true != false == true) My question is: Ho...
The answer to both of your questions is operator precedence. The == and != operators get the same precedence, meaning they will be evaluated in the order given. So in true == false != true, is evaluated as (true == false) != true first statement true==false being false, the full statement now becomes false!=true which ...
69,097,568
69,099,210
Back-face culling, does chosen vertex for view vector on triangle matter?
I want to hand implement back-face culling, before passing the tris to the GPU. So I am trying to understand the algorithm. So Wikipedia says for back-face culling to use the first vertex in the triangle: Does the vertex on the triangle chosen to create the view vector (the view vector in the Wikipedia picture is (V_0...
Your questions: Does the vertex on the triangle chosen to create the view vector (the view vector in the Wikipedia picture is V_0 - P) matter for back-face culling though? No, V0 ("the first vertex") is chosen arbitrarily. The math also holds for any other choice of V0, V1 and V2. Like is there potential edge cases ...