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
71,342,226
71,342,385
C++ not printing emojis as expected
I have the following extract of a program int main(){ cout << "1) ✊\n"; cout << "2) ✋\n"; cout << "3) ✌️\n"; } But at the time I run it I get strange texts like the following ==================== rock paper scissors! ==================== 1) Ô£è 2) Ô£ï 3) ԣŠThis seems not to be related to my terminal but instead to a compilation result because if I run echo ✊ it shows as expected. See example below I'm currently using the following compilation commands and compiler version g++ *.cpp -o rock_paper_scissors.exe g++.exe (Rev9, Built by MSYS2 project) 11.2.0 Copyright (C) 2021 Free Software Foundation, Inc. Finally, note that it was working before as expected, but at some point, it stopped working, I noticed after I used system("pause") which I'm guessing may have changed something on the compilation configurations as this is a Windows-only command, I delete such piece of code and still having the issue. You can see the rest of the code here: https://github.com/guillene/RockPaperScissors
If your terminal font supports emojis and you don't want to write much code (like switching from cout to wcout), you can use the windows api function below. #include <windows.h> #include <iostream> int main(){ SetConsoleOutputCP(CP_UTF8); std::cout << "1) ✊\n"; std::cout << "2) ✋\n"; std::cout << "3) ✌️\n"; return 0; } see: https://learn.microsoft.com/en-us/windows/console/setconsoleoutputcp
71,342,767
71,342,927
vector<unique_ptr<T>> takes more than three times as much memory as vector<T> in ubuntu
As far as I understand unique_ptr<T> is not supposed to have such a huge overhead. What do I wrong? size_t t = sizeof(DataHelper::SEQ_DATA); // t = 12 std::vector<std::vector<std::unique_ptr<DataHelper::SEQ_DATA>>> d(SEQ_00_SIZE + 1); // SEQ_00_SIZE = 4540 for (unsigned int i = 0; i < d.size(); ++i) { for (unsigned int k = 0; k < 124668; ++k) { std::unique_ptr<DataHelper::SEQ_DATA> sd = std::make_unique<DataHelper::SEQ_DATA>(); d[i].push_back(std::move(sd)); } } takes about ~21GB of ram. std::vector<std::vector<DataHelper::SEQ_DATA>> d(SEQ_00_SIZE + 1); for (unsigned int i = 0; i < d.size(); ++i) { for (unsigned int k = 0; k < 124668; ++k) { DataHelper::SEQ_DATA sd; d[i].push_back(sd); } } takes about ~6,5GB of ram. Additional information: struct SEQ_DATA { uint16_t id = 0; uint16_t label = 0; float intensity = 0.0f; float z = 0.0f; }; I just want to have a single vector<vector<T>> which holds my 4540 * 124668 objects as efficient as possible. I read values from binary files. Since the number of elements within the binary files varies, I cannot initialize the inner vector with the correct number (i.e. 124668 is only true for the first file). gcc 9.3.0, c++ 17
"std::unique_ptr doesn't have huge overhead" means that it doesn't have huge overhead compared to a bare pointer to dynamic allocation: { auto ptr = std::make_unique<T>(); } // has comparable cost to, and has exception safety unlike: { T* ptr = new T(); delete ptr; } std::unique_ptr doesn't make the cost of dynamic allocation cheaper. I just want to have a single vector<vector<T>> which holds my 4540 * 124668 objects as efficient as possible. The most efficient way to store 4540 * 124668 objects is a flat array: std::vector<DataHelper::SEQ_DATA> d(4540 * 124668); However, the benefit of this isn't necessarily significant given that the inner vectors aren't very small. (i.e. 124668 is only true for the first file). If you don't need all 124668 elements, then it may be a waste of memory to have the unused elements in the vector.
71,342,799
71,363,195
How to access elements of symmetric Eigen matrix
My understanding of a symmetric matrix is that A(i,j) == A(j,i), but in Eigen only one of these is defined. What am I missing? Here is an example below. I've also tried variations of that and don't seem to see an answer elsewhere. Am I supposed to manually ensure that the indices comply to some internal expectations? MatrixXf m(4, 4); // uninitialized 4x4 auto v = m.selfadjointView<Upper>(); // I don't need triangular matrix, but ok by me to store it only once int i = 1; int j = 3; v(i, j) = 3.0f; // either v(i,j) or v(j,i) is undefined. How can I permit both? std::cout << "\n" << v(j, i);
Accessing both halves by (i,j) is essentially not how .selfadjointView<>() is intended to work. Supporting that would require a min/max operation and for complex matrices even some kind of proxy-object, for each access which is quite expensive. You should only access the upper half by the () operator and afterwards you can use the SelfadjointView object as part of other expressions, such as products, or use special methods like rankUpdate.
71,342,830
71,342,895
Placement New U on existing T object and Manipulating it is UB?
In this link, Storage reuse section shows the following example. void x() { long long n; // automatic, trivial new (&n) double(3.14); // reuse with a different type okay } // okay and here, one of the answers contains this code. void f(float* buffer, std::size_t buffer_size_in_bytes) { double* d = new (buffer)double[buffer_size_in_bytes / sizeof(double)]; // we have started the lifetime of the doubles. // "d" is a new pointer pointing to the first double object in the array. // now you can use "d" as a double buffer for your calculations // you are not allowed to access any object through the "buffer" pointer anymore since the // floats are "destroyed" d[0] = 1.; // do some work here on/with the doubles... // ... } All the above are trying to perform placement new another type on the existing object, and the second code is manipulating the new object. But, the first link is saying the following If a new object is created at the address that was occupied by another object, then all pointers, references, and the name of the original object will automatically refer to the new object and, once the lifetime of the new object begins, can be used to manipulate the new object, but only if the original object is transparently replaceable by the new object. Object x is transparently replaceable by object y if: the storage for y exactly overlays the storage location which x occupied y is of the same type as x (ignoring the top-level cv-qualifiers) According to the emphasized sentence, the second example is undefined behavior because the new object type is not the same as the old one, and d[0] = 1.; manipulates the new object. But, no one stated this problem in the comments.. so I'm confused. Is the first example defined behavior because it just performs placement new? Is the second example wrong because of UB? Am I misunderstanding something..?
Both examples are legal. "Transparent replaceability" only matters when you want to use a pointer to the old object to access the new object without std::launder. But you're not doing that. You're manipulating the new object using the pointer returned by placement-new (not a pointer to the old object), which never needs std::launder.
71,342,973
71,343,034
Understanding what FE_TONEAREST does
The gcc documentation here, explains what FE_TONEAREST does: This is the default mode. It should be used unless there is a specific need for one of the others. In this mode results are rounded to the nearest representable value. If the result is midway between two representable values, the even representable is chosen. Even here means the lowest-order bit is zero. Now, consider the below example: printf("%.2f\n", 1.235); // nearest are 1.23 and 1.24, 1.24 should be chosen printf("%.2f\n", 1.225); // nearest are 1.22 and 1.23, 1.22 should be chosen Based on the documentation, I expect to get 1.24 and 1.22. Instead, I get 1.24 and 1.23. What am I missing?
1.235 and 1.225 are not numbers in your program. Your C implementation almost certainly uses the IEEE-754 “double precision” format for double, which is also called binary64. If it performs correctly rounded conversions to the nearest representable values, then the source text 1.235 is converted to the double 1.2350000000000000976996261670137755572795867919921875. When printf converts this to a decimal numeral with two decimal places, there is no tie; it is above 1.235, so the result is the numeral “1.24”. The source text 1.225 is converted to the double 1.225000000000000088817841970012523233890533447265625. When printf converts this to a decimal numeral with two decimal places, there is no tie; it is above 1.225, so the result is the numeral “1.23”.
71,344,218
71,344,269
How to properly insert and display data in an dynamically allocated arrays in C++?
I've been having trouble trying to properly display the correct memory address so I don't know in which memory address I'm inputting data. #include <iostream> using namespace std; int main() { system("cls"); int *p = new int[2]; for(int i = 0; i < 2; i++) { cout << "Enter value for address " << p << ": "; cin >> p[i]; } for(int i = 0; i < 2; i++) { cout << *p << " " << p << endl; p++; } } Here is the output when inputting data: Here is the output when displaying them: My concern is it doesn't output the correct memory address when inputting data. But when displaying them it seems to have no problem displaying the correct memory address.
Your input loop is displaying the p pointer as-is (ie, the base address of the array) on every iteration. It is not adjusting the pointer on each iteration, unlike your output loop which does. You are also leaking the array, as you are not delete[]'ing it when you are done using it. Try this instead: #include <iostream> #include <cstdlib> using namespace std; int main() { system("cls"); int *p = new int[2]; for(int i = 0; i < 2; i++) { cout << "Enter value for address " << &p[i] << ": "; cin >> p[i]; } for(int i = 0; i < 2; i++) { cout << p[i] << " " << &p[i] << endl; } delete[] p; return 0; } Alternatively: #include <iostream> #include <cstdlib> using namespace std; int main() { system("cls"); int *p = new int[2]; int *elem = p; for(int i = 0; i < 2; i++) { cout << "Enter value for address " << elem << ": "; cin >> *elem; ++elem; } elem = p; for(int i = 0; i < 2; i++) { cout << *elem << " " << elem << endl; ++elem; } delete[] p; return 0; }
71,344,994
71,345,028
fstream is writing on file against an if else statement
I have a file named "password.txt" which has 2 rows of usernames and passwords 2 string vectors named, user & password This function uses a new username and password and checks if the username already exists in the user vector using a for loop If it does exist, it breaks out of the loop If it does not exist, it will add the username and password to the vectors and write them both on the file void PasswordFile::addpw(string newuser, string newpassword) { fstream file; file.open("password.txt", ios::app); //if the vectors is empty it automatically adds a new user //is working if (user.size() < 1){ user.push_back(newuser); password.push_back(newpassword); file << newuser << " " << newpassword << "\r"; } //the loop (is not working) for (int i=0; i < user.size(); i++){ string name = user[i]; if (name == newuser) { break; } //it shouldn't continue past this point if the name is in the vector but it does else { cout << newuser; cout << " is being written onto the file\n"; user.push_back(newuser); password.push_back(newpassword); file << newuser << " " << newpassword << "\r"; } } file.close(); } the problem is that it is writing the second name twice and the third name three times I know also that it is pushing the newuser and newpassword multiple times onto the vector, but I can't figure out where or why its looping more than it should or why its ignoring the break and writing onto the file anyway "password.txt" 1 run dbotting 123qwe egomez qwerty tongyu liberty tongyu liberty "password.txt" second run dbotting 123qwe egomez qwerty tongyu liberty tongyu liberty egomez qwerty tongyu liberty tongyu liberty it keeps adding the last 2 every time its run
WHILE you are looping through the user vector, any time you encounter an entry that does not match the newuser being searched for, you are writing the newuser/newpassword to the file and pushing them into the vectors 1 (which then affects subsequent iterations of your loop), and then you move on to the next entry. So, for example, if you start with a file like: dbotting 123qwe egomez qwerty tongyu does not match dbotting, so you add tongyu. And then tongyu does not match egomez, so you add tongyu again. So you end up with: dbotting 123qwe egomez qwerty tongyu liberty tongyu liberty And then on the next run, tongyu doesn't match dbotting or egomez, so you add tongyu twice again. But then it does match tongyu, so you don't add it again, and break the loop. So you end up with: dbotting 123qwe egomez qwerty tongyu liberty tongyu liberty tongyu liberty tongyu liberty And so on. Online Demo To fix this, the code inside of your else block needs to be moved out of the for loop entirely. You need to search the entire vector to determine if the user already exists or not, and then write that user to the file only if they don't exist at all, eg: void PasswordFile::addpw(const string &newuser, const string &newpassword) { for (size_t i = 0; i < user.size(); ++i){ if (user[i] == newuser) { cout << newuser << " already exists" << endl; return; } } /* alternatively: if (find(user.begin(), user.end(), newuser) != user.end()) { cout << newuser << " already exists" << endl; return; } */ ofstream file("password.txt", ios::app); if (!file.is_open()) { cout << "cannot open password file" << endl; return; } cout << newuser << " is being written onto the file\n"; if (!(file << newuser << " " << newpassword << "\r")) { cout << "cannot write to password file" << endl; return; } user.push_back(newuser); password.push_back(newpassword); } 1: On a side note, you should not maintain two separate vectors that are closely related. Just use a single vector instead, eg: struct UserInfo { string username; string password; }; std::vector<UserInfo> users; void PasswordFile::addpw(const string &user, const string &password) { for (size_t i = 0; i < users.size(); ++i){ if (users[i].username == user) { cout << user << " already exists" << endl; return; } } /* alternatively: if (find_if(users.begin(), users.end(), [&](const UserInfo &u){ return u.username == user; }) != users.end()) { cout << user << " already exists" << endl; return; } */ ofstream file("password.txt", ios::app); if (!file.is_open()) { cout << "cannot open password file" << endl; return; } cout << user << " is being written onto the file\n"; if (!(file << user << " " << password << "\r")) { cout << "cannot write to password file" << endl; return; } UserInfo newuser; newuser.username = user; newuser.password = password; users.push_back(newuser); }
71,345,823
71,348,979
How do I use SetTimer() to create certain number of message boxes after another in c++?
I am trying to make it so when a messagebox opens another one opens a couple seconds later without any user input (pressing the OK button). I want the old one to stay open, but a new one to appear. I also want to be able to use SetWindowsHookEx and set a limit on how many message boxes are created. I know this uses the function SetTimer() and needs some kind of if statement with the current number of dialogs that equal the limit and stop when the number is reached. So how do I make this work? I tried to research, but nothing seemed to work. My attempt: #include <iostream> #include <Windows.h> #include <string> using namespace std; thread_local int MsgBox_X; thread_local int MsgBox_Y; thread_local int Limit = 10; static LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HCBT_CREATEWND) { CBT_CREATEWND* s = (CBT_CREATEWND*)lParam; if (s->lpcs->hwndParent == NULL) { s->lpcs->x = MsgBox_X; s->lpcs->y = MsgBox_Y; } } return CallNextHookEx(NULL, nCode, wParam, lParam); } int MessageBoxPos(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType, int X, int Y) { HHOOK hHook = SetWindowsHookEx(WH_CBT, &CBTProc, NULL, GetCurrentThreadId()); MsgBox_X = X; MsgBox_Y = Y; int result = MessageBox(hWnd, lpText, lpCaption, uType); if (hHook) UnhookWindowsHookEx(hHook); return result; if (<# of dialogs> == Limit) { std::terminate() } } void _MessageBox() { HWND HWND1; MessageBox(HWND1, TEXT("Message"), TEXT("MsgBox"), MB_ICONWARNING | MB_OK); SetTimer(HWND1, TIMER1, 2000, (TIMERPROC)NULL); case WM_TIMER: switch (wParam) { case TIMER1: MessageBoxPos(NULL, TEXT("Message 2"), TEXT("MsgBox 2"), MB_ICONWARNING | MB_OK, 50, 50); return 0; } } } int main() { ShowWindow(::GetConsoleWindow(), SW_HIDE); _MessageBox(); }
You are passing an uninitialized HWND to MessageBox(). Also, MessageBox() is a blocking function, it doesn't exit until the dialog is closed, so you need to create the timer before you call MessageBox(). Unless you use SetWindowsHookEx() or SetWinEventHook() to hook the creation of the dialog, then you can create the timer when the dialog's HWND is created, and you pass that HWND to SetTimer(). Also, your syntax to handle the WM_TIMER message is just plain wrong. That being said, MessageBox() displays a modal dialog and runs its own message loop, so you don't need to handle WM_TIMER manually at all. You can assign a callback to the timer, and let the modal loop dispatch the callback events for you. Try something more like this: #include <Windows.h> thread_local int MsgBox_X; thread_local int MsgBox_Y; thread_local int NumMsgBoxes = 0; static LRESULT CALLBACK CBTSetPosProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HCBT_CREATEWND) { CBT_CREATEWND* s = (CBT_CREATEWND*)lParam; if (s->lpcs->hwndParent == NULL) { s->lpcs->x = MsgBox_X; s->lpcs->y = MsgBox_Y; } } return CallNextHookEx(NULL, nCode, wParam, lParam); } int MessageBoxPos(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType, int X, int Y) { HHOOK hHook = SetWindowsHookEx(WH_CBT, &CBTSetPosProc, NULL, GetCurrentThreadId()); MsgBox_X = X; MsgBox_Y = Y; int result = MessageBox(hWnd, lpText, lpCaption, uType); if (hHook) UnhookWindowsHookEx(hHook); return result; } static void CALLBACK TimerProc(HWND, UINT, UINT_PTR, DWORD) { if (NumMsgBoxes > 0) { --NumMsgBoxes; MessageBoxPos(NULL, TEXT("Message 2"), TEXT("MsgBox 2"), MB_ICONWARNING | MB_OK, 50, 50); } } void _MessageBox(int NumberOfMsgBoxes) { NumMsgBoxes = NumberOfMsgBoxes; if (NumMsgBoxes > 0) { --NumMsgBoxes; UINT timer = SetTimer(NULL, 0, 2000, &TimerProc); if (timer) { MessageBox(NULL, TEXT("Message"), TEXT("MsgBox"), MB_ICONWARNING | MB_OK); KillTimer(NULL, timer); } } } int main() { ShowWindow(GetConsoleWindow(), SW_HIDE); _MessageBox(5); } Alternatively: #include <Windows.h> thread_local int MsgBox_X; thread_local int MsgBox_Y; thread_local int NumMsgBoxes = 0; static LRESULT CALLBACK CBTSetPosProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HCBT_CREATEWND) { CBT_CREATEWND* s = (CBT_CREATEWND*)lParam; if (s->lpcs->hwndParent == NULL) { s->lpcs->x = MsgBox_X; s->lpcs->y = MsgBox_Y; } } return CallNextHookEx(NULL, nCode, wParam, lParam); } int MessageBoxPos(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType, int X, int Y) { HHOOK hHook = SetWindowsHookEx(WH_CBT, &CBTSetPosProc, NULL, GetCurrentThreadId()); MsgBox_X = X; MsgBox_Y = Y; int result = MessageBox(hWnd, lpText, lpCaption, uType); if (hHook) UnhookWindowsHookEx(hHook); return result; } static void CALLBACK TimerProc(HWND hwnd, UINT message, UINT_PTR idTimer, DWORD dwTime) { KillTimer(hwnd, idTimer); if (NumMsgBoxes > 0) MessageBoxPos(NULL, TEXT("Message 2"), TEXT("MsgBox 2"), MB_ICONWARNING | MB_OK, 50, 50); } static LRESULT CALLBACK CBTSetTimerProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HCBT_CREATEWND) { CBT_CREATEWND* s = (CBT_CREATEWND*)lParam; if (s->lpcs->hwndParent == NULL) { if (--NumMsgBoxes > 0) SetTimer((HWND)wParam, 1, 2000, &TimerProc); } } return CallNextHookEx(NULL, nCode, wParam, lParam); } void _MessageBox(int NumberOfMsgBoxes) { HHOOK hHook = SetWindowsHookEx(WH_CBT, &CBTSetTimerProc, NULL, GetCurrentThreadId()); NumMsgBoxes = NumberOfMsgBoxes; if (NumMsgBoxes > 0) MessageBox(NULL, TEXT("Message"), TEXT("MsgBox"), MB_ICONWARNING | MB_OK); if (hHook) UnhookWindowsHookEx(hHook); } int main() { ShowWindow(GetConsoleWindow(), SW_HIDE); _MessageBox(5); }
71,346,670
71,346,717
'\r\n' deletes the whole buffer when the length is too long
I'm learning socket programming and there is a requirement in my project to put \r\n in every returned message. Something I notice that \r\n will delete the whole buffer when it exceeds some number of characters. For example, I have a code like this: #include <iostream> int main() { std::string message = "mkdir homewor"; const char *buffer = (message + "\r\n").c_str(); std::cout << "message: " << message << std::endl; std::cout << "buffer: " << buffer << std::endl; } I run and it gives me the output like this: message: mkdir homewor buffer: mkdir homewor I open the gdb and it gives me something like this: message: "mkdir homewor" buffer: 0x7fffffffdc50 "mkdir homewor\r\n" - *buffer: 109 'm' Which is something I expect it. But when the message is too long and I convert it to C-String, the whole buffer gets deleted. For example: #include <iostream> int main() { std::string message = "mkdir homework"; // Just one more 'k' at the end const char *buffer = (message + "\r\n").c_str(); std::cout << "message: " << message << std::endl; std::cout << "buffer: " << buffer << std::endl; } I run and it gives me the output: message: mkdir homework buffer: gdb gives me this: message: "mkdir homework" buffer: 0x55555556aeb0 "" - *buffer: 0 '\000' One more observation is that if the message has or exceeds the length of the message in the second example, the buffer will be deleted no matter what. Can anyone tell me what this problem is? I cannot get rid of \r\n because it's required in the project. Thanks in advance.
(message + "\r\n") creates a new std::string, and it is backed with a pointer. This new std::string will get destroyed at the end of the full-expression. So you should do this, #include <iostream> int main() { std::string message = "mkdir homework"; // Just one more 'k' at the end std::string messageSuffixed = message + "\r\n"; const char *buffer = messageSuffixed.c_str(); std::cout << "message: " << message << std::endl; std::cout << "buffer: " << buffer << std::endl; }
71,346,817
71,347,756
C++ 17 programming on visual studio 2017?
In title, I am specific about the task that I want to achieve. I want to utilize the c++17 features such as parallel STL etc. On visual studio 2017, I configure to c++17 under project properties for language. Even after doing this I get the error with #include that no execution file. I am just starting with simple example of array addition in parallel with C++ 17 algorithms. How do I resolve this? Source: #include <stddef.h> #include <stdio.h> #include <algorithm> #include <execution> #include <chrono> #include <random> #include <ratio> #include <vector> using std::chrono::duration; using std::chrono::duration_cast; using std::chrono::high_resolution_clock; using std::milli; using std::random_device; using std::sort; using std::vector; const size_t testSize = 1'000'000; const int iterationCount = 5; void print_results(const char *const tag, const vector<double>& sorted, high_resolution_clock::time_point startTime, high_resolution_clock::time_point endTime) { printf("%s: Lowest: %g Highest: %g Time: %fms\n", tag, sorted.front(), sorted.back(), duration_cast<duration<double, milli>>(endTime - startTime).count()); } int main() { random_device rd; // generate some random doubles: printf("Testing with %zu doubles...\n", testSize); vector<double> doubles(testSize); for (auto& d : doubles) { d = static_cast<double>(rd()); } // time how long it takes to sort them: for (int i = 0; i < iterationCount; ++i) { vector<double> sorted(doubles); const auto startTime = high_resolution_clock::now(); sort(sorted.begin(), sorted.end()); const auto endTime = high_resolution_clock::now(); print_results("Serial", sorted, startTime, endTime); } } and this is error: Error C1083 Cannot open include file: 'execution': No such file or directory Task that I want to achieve is that C++17 with CUDA GPU. Both new to me although not c++ in itself. But I am interested in parallel STL of C++17 with CUDA. I want to start from base. Any suggestions will help me? Thanks, Govind
Please check if the header file is included in the header file directory. the C++ headers path are: 1.C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.15.26726\include 2.C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\ucrt The first contains standard C++ headers such as iostream. The second contains legacy C headers such as stdio.h. If you are going to use C++ to develop desktop applications, I recommend you to refer to my setup. Also I tested your code on VS2022 without any errors. So I suggest you to use a higher version of VS and install the environment you need.
71,347,219
71,347,913
How to find unique values in a vector c++
I am trying to solve a coding problem where I am to check and see if a vector has unique values and if it does then return true else false. So Far I thought of using a nested loops where you would compare the first to the last, but I am wanted to know if C++ has anything else then doing a o(n^2) type iteration. I saw that c++ has a unique function, but that would delete the unique value. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false
std::unique checks for consecutive duplicates and moves them to the end of the range. It does not remove them from the vector. Anyhow you can make a copy. It also returns an iterator to the end of the range of unique values (that are now in the front of the vector): #include <iostream> #include <vector> #include <algorithm> bool only_unique(std::vector<int> v) { std::sort(v.begin(),v.end()); return std::unique(v.begin(),v.end()) == v.end(); } int main(){ std::cout << only_unique({1,2,3,1}); std::cout << only_unique({1,2,3,4}); } If you don't want to use the additional memory you can change the argument to a reference. Currently, only_unique leaves the parameter unmodified. Even if the vector is passed by reference the duplicates will still be present (just at a different position). This has O(n log n) complexity.
71,347,375
71,347,466
Iterating over a parameter pack
I have a parameter pack args... of vectors of arbitrary types, corresponding to which there is a vector of indices say v = {3,0,5...} having the same size, and order as the number of members of args.... I would like get_tuple to return a tuple of the elements of args... at the indices given by v. Here's what I have so far, but I'm stuck trying to iterate over the members of the parameter pack. template<typename... Args> auto get_tuple(const std::vector<size_t>& vector, const Args &... args) { return std::make_tuple(args[v[0]]...); } For example: std::vector<std::string> v1 = {"a", "b"}; std::vector<int> v2 = {1,2}; std::vector<size_t> v = {0,1}; auto result = get_tuple(v, v1, v2); // ("a",2) expected
In C++17, you need additional level of indirection to get a pack of indices to get a pack of elements at those indices: template<typename... Args, std::size_t... Is> auto get_tuple_impl(const std::vector<std::size_t>& indices, std::index_sequence<Is...>, const Args&... args) { return std::make_tuple(args[indices[Is]]...); } template<typename... Args> auto get_tuple(const std::vector<std::size_t>& indices, const Args&... args) { return get_tuple_impl(indices, std::index_sequence_for<Args...>(), args...); } In C++20, we could you a lambda function with template parameters invoked in-place: template<typename... Args> auto get_tuple(const std::vector<std::size_t>& indices, const Args&... args) { return [&]<std::size_t... Is>(std::index_sequence<Is...>) { return std::make_tuple(args[indices[Is]]...); }(std::index_sequence_for<Args...>()); } You might also want to add an assertion assert(indices.size() == sizeof...(Args)); or use std::array<std::size_t, N> type instead.
71,347,415
71,348,050
Finding if a path exists between two Nodes in a Graph using Depth First Search(DFS) C++
I'm trying to implement the Depth First Search(DFS) suing recursion to return a boolean value if a path exists between two Nodes in a graph. Below is my implementation. The edges input is in the form of a Vector array. I tried debugging the program to detect where exactly I am going wrong, but I don't know why it gives a segmentation fault as soon as I call return validPath_helper(n, i, destination, visited, adjList); function in the validPath function after checking if the Node is visited or not. bool validPath_helper(int n, int source, int destination, vector<bool> visited, vector<vector<int>> adjList){ visited[source] = true; if(adjList[source][destination]){ return true; } for(int i=0; i<adjList[source].size(); i++){ if(adjList[source][i]){ return validPath_helper(n, i, destination, visited, adjList); } } return false; } bool validPath(int n, vector<vector<int>>& edges, int source, int destination) { vector<bool> visited(n, false); vector<vector<int>> adjList(n); int u, v; for(int i=0; i<edges.size(); i++){ u = edges[i][0]; v = edges[i][1]; adjList[u].push_back(v); adjList[v].push_back(u); } for(int i=source; i<n; i++){ if(!visited[i]){ return validPath_helper(n, i, destination, visited, adjList); } } return false; } Any Help would be appreciated!
Seg faults usually occur due to access of un-allocated memory so that's what you should investigate first. You said that the validPath_helper is triggering the seg fault, so you should check that function. In your case the culprit is this line : if(adjList[source][destination]){ return true; } Here you wanted to check that whether there is an edge between source node and destination node. But if you check back to how you created your adjacency list, you will see it is a vector of vectors that is for every node we have a list of nodes it has edges to. For example the following graph: 1 - 2 0 - 1 1 - 3 The adjacency list will be : 0 -> 1 1 -> 0 2 3 2 -> 1 3 -> 1 Let's take source 2 and destination 3. Now when your validPath_helper is called it will check adjList[2][3] but as you see above length of adjList[2] is only 1 so there is no 4th element to check (3 is index so 4th element). This is the cause of your seg fault. This also leads to an entirely different problem in your code that you want to check whether edge exists between 2 and 3 but instead you check whether there is a non-zero element at 4th position of 2's list. You can fix this a couple of ways. Way # 1 Instead of if(adjList[source][destination]){ return true; } try for (int index = 0; index < adjList[source].size(); index++) { if (adjList[source][index] == destination) return true; } You need to make this change in both the places of your validPath_helper function. Way # 2 The above method increases the runtime of your program in case of big graphs, if you are concerned about runtime and know about hashlists this method is better. #include <unordered_set> // at top bool validPath_helper(int n, int source, int destination, vector<bool> visited, vector<unordered_set<int>> adjList){ visited[source] = true; if(adjList[source].find(destination) != adjList[source].end()){ return true; } for(int i: adjList[source]){ if (!visited[i] && validPath_helper(n, i, destination, visited, adjList)) { return true; } } return false; } bool validPath(int n, vector<vector<int>>& edges, int source, int destination) { vector<bool> visited(n, false); vector<unordered_set<int>> adjList(n); int u, v; for(int i=0; i<edges.size(); i++){ u = edges[i][0]; v = edges[i][1]; adjList[u].insert(v); adjList[v].insert(u); } return validPath_helper(n, i, destination, visited, adjList); } There were a couple more bugs in your code : Some unnecessary loops in both your functions. You set visited to true but do not check it before calling DFS on new nodes. You return the first DFS result and don't check other child nodes. (Due to return validPath_helper call in validPath_helper function. Look into these issues too, refer to way # 2 above if you are stuck.
71,347,589
71,347,625
how do I allow free usage of enum and enum class member?
enum class A { ORANGE, APPLE }; ... {// workspace brackets if(B == ORANGE){...} // use it like this }// end of workspace instead of keep using B==A::ORANGE, what can I do to make it like B==ORANGE within my workspace such as using namespace std?
You can only do this in c++ 20 onwards with using enum A enum class foo { a, b, c }; int main() { { using enum foo; foo f = b; } { //foo f = b; // does not compile } }
71,347,981
71,348,048
Is there a C++14 alternative to explicit(expr) introduced in C++20?
TL;DR: I am looking for a C++14 equivalent of the following C++20 MWE: template<int sz> struct bits { int v; // note explicit(expr) below explicit(sz > 1) operator bool() const { return bool(v); } }; int main() { bool c = bits<1>{1}; // Should work bool d = bits<3>{1}; // Should fail } Context: We have a C++ class bits<sz> representing bitvectors of length sz. Conversion to bool used to be implicit for all sz, but this proved to be error-prone, so we changed operator bool() to be explicit. However, 1-bit bitvectors are (in our context) almost-completely equivalent to Booleans, so it would be desirable for operator bool() to be implicit when sz == 1. This can be achieved with explicit(sz > 1) in C++20, but we are targeting C++14. I tried to overload the operator for sz == 1, but it seems that the explicit qualifier applies to it as well: the following does not work. template<int sz> struct bits { int v; explicit operator bool() const { return bool(v); } }; template<> bits<1>::operator bool() const { return bool(v); } int main() { bool c = bits<1>{1}; // Fails: "No viable conversion" } Hence the question: How can I specify in C++14 that operator bool() should be explicit only for sz > 1? I'm including some background below for curious readers. Background: This problem came up in the context of an embedded domain-specific language in C++. One of the business requirements is that operator== returns a bit<1>, not a bool. This is working smoothly with GNU's libstdc++, but we're running into trouble with that requirement on macOS because libstdc++ there implements operator== on std::array using the version of std::equal that takes a predicate, and implements that predicate using a struct whose operator() returns bool with body a == b (which in our case returns a bits<1>, causing a conversion error). To make it concrete for curious readers, the following program compiles fine on GNU, but not on macOS, because of the way operator== on std::array is implemented: #include <array> struct S { explicit operator bool() const { return true; } }; struct T {}; S operator==(T, T) { return S(); } int main() { std::array<T, 1> arr = { T() }; return arr == arr; } That's because deep down in the implementation of == on arrays GNU libstdc++ has a test if (!(*it1 == *it2)), which invokes the explicit operator bool() on S without trouble, where as on macOS the library uses if (!__pred(*it1, *it2)) with __pred roughly equivalent to bool __pred(S a, S b) { return a == b; }, which doesn't typecheck.
Yes. You can SFINAE the conversion operator: #include <type_traits> template<int sz> struct bits { int v; explicit operator bool() const { return bool(v); } template <int S = sz> operator std::enable_if_t<S == 1, bool> () const { return bool(v);} }; Check it on godbolt int main() { bool c1 = bits<1>{1}; // Ok bool c2 = bits<3>{1}; // error cannot convert bool c3 = static_cast<bool>(bits<3>{1}); // OK }
71,348,386
71,357,534
Emscripten C++ to WASM with Classes - "error: undefined symbol"
I have a really simple C++ project (removed as much code til the problem is still there.) Running em++ is always leading to an error, error: undefined symbol main.cpp #include "edgeguard.hpp" int main() { EdgeGuardConfig core = EdgeGuardConfig::BuildEdgeGuard(); } edgeguard.cpp #include "edge-guard.hpp" EdgeGuardConfig EdgeGuardConfig::BuildEdgeGuard() { } edgeguard.hpp class EdgeGuardConfig { public: static EdgeGuardConfig BuildEdgeGuard(); }; The command I'm using is em++ ./main.cpp --std=c++17 -o ~/edgeguard-wasm/edgeguard-ft90x.html The results are always the same: error: undefined symbol: _ZN15EdgeGuardConfig14BuildEdgeGuardEv (referenced by top-level compiled C/C++ code) warning: Link with `-s LLD_REPORT_UNDEFINED` to get more information on undefined symbols warning: To disable errors for undefined symbols use `-s ERROR_ON_UNDEFINED_SYMBOLS=0` warning: __ZN15EdgeGuardConfig14BuildEdgeGuardEv may need to be added to EXPORTED_FUNCTIONS if it arrives from a system library Error: Aborting compilation due to previous errors em++: error: '/home/nessdan/code/emsdk/node/14.18.2_64bit/bin/node /home/nessdan/code/emsdk/upstream/emscripten/src/compiler.js /tmp/tmpqwnlcp5h.json' failed (returned 1) Some other things I've tried: Using EMSCRIPTEN_KEEPALIVE Wrapping things in extern "C" Running with -s ERROR_ON_UNDEFINED_SYMBOLS=0 (command finishes, but HTML output logs the error in my console when I open it.) Running with -s LINKABLE=1 -s EXPORT_ALL=1 - nothing changes, console output is the same. I'm using the latest version of emscripten (3.1.6) and installed it fresh today (also installed and ran from my Windows computer with the exact same results.)
Thanks to Marc Glisse's comment, I realize now that I needed to not just pass main.cpp but also all related .cpp files (I thought it would pick up that information from the includes ‍♂️) It is now compiling
71,348,675
71,349,187
How to sort a vector using std::views C++20 feature?
I want to loop through a vector in a sorted way without modifying the underlying vector. Can std::views and/or std::range be used for this purpose? I've successfully implemented filtering using views, but I don't know if it is possible to sort using a predicate. You can find an example to complete here : https://godbolt.org/z/cKer8frvq #include <iostream> #include <ranges> #include <vector> #include <chrono> struct Data{ int a; }; int main() { std::vector<Data> vec = {{1}, {2}, {3}, {10}, {5}, {6}}; auto sortedView = // <= can we use std::views here ? for (const auto &sortedData: sortedView) std::cout << std::to_string(sortedData.a) << std::endl; // 1 2 3 5 6 10 for (const auto &data: vec) std::cout << std::to_string(data.a) << std::endl; // 1 2 3 10 5 6 }
You have to modify something to use std::ranges::sort (or std::sort), but it doesn't have to be your actual data. #include <iostream> #include <ranges> #include <numeric> #include <algorithm> #include <vector> #include <chrono> struct Data{ int a; friend auto operator<=> (const Data &, const Data &) = default; }; int main() { std::vector<Data> vec = {{1}, {2}, {3}, {10}, {5}, {6}}; std::vector<std::size_t> indexes(vec.size()); std::iota(indexes.begin(), indexes.end(), std::size_t{ 0 }); // 0z in C++23 auto proj = [&vec](std::size_t i) -> Data & { return vec[i]; }; std::ranges::sort(indexes, std::less<>{}, proj); auto sortedView = std::ranges::views::transform(indexes, proj); for (const auto &sortedData: sortedView) std::cout << sortedData.a << std::endl; // 1 2 3 5 6 10 for (const auto &data: vec) std::cout << data.a << std::endl; // 1 2 3 10 5 6 }
71,349,240
71,381,959
C++ OpenSSL: libssl fails to verify certificates on Windows
I've done a lot of looking around but I can't seem to find a decent solution to this problem. Many of the StackOverflow posts are regarding Ruby, but I'm using OpenSSL more or less directly (via the https://gitlab.com/eidheim/Simple-Web-Server library) for a C++ application/set of libraries, and need to work out how to fix this completely transparently for users (they should not need to hook up any custom certificate verification file in order to use the application). On Windows, when I attempt to use the SimpleWeb HTTPS client, connections fail if I have certificate verification switched on, because the certificate for the connection fails to validate. This is not the case on Linux, where verification works fine. I was advised to follow this solution to import the Windows root certificates into OpenSSL so that they could be used by the verification routines. However, this doesn't seem to make any difference as far as I can see. I have dug into the guts of the libssl verification functions to try and understand exactly what's going on, and although the above answer recommends adding the Windows root certificates to a new X509_STORE, it appears that the SSL connection context has its own store which is set up when the connection is initialised. This makes me think that simply creating a new X509_STORE and adding certificates there is not helping because the connection doesn't actually use that store. It may well be that I've spent so much time debugging the minutiae of libssl that I'm missing what the actual approach to solving this problem should be. Does OpenSSL provide a canonical way of looking up system certificates that I'm not setting? Alternatively, could the issue be the way that the SimpleWeb library/ASIO is initialising OpenSSL? I know that the library allows you to provide a path for a "verify file" for certificates, but I feel like this wouldn't be an appropriate solution since I as a developer should be using the certificates found on the end user's system, rather than hard-coding my own. EDIT: For context, this is the code I'm using in a tiny example application: #define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_ENCODING) static void LoadSystemCertificates() { HCERTSTORE hStore; PCCERT_CONTEXT pContext = nullptr; X509 *x509 = nullptr; X509_STORE *store = X509_STORE_new(); hStore = CertOpenSystemStore(NULL, "ROOT"); if (!hStore) { return; } while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != nullptr) { const unsigned char* encodedCert = reinterpret_cast<const unsigned char*>(pContext->pbCertEncoded); x509 = d2i_X509(nullptr, &encodedCert, pContext->cbCertEncoded); if (x509) { X509_STORE_add_cert(store, x509); X509_free(x509); } } CertCloseStore(hStore, 0); } static void MakeRequest(const std::string& address) { using Client = SimpleWeb::Client<SimpleWeb::HTTPS>; Client httpsClient(address); httpsClient.io_service = std::make_shared<asio::io_service>(); std::cout << "Making request to: " << address << std::endl; bool hasResponse = false; httpsClient.request("GET", [address, &hasResponse](std::shared_ptr<Client::Response> response, const SimpleWeb::error_code& error) { hasResponse = true; if ( error ) { std::cerr << "Got error from " << address << ": " << error.message() << std::endl; } else { std::cout << "Got response from " << address << ":\n" << response->content.string() << std::endl; } }); while ( !hasResponse ) { httpsClient.io_service->poll(); httpsClient.io_service->reset(); std::this_thread::sleep_for(std::chrono::milliseconds(20)); } } int main(int, char**) { LoadSystemCertificates(); MakeRequest("google.co.uk"); return 0; } The call returns me: Got error from google.co.uk: certificate verify failed
OK, to anyone who this might help in future, this is how I solved this issue. This answer to a related question helped. It turns out that the issue was indeed that the SSL context was not making use of the certificate store that I'd set up. Everything else was OK, bu the missing piece of the puzzle was a call to SSL_CTX_set_cert_store(), which takes the certificate store and provides it to the SSL context. In the context of the SimpleWeb library, the easiest way to do this appeared to be to subclass the SimpleWeb::Client<SimpleWeb::HTTPS> class and add the following to the constructor: #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <wincrypt.h> class MyClient : public SimpleWeb::Client<SimpleWeb::HTTPS> { public: MyClient( /* ... */ ) : SimpleWeb::Client<SimpleWeb::HTTPS>( /* ... */ ) { AddWindowsRootCertificates(); } private: using OpenSSLContext = asio::ssl::context::native_handle_type; void AddWindowsRootCertificates() { // Get the SSL context from the SimpleWeb class. OpenSSLContext sslContext = context.native_handle(); // Get a certificate store populated with the Windows root certificates. // If this fails for some reason, the function returns null. X509_STORE* certStore = GetWindowsCertificateStore(); if ( sslContext && certStore ) { // Set this store to be used for the SSL context. SSL_CTX_set_cert_store(sslContext, certStore); } } static X509_STORE* GetWindowsCertificateStore() { // To avoid populating the store every time, we keep a static // pointer to the store and just initialise it the first time // this function is called. static X509_STORE* certificateStore = nullptr; if ( !certificateStore ) { // Not initialised yet, so do so now. // Try to open the root certificate store. HCERTSTORE rootStore = CertOpenSystemStore(0, "ROOT"); if ( rootStore ) { // The new store is reference counted, so we can create it // and keep the pointer around for later use. certificateStore = X509_STORE_new(); PCCERT_CONTEXT pContext = nullptr; while ( (pContext = CertEnumCertificatesInStore(rootStore, pContext)) != nullptr ) { // d2i_X509() may modify the pointer, so make a local copy. const unsigned char* content = pContext->pbCertEncoded; // Convert the certificate to X509 format. X509 *x509 = d2i_X509(NULL, &content, pContext->cbCertEncoded); if ( x509 ) { // Successful conversion, so add to the store. X509_STORE_add_cert(certificateStore, x509); // Release our reference. X509_free(x509); } } // Make sure to close the store. CertCloseStore(rootStore, 0); } } return certificateStore; } }; Obviously GetWindowsCertificateStore() would need to be abstracted out to somewhere platform-specific if your class needs to compile on multiple platforms.
71,349,401
71,349,627
error: expected ',' or '...' before 'nullptr'
The below code snippet is generating the error: expected identifier before 'nullptr' as well as error: expected ',' or '...' before 'nullptr' in line edge minIncoming(nullptr, NOPATH); Any idea what is wrong? All I want to do is use the constructor to initialize minIncoming. I tried searching but couldn't find a answer. I apologize in advance if question is too basic. #include <vector> #include <unordered_map> #include <fstream> #include <sstream> #include <algorithm> #include <queue> #define MAXN 8 #define NOPATH 1000000 #define DEBUG using namespace std; struct vertex; struct edge { vertex* node; int weight; edge(vertex* n, int w) : node(n), weight(w) {} }; struct vertex { vector< edge > outgoing; edge minIncoming(nullptr, NOPATH); bool visited; #ifdef DEBUG int id; #endif // DEBUG };
Due to C++'s most vexing parse, the statement: edge minIncoming(nullptr, NOPATH); is treated as if you're declaring a function named minIncoming with return type of edge and taking two parameters. But since during declaration of a function, we specify the types of the parameters instead of specifying the arguments(as you did in your program), the program gives the mentinoed error. To solve this replace that statement with: edge minIncoming{ nullptr, NOPATH }; Now the above statement defines an object(data member) named minIncoming of type edge while passing the two initializers.
71,349,651
71,352,156
Longest palindrome in a string?
I want to print the longest palindrome in a string , I have written the code but this is giving wrong answer for some test cases . I am not able to find the error in my code . Anyone help me with this , Anyhelp would be appreciated. Input vnrtysfrzrmzlygfv Output v Expected output rzr Code: class Solution { public: int ispalindrome(string s) { string rev = ""; int n = s.size(); for (int i = n - 1; i >= 0; i--) { rev = rev + s[i]; } if (rev == s) { return 1; } return 0; } string longestPalin(string S) { // code here int size = S.size(); int size_of_substr = 0; string ans; for (int i = 0; i < size; i++) { for (int j = i + 1; j < size; j++) { string s2 = S.substr(i, j); if (ispalindrome(s2)) { if (s2.size() > size_of_substr) { ans = s2; size_of_substr = s2.size(); } else { continue; } } else { continue; } } } return ans; } };
You are using substr(.) incorrectly. The second argument is the size of the substring. string s2 = S.substr(i, j); should be replaced by string s2 = S.substr(i, j-i+1); Moreover, this code will not be very efficient. To speed it up, I modified your code in the following way: I pass the string by reference to the ispalindromefunction I modified the algorithm to check if the substring is a palindrome. It returns false after the first mismatch I don't build each substring explicitly. I only pass the start and beginning of the substring to the helper function I start by checking if there exists a palindrome of the maximum size, and then I decrease its length. As soon as a palindrome is found, we know it has the maximum size, and we can stop the search #include <iostream> #include <string> class Solution { public: int ispalindrome(const std::string& S, int i, int j) { while (i < j) { if (S[i++] != S[j--]) return 0; } return 1; } std::string longestPalindrome(const std::string& S) { int size = S.size(); int imax = 1; for (int size_of_substr = size; size_of_substr > 0; size_of_substr--, imax++) { int j = size_of_substr - 1; for (int i = 0; i < imax; i++, j++) { if (ispalindrome(S, i, j)) { std::string ans = S.substr(i, size_of_substr); return ans; } } } return ""; } }; int main() { Solution sol; std::string S; std::cin >> S; auto ans = sol.longestPalindrome(S); std::cout << ans << "\n"; return 0; }
71,349,888
71,350,225
Do while loop c++ assistance
I'm trying to make a cpp program that asks the user for two number inputs. Then print from 1 to the first number the user entered or until the first multiple of the second number. Print "Multiple of X(second number)" if the number is a multiple of the second input. using Do while loop. This is what I managed to do so far. int main() { std::cout << "enter two numbers: "; int first = 0; int second = 0; std::cin >> first >> second; if(second != 0 && first%second == 0) std::cout << first << " is a multiple of " << second << '\n' ; else { int n = 0; int maxval = second*2 > first ? first : second*2; do std::cout << ++n << '\n'; while(n < maxval); } } I'm hoping someone can help me fix the code or point out what's wrong/missing in it. Input should be any two numbers then output should print numbers from 1 until the first number OR until the first multiple of the second number if it comes before the first number. Example: Enter two numbers: 10 7 1 2 3 4 5 6 Multiple of 7
You should use break when you get to the target number. #include <iostream> int main() { std::cout << "enter two numbers: "; int first = 0; int second = 0; std::cin >> first >> second; if (second != 0 && first % second == 0) std::cout << first << " is a multiple of " << second << '\n'; else { int n = 0; int maxval = second * 2 > first ? first : second * 2; do { if (++n % second == 0) { std::cout << "Multiple of " << second << '\n'; break; } else { std::cout << n << '\n'; } } while (n < maxval); } } https://cplayground.com/?p=marmoset-tiger-vicuna
71,349,963
71,350,560
Which C++ random number distribution to use for the Java skip list generator?
The Java ConcurrentSkipListMap class contains a method randomLevel that outputs the following, according to The Art of Multiprocessor Programming: The randomLevel() method is designed based on empirical measurements to maintain the skiplist property. For example, in the java.util.concurrent package, for a maximal SkipList level of 31, randomLevel() returns 0 with probability 3/4, i with probability 2^(−(i+2)) for i ∈ [1, 30], and 31 with probability 2^−32. This looks like a geometric distribution, but not quite. Is there some way to neatly define this in terms of the provided random distributions, or do I have to do my own manipulation, as such: inline unsigned randomLevel() { auto randNum = distribution.operator()(engine); // distribution is std::uniform_int_distribution<> unsigned two__30{0x4000'0000}; if (randNum == 0) return 31; // p(level == 31) = 2**-31 else if (randNum >= two__30) return 0; // p(level = 0) = 0.75 else return 30 - static_cast<unsigned>(log2(randNum)); // p(level = i) = 2**-(i+2) }
This looks like a geometric distribution, but not quite. You are right, but problem is only probability of 0. Note that you can use std::geometric_distribution, by merging first two values into one. class RandomLevel { std::geometric_distribution<unsigned> distribution; std::mt19937 gen{std::random_device{}()}; public: unsigned operator()() { auto result = distribution(gen); return result > 1u : result - 1u : 0u; } }
71,350,000
71,351,370
C++ template lambda wrapper
Can anyone figure out how to make this compile ? I'm trying to wrap a lambda in another function that does something (here printing "you know what") + calling the lambda. Best would be to have automatic template parameters deduction. #include <iostream> #include <functional> #include <utility> void youKnowWhat(const std::function<void()>&& fun) { std::cout << "You know what ?" << std::endl; fun(); } template <typename... Args> auto youKnowWhatSomething(const std::function<void(Args...)>&& fun) { return [fun{std::move(fun)}](Args... args) { youKnowWhat(std::bind(fun, std::forward<Args>(args)...)); }; } int main() { const auto imHavingSomething([](const std::string& s){ std::cout << "Im having " << s << std::endl; }); const auto youKnowWhatImHavingSomething(youKnowWhatSomething(std::move(imHavingSomething))); youKnowWhatImHavingSomething("fun with templates"); youKnowWhatImHavingSomething("headaches"); }
How about #include <iostream> #include <functional> #include <utility> template <typename F> void youKnowWhat(F&& fun) { std::cout << "You know what ?" << std::endl; fun(); } template <typename F> auto youKnowWhatSomething(F&& fun) { return [fun{std::move(fun)}](auto&&... args) -> decltype(fun(std::forward<decltype(args)>(args)...), void()) { youKnowWhat([&](){fun(std::forward<decltype(args)>(args)...); }); }; } int main() { const auto imHavingSomething([](std::string s){ std::cout << "Im having " << s << std::endl; }); const auto youKnowWhatImHavingSomething(youKnowWhatSomething(imHavingSomething)); youKnowWhatImHavingSomething("fun with templates"); youKnowWhatImHavingSomething("headaches"); } Demo
71,350,907
71,599,446
SNMP++ library ignore USM model and accept every input even without auth
I am building a C++ application which purpose is, among other thing, to receive SNMP traps. For this I am using SNMP ++ library version V3.3 (https://agentpp.com/download.html C++ APIs SNMP++ 3.4.9). I was expecting for traps using no authentication to be discarded/dropped if configuration was requesting some form of authentication but it does not seem to be the case. To confirm this behavior I used the provided receive_trap example available in the consoleExamples directory. I commented every call to usm->add_usm_user(...) except for the one with "MD5" as security name : usm->add_usm_user("MD5", SNMP_AUTHPROTOCOL_HMACMD5, SNMP_PRIVPROTOCOL_NONE, "MD5UserAuthPassword", ""); I then sent a trap (matching the "MD5" security name) to the application using net-snmp : snmptrap -v 3 -e 0x090807060504030200 -u MD5 -Z 1,1 -l noAuthNoPriv localhost:10162 '' 1.3.6.1.4.1.8072.2.3.0.1 1.3.6.1.4.1.8072.2.3.2.1 i 123456 Since the application only registered User Security Model requires an MD5 password I would have though the trap would have been refused/dropped/discarded, but it was not : Trying to register for traps on port 10162. Waiting for traps/informs... press return to stop reason: -7 msg: SNMP++: Received SNMP Notification (trap or inform) from: 127.0.0.1/45338 ID: 1.3.6.1.4.1.8072.2.3.0.1 Type:167 Oid: 1.3.6.1.4.1.8072.2.3.2.1 Val: 123456 To make sure there was no "default" UserSecurityModel used instead I then commented the remaining usm->add_usm_user("MD5", SNMP_AUTHPROTOCOL_HMACMD5, SNMP_PRIVPROTOCOL_NONE, "MD5UserAuthPassword", ""); and sent my trap again using the same command. This time nothing happened : Trying to register for traps on port 10162. Waiting for traps/informs... press return to stop V3 is around 18k lines of RFC so it is completely possible I missed or misunderstood something but I would expect to be able to specify which security level I am expecting and drop everything which does not match. What am I missing ? EDIT Additional testing with SNMPD I have done some test with SNMPD and I somehow still get similar result. I have created a user : net-snmp-create-v3-user -ro -A STrP@SSWRD -a SHA -X STr0ngP@SSWRD -x AES snmpadmin Then I am trying with authPriv key : snmpwalk -v3 -a SHA -A STrP@SSWRD -x AES -X STr0ngP@SSWRD -l authPriv -u snmpadmin localhost The request is accepted with authNoPriv : snmpwalk -v3 -a SHA -A STrP@SSWRD -x AES -l AuthNoPriv -u snmpadmin localhost The request is accepted with noAuthNoPriv : snmpwalk -v3 -a SHA -A STrP@SSWRD -x AES -X STr0ngP@SSWR2D -l noauthnoPriv -u snmpadmin localhost The request is rejected. As I understand the authNoPriv must be rejected, but is accepted, this is incorrect from what I have read in the RFC and the cisco snmpv3 resume
Disclaimer I am not expert so take the following with a pinch of salt. I cannot say for the library you are using but regarding the SNMP v3 flow: In SNMPv3 exchanges, the USM is responsible for validation only on the SNMP authoritative engine side, the authoritative role depending of the kind of message. Agent authoritative for : GET / SET / TRAP Receiver authoritative for : INFORM The RFC 3414 describes the reception of message in section 3.2 : If the information about the user indicates that it does not support the securityLevel requested by the caller, then the usmStatsUnsupportedSecLevels counter is incremented and an error indication (unsupportedSecurityLevel) together with the OID and value of the incremented counter is returned to the calling module. If the securityLevel specifies that the message is to be authenticated, then the message is authenticated according to the user’s authentication protocol. To do so a call is made to the authentication module that implements the user’s authentication protocol according to the abstract service primitive So in the step 6, the securityLevel is the one from the message. This means the TRAP is accepted by the USM layer on the receiver side even if the authentication is not provided. It is then the task of the user of the TRAP to decide if the message must be interpreted or not.
71,350,929
71,351,311
Casting from long double to unsigned long long appears broken in the MSVC C++ compiler
Consider the following code: #include <iostream> using namespace std; int main(int argc, char *argv[]) { long double test = 0xFFFFFFFFFFFFFFFF; cout << "1: " << test << endl; unsigned long long test2 = test; cout << "2: " << test2 << endl; cout << "3: " << (unsigned long long)test << endl; return 0; } Compiling this code with GCC g++ (7.5.0) and running produces the following output as expected: 1: 1.84467e+19 2: 18446744073709551615 3: 18446744073709551615 However compiling this with the Microsoft Visual C++ compiler (16.8.31019.35, both 64-bit and 32-bit) and running produces the following output: 1: 1.84467e+19 2: 9223372036854775808 3: 9223372036854775808 When casting a value to an unsigned long long, the MSVC compiler won't give a value lager than the max of a (signed) long long. Am I doing something wrong?  Am I running into a compiler limitation that I do not know about? Does anyone know of a possible workaround to this problem?
You are seeing undefined behaviour because, as pointed out in the comments, a long double is the same as a double in MSVC and the 'converted' value of your 0xFFFFFFFFFFFFFFFF (or ULLONG_MAX) actually gets 'rounded' to a slightly (but significantly) larger value, as can be seen in the following code: int main(int argc, char* argv[]) { long double test = 0xFFFFFFFFFFFFFFFF; cout << 0xFFFFFFFFFFFFFFFFuLL << endl; cout << fixed << setprecision(16) << endl; cout << test << endl; return 0; } Output: 18446744073709551615 18446744073709551616.0000000000000000 Thus, when converting that floating-point value back to an unsigned long long, you are falling foul of the conversion rules specified in this Microsoft document: For conversion to unsigned long or unsigned long long, the result of converting an out-of-range value may be some value other than the highest or lowest representable value. Whether the result is a sentinel or saturated value or not depends on the compiler options and target architecture. Future compiler releases may return a saturated or sentinel value instead. This UB can be further 'verified' (for want of a better term) by switching to the clang-cl compiler that can be used from within Visual Studio. For your original code, this then gives 0 for the values on both the "2" and "3" output lines. Assuming that the clang (LLVM) compiler is not bound by the aforementioned "Microsoft Rules," we can, instead, fall back on the C++ Standard: 7.10 Floating-integral conversions      [conv.fpint] 1     A prvalue of a floating-point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type.
71,351,077
71,351,131
How to handle classes that are not copyable?
An example: class File { public: File(const char* path); File(File& other) = delete; File& operator=(File& rhs) = delete; ~File(); private: char* path; FILE* cfile; }; class Filesystem { public: Filesystem(); Filesystem(Filesystem& other); ~Filesystem(); File Search(const char* filepath) { File file(filepath); return file; } private: }; With the copy constructor and assignment operator deleted from the File class (because it shouldn't be copied), is there any way you can return it from the Search function of the filesystem or other ways to handle it?
Moveable types You can make the class moveable by adding the move constructor and move assignment operator. (Some possibly useful overview of that.) ... // rough sketch // Having the path as `char*` seems // bad (use std::string instead), // but let's stick with the example as posted) File(File&& other) : path(nullptr) , cfile(nullptr) { using std::swap; // steal the guts of the moved-from object swap(path, other.path); swap(cfile, other.cfile); } The move assignment operator can be a little bit more tricky, what with self-assigment checks. /or/ Smart pointers You can wrap instances of these classes in a smart pointer and work with those: std::shared_ptr, std::unique_ptr etc. std::unique_ptr<File> Search(const char* filepath) { auto pfile = std::make_unique<File>(filepath); ... return pfile; } This is especially helpful when you work with 3rd party classes (possibly legacy) that don't support move operations. Yes, these have heap allocation overhead, but given the overhead of opening e.g. a file or acquiring another expensive resource that prevents copying, the heap allocation overhead might well be negligible.
71,351,243
71,351,443
C++ vector insert with Iterator is not working as I expected
C++11, Input is nums = [1,2,3,4,5] void rotate(vector<int>& nums, int k) { nums.insert(nums.begin(), nums.end() - k, nums.end()); } When k = 2, I expect this function should make nums to [4,5,1,2,3,4,5] but it becomes [2,3,1,2,3,4,5] When k = 1, nums is [4,1,2,3,4,5] but when k = 4, nums is [2,3,4,5,1,2,3,4,5], which is what I wanted. What am I doing wrong? Please help.
The std::vector::insert overload that you are using has a precondition that neither the second nor the third argument are iterators into the vector itself. You are violating that precondition and therefore your program has undefined behavior.
71,351,373
71,417,216
How to force exe file to run on Nvidia GPU on windows
I have a program written in C++ language. My whole code contains only 3 files: a header file for my own class, a cpp file with code implementation for the class and a 3rd cpp file where I have the main() method. I need to make very complicated calculations, and on a normal CPU my code takes about 3 months to complete the execution. That's why I tried to run the program on my Nvidia GPU. The code was developed on Visual Studio IDE and I made an EXE file. This is what I tried to do: Went to graphics settings -> Choose the relevant Exe file -> set the file for high performance with Nvidia card. This did Not work. I open Nvidia Control Panel -> apps settings -> again, picked the relevant Exe file -> select Nvidia GPU for high performance. Also, no luck here. Both ways failed, my code is running on my Intel GPU and not on my Nvidia card. How can I force the execution of the Exe file to run on the Nvidia card? Is three a way via the command line (or any other way) to make my C++ code to be compiled and run on my Nvidia GPU?
As far as I know, there is no easy and/or automatic way to compile general C++ code to be executed in a GPU. You have to use some specific API for GPU computing or implement the code in a way that some tool is able to automatically generate the code for a GPU. The C++ APIs that I know for GPU programming are: CUDA: intended for NVIDIA GPUs only, relatively easy to use. Here you have a good introduction: https://developer.nvidia.com/blog/even-easier-introduction-cuda/ OpenCL: can be used for most of the GPUs in the market, but is not as easy to use as CUDA. An interesting feature of OpenCL is that the generated code can also run in CPU. An example here: https://www.eriksmistad.no/getting-started-with-opencl-and-gpu-computing/ SYCL: a relatively recent API for heterogeneous programming built on top of OpenCL. SYCL highly simplifies the GPU programming, I found this interesting tutorial which shows how easy to use SYCL is: https://tech.io/playgrounds/48226/introduction-to-sycl/introduction-to-sycl-2 Unfortunately, you will need to rewrite some parts of your code if you want to use one of these options. I believe that SYCL will be the easier choice and the one that will require less modifications in the C++ code (I really encourage you to take a look at the tutorial, SYCL is pretty easy to use). Also, it seems that Visual Studio already supports SYCL: https://developer.codeplay.com/products/computecpp/ce/guides/platform-support/targeting-windows
71,351,702
71,351,814
/usr/bin/ld: cannot find during linking g++
This question has already been here so many times. But I didn't find the answer. I have this .cpp file #include <clickhouse/client.h> #include <iostream> using namespace clickhouse; int main(){ /// Initialize client connection. Client client(ClientOptions().SetHost("localhost")); client.Select("SELECT l.a, l.b from table", [] (const Block& block) { for (size_t i = 0; i < block.GetRowCount(); ++i) { std::cout << block[0]->As<ColumnUInt64>()->At(i) << " " << block[1]->As<ColumnString>()->At(i) << "\n"; } } ); return 0; } and I have instantiated SO library, like written here. after that i got the following structure of /usr/local/lib directory: ~/$ ls /usr/local/lib >>libclickhouse-cpp-lib-static.a libclickhouse-cpp-lib.so in next step I trying execute compilation with g++ ~/$ g++ run.cpp -std=c++17 -o result -llibclickhouse-cpp-lib -L/usr/local/lib >>/usr/bin/ld: cannot find -llibclickhouse-cpp-lib >>collect2: error: ld returned 1 exit status I don't know what hinders create links. thank You for Your help!
ld's manual page describes the -l option as follows (irrelevant details omitted): -l namespec --library=namespec Add the archive or object file specified by namespec to the list of files to link. [...] ld will search a directory for a library called libnamespec.so If you read this very carefully, you will reach the conclusion that -llibclickhouse-cpp-lib instructs ld to search for a library named liblibclickhouse-cpp-lib.so which, obviously, does not exist. This should simply be -lclickhouse-cpp-lib.
71,352,014
71,357,710
How to safely terminate a multithreaded process
I am working on a project where we have used pthread_create to create several child threads. The thread creation logic is not in my control as its implemented by some other part of project. Each thread perform some operation which takes more than 30 seconds to complete. Under normal condition the program works perfectly fine. But the problem occurs at the time of termination of the program. I need to exit from main as quickly as possible when I receive the SIGINT signal. When I call exit() or return from main, the exit handlers and global objects' destructors are called. And I believe these operations are having a race condition with the running threads. And I believe there are many race conditions, which is making hard to solve all of theses. The way I see it there are two solutions. call _exit() and forget all de-allocation of resources When SIGINT is there, close/kill all threads and then call exit() from main thread, which will release resources. I think 1st option will work, but I do not want to abruptly terminate the process. So I want to know if it is possible to terminate all child threads as quickly as possible so that exit handler & destructor can perform required clean-up task and terminate the program. I have gone through this post, let me know if you know other ways: POSIX API call to list all the pthreads running in a process Also, let me know if there is any other solution to this problem
What is it that you need to do before the program quits? If the answer is 'deallocate resources', then you don't need to worry. If you call _exit then the program will exit immediately and the OS will clean up everything for you. Be aware also that what you can safely do in a signal hander is extremely limited, so attempting to perform any cleanup yourself is not recommended. If you're interested, there's a list of what you can do here. But you can't flush a file to disk, for example (which is about the only thing I can think of that you might legitimately want to do here). That's off limits.
71,352,306
71,352,970
How to make a timeout at receiving in boost::asio udp::socket?
I create an one-thread application which exchanges with another one via UDP. When the second is disconnecting, my socket::receive_from blocks and I don't know how to solve this problem not changing the entire program into multi-threads or async interactions. I thought that next may be a solution: std::chrono::milliseconds timeout{4}; boost::system::error_code err; data_t buffer(kPackageMaxSize); std::size_t size = 0; const auto status = std::async(std::launch::async, [&]{ size = socket_.receive_from(boost::asio::buffer(buffer), dst_, 0, err); } ).wait_for(timeout); switch (status) { case std::future_status::timeout: /*...*/ break; } But I achieved a new problem: Qt Creator (GDB 11.1) (I don't have ability to try something yet) began to fall when I am debugging. If it runs without, the solution also not always works.
PS. As for "it doesn't work when debugging", debugging (specifically breakpoints) obviously changes timing. Also, keep in mind network operations have varying latency and UDP isn't a guaranteed protocol: messages may not be delivered. Asio stands for "Asynchronous IO". As you might suspect, this means that asynchronous IO is a built-in feature, it's the entire purpose of the library. See overview/core/async.html: Concurrency Without Threads It's not necessary to complicate with std::async. In your case I'd suggest using async_receive_from with use_future, as it is closest to the model you opted for: Live On Coliru #include <boost/asio.hpp> #include <iostream> #include <iomanip> namespace net = boost::asio; using net::ip::udp; using namespace std::chrono_literals; constexpr auto kPackageMaxSize = 65520; using data_t = std::vector<char>; int main() { net::thread_pool ioc; udp::socket socket_(ioc, udp::v4()); socket_.bind({{}, 8989}); udp::endpoint ep; data_t buffer(kPackageMaxSize); auto fut = socket_.async_receive_from(net::buffer(buffer), ep, net::use_future); switch (fut.wait_for(4ms)) { case std::future_status::ready: { buffer.resize(fut.get()); // never blocks here std::cout << "Received " << buffer.size() << " bytes: " << std::quoted( std::string_view(buffer.data(), buffer.size())) << "\n"; break; } case std::future_status::timeout: case std::future_status::deferred: { std::cout << "Timeout\n"; socket_.cancel(); // stop the IO operation // fut.get() would throw system_error(net::error::operation_aborted) break; } } ioc.join(); } The Coliru output: Received 12 bytes: "Hello World " Locally demonstrating both timeout and successful path:
71,352,429
71,353,008
SDL2.dll was not found
I'm trying to set up SDL2 in C++ Visual Studio but when I run the code(just some starter code I copied) it pops up with an error box box that talks about "SDL2.dll cannot be found" I tried switching to x64 but that was no help. I can see that the dll is right next to the lib files but it just won't work.
Your problem is the lib folder is not a place that your OS will search for dependent dlls by default. To fix this you would have to help your OS find the dll. There are several methods you can use to tell your OS where to look. One is adding an entry to your PATH environment variable that contains the full path to the folder containing the dll. This site can help with setting the PATH: https://www.computerhope.com/issues/ch000549.htm As second method is to put the dll in the same folder as the executable. By default your OS probably is using the safe search option described here: The directory from which the application loaded. The system directory. Use the GetSystemDirectory function to get the path of this directory. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory. The current directory. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.***
71,352,799
71,352,953
Evaluating if ( std::function<void()> == function )?
How can I evaluate given expression (function<void()> == functor). Code example: #include <functional> using namespace std; void Foo() { } int main() { function<void()> a; // if (a == Foo) -> error } Edit: debugging details, and remove picture.
std::function::target() will retrieve a pointer to the stored callable object. And that's what you're trying to compare. You must specify the expected stored type, and target() will return nullptr if the type does not match. (This means that if std::function holds a function pointer, target() will return a pointer-to-a-function-pointer.) auto f = Foo; // This pointer existed in an earlier version of the question if (*it->target<decltype(f)>() == f) { // Success See it work in Compiler Explorer Note that because functions decay to function pointers: *it->target< decltype(Foo) >() == Foo will not work, because std::function can not possibly be holding a copy of the function Foo. You would need to decay the function, such as: *it->target< std::decay_t<decltype(Foo)> >() == Foo or: *it->target< decltype(&Foo) >() == Foo
71,352,971
71,354,055
Post a multipart/form-data HTTP request with WinHTTP
I have been trying for the past few days to send an HTTP POST request to my SpringBoot application with the Win32 API, but I'm always receiving the same error. The request is a multipart consisting of a binary file and a JSON. Sending the request via Postman works with no problems, and I'm able to receive the file and the JSON correctly. I have looked at almost every post and question regarding how to construct an HTTP request with WinHTTP, and it seems they all do exactly what I did, but for some reason I'm getting a weirdly constructed request, as seen in the WireShark image below. It seems as if the request is not recognized as several parts, but rather as one chunk of data. Looking in WireShark at the correct request which was sent with postman, shows that the request consists of all parts, just as it supposed to. Here is my code: LPCWSTR additionalHeaders = L"Accept: application/json\r\nContent-Type: multipart/form-data; boundary=----------------------------346435246262465368257857\r\n"; if (data->type == RequestType::MULTIPART) { size_t filesize = 0; char* fileData = fileToString("img.png", "rb", &filesize); WinHttpAddRequestHeaders(hRequest, additionalHeaders, -1L, WINHTTP_ADDREQ_FLAG_ADD); char postData1[] = "----------------------------346435246262465368257857\r\n" "Content-Disposition: form-data; name=\"file\"; filename=\"img.png\"\r\n" "Content-Type: image/png\r\n\r\n"; char postData2[] = "\r\n----------------------------346435246262465368257857\r\n" "Content-Disposition: form-data; name=\"newData\"\r\n" "Content-Type: application/json\r\n\r\n" "{\"dataType\":\"DEVICE_SETTINGS\"}" "\r\n----------------------------346435246262465368257857--\r\n"; if (hRequest) bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, lstrlenA(postData1) + lstrlenA(postData2) + filesize, NULL); DWORD dwBytesWritten = 0; if (bResults) bResults = WinHttpWriteData(hRequest, postData1, lstrlenA(postData1), &dwBytesWritten); if (bResults) bResults = WinHttpWriteData(hRequest,(LPCVOID) fileData, filesize, &dwBytesWritten); if (bResults) bResults = WinHttpWriteData(hRequest, postData2, lstrlenA(postData2), &dwBytesWritten); } errorMessageID = ::GetLastError(); // End the request. if (bResults) bResults = WinHttpReceiveResponse(hRequest, NULL); Valid request sent with Postman Invalid request sent with WinHTTP Postman configuration 1 Postman configuration 2 SpringBoot controller Here is the error I receive in my SpringBoot app log: 2022-03-04 14:48:34.520 WARN 25412 --- [nio-8010-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present] I would really appreciate any help here solving this mystery!
The MIME boundaries in your postdata1 and postdata2 strings are incomplete, which is why WireShark and the SpringBoot app are not parsing your data correctly. Every MIME boundary in the body data must start with a leading --, followed by the value you specified in the Content-Type's boundary attribute, followed by a trailing -- in the final termination boundary. Let's look at an simpler example that doesn't use any - in the boundary value at all, this should make it clearer to you: POST /resource HTTP/1.1 Host: ... Content-Type: multipart/form-data; boundary=myboundary\r\n"; --myboundary Content-Disposition: form-data; name="file"; filename="img.png" Content-Type: image/png <file data> --myboundary Content-Disposition: form-data; name="newData" Content-Type: application/json <json data> --myboundary-- As you can see above, and in Postman's data, the leading -- is present on each boundary, but is missing in your data: Postman's boundary attribute declares a value with 26 leading -s, and each boundary in the body data begins with 28 leading -s. Your boundary attribute declares a value with 28 leading -s, and each boundary in the body data also begins with 28 leading -s. Hence, the leading -- is missing from each boundary in your data. Simply remove 2 -s from the value in your Content-Type's boundary attribute, and then you should be fine.
71,354,023
71,355,052
Is there a standard binary representation of integer data types in c++20?
I understand that with c++20 sign magnitude and one's comp are finally being phased out in favor of standardizing two's comp. (see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0907r3.html, and http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1236r1.html) I was wondering what this meant for the implications of how much we can make assumptions about the binary representation of integers now in c++20? As I'm reading it, it seems like a lot of thought has been put into the allowed ranges, but I don't see anything that would really indicate requirements on the bit layout, nor endianness. I would thus assume that endianness is still an issue, but what about bit layout? according to the standard, is 0b00000001 == 1 always true for an int8_t? What about 0b11111111 == -1 I understand that on nearly all practical systems, the leftmost bit will be the most significant, decreasing incrementally until the rightmost and least significant byte is reached, and all systems I've tested this on seem to use this representation, but does the standard say anything about this and any guarantees we get? Or would it be safer to use a 256 element lookup table to map each value a byte can represent to a specific bit representation explicitly if we need to know the underlying representation rather than relying on this? I'd rather not take the performance hit of a lookup if I can use the bytes directly as is, but I'd also like to make sure that my code isn't making too many assumptions as portability is important.
The sign bit is required to be the most significant bit (§[basic.fundamental]/3): For each value x of a signed integer type, the value of the corresponding unsigned integer type congruent to x modulo 2N has the same value of corresponding bits in its value representation. Things only work this way if the sign bit is what would be the MSB in an unsigned. This also requires that (for example) uint8_t x = -1; will set x to 0b11111111 (since -1 reduced modulo 28 is 255). In fact, that's used as an example in the standard: [Example: The value −1 of a signed integer type has the same representation as the largest value of the corresponding unsigned type. —end example] As far as an offset representation goes, I believe it's considered impossible. The C++ standard refers to the C standard which requires (§6.2.6.2/1): If there are N value bits, each bit shall represent a different power of 2 between 1 and 2N-1, so that objects of that type shall be capable of representing values from 0 to 2N - 1 using a pure binary representation; "using a pure binary representation" is at least normally interpreted as meaning a representation like: bNbN-1bN-2...b2b1b0. I.e., where, if you count bits from 0 through N-1, each bit represents the corresponding power of 2.
71,354,571
71,354,847
Replacing specific chars with different and more chars
I'm trying to do an interesting exercise from a book with the following question: For our dynamically allocated strings, create a function replaceString that takes three parameters, each of type arrayString: source, target, and replaceText. The function replaces every occurrence of target in source with replaceText. For example, if source points to an array containing abcdabee, target points to ab, and replaceText points to xyz, then when the function ends, source should point to an array containing xyzcdxyzee. I replace every occurence of target, in this case ab, with replaceText, in this case xyz in char *. For this exercise the book uses a 0 to mark char * termination and uses a typedef for char *. I've written the following function to test replaceString out. arrayString being typedef char *arrayString void replaceStringTester() { arrayString test = new char[8]; test[0] = 'a'; test[1] = 'b'; test[2] = 'c'; test[3] = 'd'; test[4] = 'a'; test[5] = 'b'; test[6] = 'e'; test[7] = 'e'; test[8] = 0; arrayString target = new char[3]; target[0] = 'a'; target[1] = 'b'; target[3] = 0; arrayString replaceText = new char[4]; replaceText[0] = 'x'; replaceText[1] = 'y'; replaceText[2] = 'z'; replaceText[3] = 0; replaceString(test, target, replaceText); cout << test; } As well as the following function to find the length of an arrayString int length(arrayString as) { int count = 0; while (as[count] != 0) { ++count; } return count; } My idea up until now has been, iterate over the source arrayString, check does the source start with the first char of target? If it does, iterate over target and check if the rest lines up. I've written following function for it, however im uncertain if it does exactly what I drafted up. void replaceString(arrayString &source, arrayString target, arrayString replaceText) { int sourceLength = length(source); int targetLength = length(target); int replaceTextLength = length(replaceText); int targetPresent = 0; for (int i = 0; i < sourceLength; ++i) { if (source[i] == target[0]) { int count = 0; for (int k = 0; k < targetLength; ++k) { if (target[k] == source[i + k]) { ++count; } } if (count == targetLength) { ++targetPresent; } } } int newStringLength = sourceLength + (replaceTextLength - targetLength) * targetPresent + 1; arrayString newString = new char[newStringLength]; newString[newStringLength] = 0; int j = 0; int i = 0; while (j < newStringLength) { if (source[j] == target[0]) { bool targetAcquired = false; for (int k = 0; k < targetLength; ++k) { if (target[k] == source[j + k]) { targetAcquired = true; } else { targetAcquired = false; break; } } if (targetAcquired) { for(int k = 0; k < replaceTextLength; ++k) { newString[i] = replaceText[k]; ++i; } j += targetLength; } if (!targetAcquired) { newString[i] = source[j]; ++j; ++i; } } else { newString[i] = source[j]; ++j; ++i; } } delete[] source; source = newString; } Edit: I've solved it by implementing two trackers for our positions in each respective stringArray and then filtering with a boolean what is in where. Thank you for your help.
For starters using this typedef typedef char *arrayString; is a bad idea. For example if you need to declare a pointer to a constant string then this declaration const arrayString p; will not denote const char *p; It means char * const p; that is not the same as the above declaration.. And the second and the third parameters of your function should be declared as having the type const char * because they are not changed within the function, The function should be declared the following way char * replaceString( char * &source, const char *target, const char *replaceText ); Within the function you need at first to count how many times the string target is found in the string source. When using this information and the length of the string replaceText you need to allocate dynamically a new character array if it is required. When just copy the source string into the dynamically allocated array substituting the target string for the replacing string. After that you should delete the source string and assign its pointer with the newly formed string. Pat attention to that there is standard C string function strstr declared in the header <cstring> that can simplify your code. Also to find the length of a string you can use another standard C string function strlen. Otherwise you should write them yourself.
71,354,703
71,354,749
How to perfectly forward `*this` object inside member function
Is it possible to perfectly forward *this object inside member functions? If yes, then how can we do it? If no, then why not, and what alternatives do we have to achieve the same effect. Please see the code snippet below to understand the question better. class Experiment { public: double i, j; Experiment(double p_i = 0, double p_j = 0) : i(p_i), j(p_j) {} double sum() { return i + j + someConstant(); } double someConstant() && { return 10; } double someConstant() & { return 100; } }; int main() { Experiment E(3, 5); std::cout << std::move(E).sum() << "\n"; // prints: 108 std::cout << E.sum() << "\n"; // prints: 108 } This output seems expected if we consider that *this object inside the member function double sum() is always either an lvalue or xvalue (thus a glvalue) . Please confirm if this is true or not. How can we perfectly forward *this object to the member function call someConstant() inside the double sum() member function? I tried using std::forward as follows: double sum() { return i + j + std::forward<decltype(*this)>(*this).someConstant(); } But this did not have any effect, and double someConstant() & overload is the one always being called.
This is not possible in C++11 without overloading sum for & and && qualifiers. (In which case you can determine the value category from the qualifier of the particular overload.) *this is, just like the result of any indirection, a lvalue, and is also what an implicit member function call is called on. This will be fixed in C++23 via introduction of an explicit object parameter for which usual forwarding can be applied: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p0847r7.html
71,354,825
71,355,567
C++ my own class predicate is not working
I'm a complete newbie at C++. I want to create my own predicate. But the part with bool operator seems to be wrong (at least in my humble opinion). Could someone give me a hint? I don't want to change the overall structure of this idea, I'm just sure I don't understand some details about operator () implementation or something related to classes in c++. #include <iostream> #include <vector> class Predicate { private: int number = 0; public: Predicate() = default; Predicate(const int number) { this->number = number; } bool operator()(int value) const { Predicate *pred = new Predicate(); bool result = pred->operator()(value); return result; } }; class Even : public Predicate { bool operator()(int value) const { return value % 2 == 0; } }; class Negative : public Predicate { bool operator()(int value) const { return value < 0; } }; int count(const std::vector<int> &elements, const Predicate &predicate) { int count = 0; for (int index = 0; index < elements.size(); ++index) { if (predicate(elements[index])) { ++count; } } return count; } int main() { const std::vector<int> elements{-7, 12, -11, 2, 9, -4, -6, 5, 23, -1}; std::cout << count(elements, Even()) << " " << count(elements, Negative()) << std::endl; }
What you need is: define Predicate as an abstract type, implements different versions of it. Predicate as an abstract type: class Predicate { public: virtual bool operator(int v) const = 0; }; Implementing (realising) a given Predicate: class IsNegative : public Predicate { // means IsNegatives are Predicates public: virtual bool operator(int v) const { return v<0; } // realisation of the operator };
71,354,935
71,356,028
Pass method as other method callback parameter
I'm trying to give a method as a callback of another method just like that: Actions actions; Button button; int main() { actions = Actions(); button = Button(); button.onClick(actions.doSmthg); return 0; } Here is my Actions: class Actions { public: Actions(); void doSmthg(); }; and here is the Button with my attempt of implementing a callback pattern: class Button { public: Button() {}; void onClick(void (*callbackPtr)()); }; Sadly I got the following error: error: invalid use of non-static member function ‘void Actions::doSmthg()’ I've check multiple examples that suggest to use std::bind when dealing with callbacks but I'm really not sure how to make it work. Any idea to implement such a pattern in C++? Here is a live sandbox https://onlinegdb.com/nL3SIUOaI.
Method 1 You can make use of std::bind and std::function as shown below: #include <iostream> #include <functional> class Actions { public: Actions(){} void doSmthg(){ std::cout<<"do something called"<<std::endl; } }; class Button { public: Button() {}; void setFunc(std::function<void ()> eventFunction) { fn = eventFunction; } void onClick(){ std::cout<<"button clicked"<<std::endl; //call the function on the passed object fn(); } private: std::function<void ()> fn; }; int main() { Actions action; Button button; button.setFunc(std::bind(&Actions::doSmthg, action)); button.onClick(); return 0; } The output of the above program can be seen here: button clicked do something called Method 2 Here we make the onClick member function to be a member function template. #include <iostream> class Actions { public: Actions(){} void doSmthg(){ std::cout<<"do something called"<<std::endl; } }; class Button { public: Button() {}; template<typename T> void onClick(void (T::*callbackPtr)(), T obj){ std::cout<<"button clicked"<<std::endl; //call the function on the passed object (obj.*callbackPtr)(); } }; int main() { Actions action; Button button;; button.onClick<Actions>(&Actions::doSmthg, action); return 0; } The output of the above program can be seen here: button clicked do something called
71,355,654
71,355,778
Same code, one works one doesn't. What's different?
i'm an beginner programmer, this is my first time posting. I'm currently writing a snake game in c++. Most of the game wasn't so hard to implement but when it came to the tail of the snake the entire program broke. I spent like 2 hours trying to figure out what was wrong and then i decided to try to rewrite the problematic code. From my understanding i haven't changed a thing but now it works. Can someone explain to me what changed? Here is the code, the commented one is not working the other works fine: else { bool eCoada = false; for (int s = 0; s <= ntail; s++) { if (tail[s].height == j && tail[s].width == k) { eCoada = true; break; } } if (eCoada == false) cout << " "; else cout << "o"; } /* else { bool eCoada = false; for (int s = 0;s <= ntail; s++) { if (tail[s].height==j && k==tail[s].width==k) { eCoada = true; break; } if (eCoada==false) cout << " "; else cout << "o"; } }*/ Also i should mention that this code is a part of a function, if you want me to post the full code i will do so.
k==tail[s].width==k is not the same as tail[s].width == k. You may think you've written something like (k == tail[s].width) && (tails[s].width == k. But C++ doesn't automatically put in && operators like that. What actually happens is that the associativity of the == operator is left to right. So what that actually means is (k == tails[s].width) == k Assuming k and tails[s].width are ints, that means (k == tails[s].width) is a bool. The comparison between that and k will be checking if k is 0 or 1, instead of checking if it matches the width as intended. Another difference is in the placement if your if(eCoada==false) line. In your working code, it's after the for loop finishes, which means that it only executes once. In your broken code, it's inside the for loop, which means that every time the loop executes it prints a space. It also means that because you break out of the loop immediately upon setting eCoada to true, you never execute the else branch and never print an o.
71,355,745
71,356,070
Overwriting object with new object of same type and using closure using this
In the following code an object is overwritten with a new object of same type, where a lambda-expression creates a closure that uses this of the old object. The old address (this) remains the same, the new object has the same layout, so this should be ok and not UB. But what about non trivial objects or other cases? struct A { void g(A& o, int v) { o = A{.x = v, .f = [this]{ std::cout << "f" << this->x << '\n'; }}; } int x{0}; std::function<void()> f; ~A() { std::cout << "dtor" << x << '\n'; } }; void test() { A a; a.g(a, 2); a.f(); }
You are not actually replacing any object. You are just assigning from another object to the current one. o = simply calls the implicit copy assignment operator which will copy-assign the individual members from the temporary A constructed in the assignment expression with A{...}. The lambda is going to capture this from this in g, not from the temporary object. std::function will always keep a copy of the lambda referring to the original object on which g was called and since that is its parent object, it cannot outlive it. So there is no problem here. The only exception would be that you call f during the destruction of the A object, in which case using the captured pointer may be forbidden.
71,356,155
71,356,382
constructor initialisation order when Base constructor depends on reference from Derived
I have a base class which writes objects to a std::ostream with buffering. I want to call this with Obj obj; flat_file_stream_writer<Obj> writer(std::cout); writer.write(obj); writer.flush(); but also with Obj obj; flat_file_writer<Obj> writer("filename.bin"); writer.write(obj); writer.flush(); The latter call must establish a std::ofstream instance, and hold that for the duration of writing, and can then call the former version. I thought simple non-virtual inheritance would be fine here. But I have constructor initialization order issues. warning: field 'ofstream_' will be initialized after base 'flat_file_stream_writer<hibp::pawned_pw>' [-Wreorder-ctor] Because the base class depends on a reference to the object held by the derived this seems like chicken and egg and can't be solved? Is inheritance just the wrong abstraction here? A clean alternative? template <typename ValueType> class flat_file_stream_writer { public: explicit flat_file_stream_writer(std::ostream& os, std::size_t buf_size = 100) : db_(os), buf_(buf_size) {} void write(const ValueType& value) { if (buf_pos_ == buf_.size()) flush(); std::memcpy(&buf_[buf_pos_], &value, sizeof(ValueType)); ++buf_pos_; } void flush() { // could also be called in destructor? if (buf_pos_ != 0) { db_.write(reinterpret_cast<char*>(buf_.data()), // NOLINT reincast static_cast<std::streamsize>(sizeof(ValueType) * buf_pos_)); buf_pos_ = 0; } } private: std::ostream& db_; std::size_t buf_pos_ = 0; std::vector<ValueType> buf_; }; template <typename ValueType> class flat_file_writer : public flat_file_stream_writer<ValueType> { public: explicit flat_file_writer(std::string dbfilename) : dbfilename_(std::move(dbfilename)), dbpath_(dbfilename_), ofstream_(dbpath_, std::ios::binary), flat_file_stream_writer<ValueType>(ofstream_) { if (!ofstream_.is_open()) throw std::domain_error("cannot open db: " + std::string(dbpath_)); } private: std::string dbfilename_; std::filesystem::path dbpath_; std::ofstream ofstream_; };
You can put std::ofstream ofstream_; in a separate struct, then have flat_file_writer inherit from that struct using private. Base classes are initialized in the order they are declared, so make sure to inherit from that struct before flat_file_stream_writer. You can now initialize that ofstream_ before the base class flat_file_stream_writer. On closer inspection, I think you'll probably want to put all 3 of those members in the struct. See below for updated code. So this in effect means that the 3 members in ofstream_holder now come before the flat_file_stream_writer in the layout of flat_file_writer. This seems like the right solution, not just because it "squashes the compiler warning", but because now we are really getting the correct initialization order, ie construct the std::ofstream first and then pass a reference to it to flat_file_stream_writer. And during destruct the std::ofstream will be destroyed last. The original code above had this exactly the wrong way around, because the order we write in the derived constructor initializer is ignored and the actual order implemented is layout order, ie the order the members are declared. (despite the flaws of the original code, it "ran fine" for me with sanitizers etc... but was probably UB?). template <typename ValueType> class flat_file_stream_writer { public: explicit flat_file_stream_writer(std::ostream& os, std::size_t buf_size = 100) : db_(os), buf_(buf_size) {} void write(const ValueType& value) { if (buf_pos_ == buf_.size()) flush(); std::memcpy(&buf_[buf_pos_], &value, sizeof(ValueType)); ++buf_pos_; } void flush() { if (buf_pos_ != 0) { db_.write(reinterpret_cast<char*>(buf_.data()), // NOLINT reincast static_cast<std::streamsize>(sizeof(ValueType) * buf_pos_)); buf_pos_ = 0; } } private: std::ostream& db_; std::size_t buf_pos_ = 0; std::vector<ValueType> buf_; }; struct ofstream_holder { explicit ofstream_holder(std::string dbfilename) : dbfilename_(std::move(dbfilename)), dbpath_(dbfilename_), ofstream_(dbpath_, std::ios::binary) {} std::string dbfilename_; std::filesystem::path dbpath_; std::ofstream ofstream_; }; template <typename ValueType> class flat_file_writer : private ofstream_holder, public flat_file_stream_writer<ValueType> { public: explicit flat_file_writer(std::string dbfilename) : ofstream_holder(std::move(dbfilename)), flat_file_stream_writer<ValueType>(ofstream_) { if (!ofstream_.is_open()) throw std::domain_error("cannot open db: " + std::string(dbpath_)); } };
71,356,243
71,356,294
Dynamic memory allocation confusion
I saw a tutorial where the instructor dynamically allocates memory for n*int size (n is not known in advance, user would give it as an input). Just out of curiosity, I have changed the code from calloc(n,sizeof(int)) to calloc(1,sizeof(int)) and I was expecting to see an error, but I did not face an error, and the code runs smoothly. If I increment the pointer and it just continues without a problem, why should I use anything else but calloc(1,sizeof(int))? #include <iostream> using namespace std; int main(){ int n; printf("enter the size of array\n"); scanf("%d",&n); int* A = (int*)calloc(1,sizeof(int)); for(int i=0; i<n; i++){ *(A+i) = i+1; } for(int i=0; i<n; i++){ printf("%d\n", A[i]); printf("%d\n", &A[i]); } // free(A) return 0; }
I was expecting to see an error Your expectation was misguided. If you access outside the region of allocated storage, then the behaviour of the program is undefined. You aren't guaranteed to get an error. Don't access memory outside of bounds. Avoid undefined behaviour. It's very bad. The program is broken. Other advice: Avoid using calloc in C++. Avoid using using namespace std;.
71,356,247
71,358,681
RAII: do mutexes in a vector declared in a loop all unlock in the next iteration?
Suppose I have the following: // ... necessary includes class X { struct wrapper{ std::mutex mut{}; } std::array<wrapper, 20> wrappers{}; void Y() { for (auto i{0u}; i < 10; ++i) { std::vector<std::unique_lock<std::mutex>> locks_arr{}; for (auto& wrapp : wrappers) { locks.emplace_back(std::unique_lock{wrapp.mut}); } // are the mutexes in locks_arr unlocked here by RAII, // because locks_arr goes 'out of scope'? if (/* some condition */) continue; // do some other long stuff // end of loop iteration; how about here? } } } A straightforward question, elucidated in the code itself. Do the mutex locks in locks_arr unlock in the next iteration of the loop, or is there an explicit need to unlock all the mutexes one by one in both the if statement block, and at the end of the outer for-loop?
To answer my own question—yes, this is how RAII works. The vector is declared inside the body of the for loop; it is destroyed and recreated every iteration. continue also causes the execution of the rest of the loop to be short-circuited. When the vector is destructed, every object it contains is also destroyed. As such, the destructor of unique_lock is called, which unlocks the mutexes.
71,358,353
71,358,616
C++03 equivalent for auto in the context of obtaining an allocator
auto source_allocator = source.get_allocator(); Is there a way of replacing auto in the above with something C++03/98-friendly, in the event where the type of allocator is not known in advance?
Based on what you posted in the comments, it sounds like you're trying to do this inside a template. Assuming you are expecting your templated type to be a std::container, or something compatible, you can do this: typename T::allocator_type in place of auto. https://godbolt.org/z/Pda77vjox
71,358,578
71,359,064
std::disjuction not finding type in parameter pack passed to template function
I'm trying to use std::disjuction to test whether a parameter pack contains std::wstring, and nothing I've tried seems to want to make it return the value I'm expecting. Here's the code as it is currently (https://godbolt.org/z/x99M8avYE): #include <string> #include <iostream> #include <type_traits> template <typename ...Ts> using HasWS = std::disjunction<std::is_same<std::wstring,Ts>...>; template <typename T, typename ...Ts> using HasWS2 = std::disjunction<std::is_same<T,Ts>...>; template<typename... Args> void f(Args&&... args) { std::cout << HasWS<Args...>::value << std::endl; std::cout << HasWS2<std::wstring, Args...>::value << std::endl; std::cout << std::disjunction_v<std::is_same<std::wstring, Args>...> << std::endl; (std::cout << typeid(args).name() << std::endl, ...); } template <typename T, typename ...Ts> using areT = std::disjunction<std::is_same<T,Ts>...>; int main() { std::wstring wstr(L"abc"); std::string str("def"); static_assert(areT<std::wstring,std::string,std::wstring>::value); static_assert(HasWS<std::wstring,decltype(wstr),decltype(str)>::value); static_assert(std::is_same<decltype(wstr), std::wstring>::value); f(wstr, str); f(str, str); f(wstr, wstr); std::cout << std::is_same_v<decltype(wstr), std::wstring> << std::endl; return 0; } As you can see, I was experimenting with different ways to call disjuction but none of them would find the wstring and return true. I even stooped as low as printing out the types for each of the elements in the pack and using is_same to make sure that wstr was actually a wstring. What the heck is going on? Is it something to do with the pack argument to the template that I'm just not aware of?
Note that the parameter type received by f is forwarding reference Args&&, so when you pass in an lvalue wstr, Args will be instantiated as std::wstring& instead of std::wstring, you should remove the reference, e.g. template<typename... Args> void f(Args&&... args) { std::cout << HasWS<std::remove_reference_t<Args>...>::value << std::endl; std::cout << HasWS2<std::wstring, std::remove_reference_t<Args>...>::value << std::endl; std::cout << std::disjunction_v<std::is_same<std::wstring, std::remove_reference_t<Args>>...> << std::endl; } Demo
71,358,665
71,390,333
How to access Qlist of structure elements in QML
How can I access Qlist of struct elements in QML. I have implemented as follows, but the output is not working as expected. Can some one please help me how to get the values of qlist struct elements in qml sample.cpp #include "sample.h" int xVal[5] = {1,2,3,4,5}; int yVal[5] = {6,7,8,9,10}; Sample::Sample(QObject *parent) : QObject(parent) { } void Sample::prepareList() { listOfObjects obj; for(int iLoop = 0; iLoop < 5; iLoop++) { obj.xVal = xVal[iLoop]; obj.yval = yVal[iLoop]; listObj.append(obj); } } QVariant Sample::getList() { return QVariant::fromValue(listObj); } sample.h #ifndef SAMPLE_H #define SAMPLE_H typedef struct { int xVal; int yval; }listOfObjects; Q_DECLARE_METATYPE(listOfObjects); class Sample : public QObject { Q_OBJECT public: explicit Sample(QObject *parent = nullptr); Q_PROPERTY(QVariant varlist READ getList) public slots: void prepareList(); void printList(); private: QList<listOfObjects> listObj; QVariant getList(); }; #endif // SAMPLE_H main.cpp int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; qmlRegisterType<Sample>("Sample", 1, 0, "SampleObj"); const QUrl url(QStringLiteral("qrc:/main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) QCoreApplication::exit(-1); }, Qt::QueuedConnection); engine.load(url); return app.exec(); } main.qml import QtQuick 2.12 import QtQuick.Window 2.12 import Sample 1.0 Window { id: mainWindow visible: true width: 640 height: 480 title: qsTr("Hello World") property var obj: ({}) SampleObj { id: sampleId } Component.onCompleted: { sampleId.prepareList() obj = sampleId.varlist for(var i = 0; i < obj.length; i++) { console.log(obj[i]) //Expected:console.log("(x, y) = " + obj[i].xVal, obj[i].yVal ) } } } The console log is giving the outputs as qml: QVariant(listOfObjects, ) qml: QVariant(listOfObjects, ) qml: QVariant(listOfObjects, ) qml: QVariant(listOfObjects, ) qml: QVariant(listOfObjects, )
use QVariantList instead of QVariant for the return type code like below .pro file QT += quick qml SOURCES += \ ctestforqml.cpp \ main.cpp resources.files = main.qml resources.prefix = /$${TARGET} RESOURCES += resources \ Resources.qrc CONFIG += qmltypes QML_IMPORT_NAME = com.demo.cppobject QML_IMPORT_MAJOR_VERSION = 1 # Additional import path used to resolve QML modules in Qt Creator's code model QML_IMPORT_PATH = # Additional import path used to resolve QML modules just for Qt Quick Designer QML_DESIGNER_IMPORT_PATH = # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target HEADERS += \ ctestforqml.h ctestforqml.h #ifndef CTESTFORQML_H #define CTESTFORQML_H #include <QObject> #include <QQmlEngine> class CTestforQML : public QObject { Q_OBJECT QML_ELEMENT public: Q_INVOKABLE QVariantList getData() const; public: explicit CTestforQML(QObject *parent = nullptr); signals: }; #endif // CTESTFORQML_H ctestforqml.cpp #include "ctestforqml.h" #include <QJsonObject> QVariantList CTestforQML::getData() const { QVariantList list; QJsonObject json; for (int i = 0; i < 10; i ++) { json.insert("name", "demo" + QString::number(i)); json.insert("value", QString::number(i)); list.append(json); } return list; } CTestforQML::CTestforQML(QObject *parent) : QObject{parent} { } main.cpp import QtQuick import com.demo.cppobject Window { width: 640 height: 480 visible: true title: qsTr("Hello World") CTestforQML { id: testForQml } Component.onCompleted: { let val = testForQml.getData() for (let i = 0; i < val.length; i ++) { console.log(val[i].name, val[i].value); } } }
71,358,875
71,359,381
abi::__cxa_demangle cannot demangle symbols?
I am unsure why this fails to demangle symbols: #include <cxxabi.h> void _debugBacktrace(code_part part) { #if defined(WZ_OS_LINUX) && defined(__GLIBC__) void *btv[20]; unsigned num = backtrace(btv, sizeof(btv) / sizeof(*btv)); char **btc = backtrace_symbols(btv, num); unsigned i; char buffer[255]; for (i = 1; i + 2 < num; ++i) { int status = -1; size_t demangledLen = 0; memset(buffer, 0, 255); char *readableName = abi::__cxa_demangle(btc[i], buffer, &demangledLen, &status); if (status == 0) { _debug(0, part, "BT", "%s", readableName); } else { _debug(0, part, "BT", "%s [status: %i]", btc[i], status); } } free(btc); #else // debugBacktrace not implemented. #endif } Stdout: error |02:25:21: [BT:0] ./src/warzone2100(_ZNK5EcKey4signEPKvm+0x98) [0x16405da] [status: -2] error |02:25:21: [BT:0] ./src/warzone2100(_Z8recvPing8NETQUEUE+0x1ab) [0x126bc2d] [status: -2] error |02:25:21: [BT:0] ./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI21frontendMultiMessagesEb+0x7d9) [0x11ce219] [status: -2] error |02:25:21: [BT:0] ./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI3runEv+0x45) [0x11cf32b] [status: -2] error |02:25:21: [BT:0] ./src/warzone2100(_Z9titleLoopv+0x1aa) [0x1480b35] [status: -2] error |02:25:21: [BT:0] ./src/warzone2100() [0x1169cbc] [status: -2] ... ... ### BUT this works? > addr2line -f 0x16405da -C -e ./src/warzone2100 EcKey::sign(void const*, unsigned long) const /home/docker/code/lib/framework/crc.cpp:284 Compiled (C++11) under docker with: docker@b12fbaed9c6c:~/code> g++ --version g++ (SUSE Linux) 11.2.1 20210816 [revision 056e324ce46a7924b5cf10f61010cf9dd2ca10e9] docker@b12fbaed9c6c:~/code> ld --version GNU ld (GNU Binutils; openSUSE Tumbleweed) 2.37.20210803-1 Executed on host machine: > g++ --version g++ (SUSE Linux) 11.2.1 20220103 [revision d4a1d3c4b377f1d4acb34fe1b55b5088a3f293f6] > ld -version GNU ld (GNU Binutils; openSUSE Tumbleweed) 2.37.20211112-3
For one thing, you are not calling __cxa_demangle correctly. Documentation says: output_buffer A region of memory, allocated with malloc, of *length bytes, into which the demangled name is stored. If output_buffer is not long enough, it is expanded using realloc. output_buffer may instead be NULL; in that case, the demangled name is placed in a region of memory allocated with malloc. You are passing a stack buffer instead. Get rid of it (and the pointless memset), and do this instead: for (i = 1; i + 2 < num; ++i) { int status = -1; char *readableName = abi::__cxa_demangle(btc[i], NULL, NULL, &status); if (status == 0) { _debug(0, part, "BT", "%s", readableName); } else { _debug(0, part, "BT", "%s [status: %i]", btc[i], status); } free(readableName); } Update: The second problem is that you appear to be expecting that __cxa_demangle() will ignore any characters that aren't part of the mangled name, and demangle the rest. (You didn't show what the actual content of btc[i] is, but from the output it appears to contain strings like ./src/warzone2100(_ZNK5EcKey4signEPKvm+0x98) [0x16405da]). (Re-reading the code you posted, btc[i] comes from backtrace_symbols, which is documented to return function name, a hexadecimal offset into the function, and the actual return address, so definitely some "extra" cruft __cxa_demangle() isn't expecting.) As the following test demonstrates, __cxa_demangle() does not ignore anything; it needs mangled name, not "stuff which contains mangled name". #include <cxxabi.h> #include <string.h> #include <array> #include <iostream> int main() { const std::array<const char *, 5> bt = { "./src/warzone2100(_ZNK5EcKey4signEPKvm+0x98) [0x16405da]", "./src/warzone2100(_Z8recvPing8NETQUEUE+0x1ab) [0x126bc2d]", "./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI21frontendMultiMessagesEb+0x7d9) [0x11ce219]", "./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI3runEv+0x45) [0x11cf32b]", "./src/warzone2100(_Z9titleLoopv+0x1aa) [0x1480b35]", }; std::cout << "Wrong way:" << std::endl << std::endl; for (const char* p : bt) { int status; char *demangled = abi::__cxa_demangle(p, NULL, NULL, &status); std::cout << p << " " << status << std::endl; free(demangled); } auto trim = [](const char *in, char *out) { const char *begin = strchr(in, '_'); const char *end = strchr(begin, '+'); memcpy(out, begin, end - begin); out[end - begin] = '\0'; }; std::cout << std::endl << "Right way:" << std::endl << std::endl; for (const char* p : bt) { int status; char buf[1024]; trim(p, buf); char *demangled = abi::__cxa_demangle(buf, NULL, NULL, &status); std::cout << buf << " -> " << demangled << " " << status << std::endl; free(demangled); } } Using (Debian 11.2.0-14), I get: g++ -g foo.cc && ./a.out Wrong way: ./src/warzone2100(_ZNK5EcKey4signEPKvm+0x98) [0x16405da] -2 ./src/warzone2100(_Z8recvPing8NETQUEUE+0x1ab) [0x126bc2d] -2 ./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI21frontendMultiMessagesEb+0x7d9) [0x11ce219] -2 ./src/warzone2100(_ZN27WzMultiplayerOptionsTitleUI3runEv+0x45) [0x11cf32b] -2 ./src/warzone2100(_Z9titleLoopv+0x1aa) [0x1480b35] -2 Right way: _ZNK5EcKey4signEPKvm -> EcKey::sign(void const*, unsigned long) const 0 _Z8recvPing8NETQUEUE -> recvPing(NETQUEUE) 0 _ZN27WzMultiplayerOptionsTitleUI21frontendMultiMessagesEb -> WzMultiplayerOptionsTitleUI::frontendMultiMessages(bool) 0 _ZN27WzMultiplayerOptionsTitleUI3runEv -> WzMultiplayerOptionsTitleUI::run() 0 _Z9titleLoopv -> titleLoop() 0
71,358,961
71,359,024
C++ read only integers in an fstream
How do I read in a file and ignore nonintegers? I have the part down where I remove the ',' from the file, but also need to remove the first word as well. #include <iostream> #include <fstream> #include <sstream> using namespace std; above is all the STL I am using. string line, data; int num; bool IN = false; ifstream file; file.open(filename); if (!file) { cout << "File is not loading" << endl; return; } while (getline(file, line)) { stringstream ss(line); while (getline(ss, data, ',')) { if (!stoi(data)) { break; } else { num = stoi(data); if (IN == false) { //h(num); //IN = true; } } } } The file I am trying to read from is 3 Andrew A,0,1 Jason B,2,1 Joseph C,3,0 Basically, I am able to just completely ignore the names. I just need the numbers
You already know how to read line-by-line, and break up a line into words based on commas. The only problem I see with your code is you are misusing stoi(). It throws an exception on failure, which you are not catching, eg: while (getline(ss, data, ',')) { try { num = stoi(data); } catch (const exception&) { continue; // or break; your choice } // use num as needed... } On the other hand, if you know the 1st word of each line is always a non-integer, then just ignore it unconditionally, eg: while (getline(file, line)) { istringstream ss(line); getline(ss, data, ','); // or: // ss.ignore(numeric_limits<streamsize>::max(), ','); while (getline(ss, data, ',')) { num = stoi(data); // use num as needed... } }
71,359,065
71,363,890
Group pairs of elements based on connecting element in C++
Assume I have pair of integers like: [(1,2), (3,4), (2,3), (3,5), (7, 8), (7,9)] and I would like to sort the pairs into unique groups based on connected elements amongst them i.e. if elements share a common element with one other pair in the same group, then they should be put into the same group. So in the example above, we will end up with two groups: Group1: (1,2), (2,3), (3,4), (3,5) Group2: (7,8), (7, 9) The key is that there should be at least one reference that appears in a previous pair (i.e. this is the definition of connected pairs), and this previous pair can be any one of the previous pairs, and not the one directly preceding it. If there are no "connected pairs", then the pair should be separated to a new group by itself I understand that this can be done with graphs, but would anyone be able to suggest the most efficient, and easy to implement solution in C++? Thanks!
Assumptions: Pairs are ordered. (a,a),(a,b),(b,a) is a valid input. Yes this problem can be solved using an undirected graph. For each given pair (a, b), create an undirected edge between a and b. Now traverse this graph to find its connected components. Remember the component of each node, eg. by coloring them. Finally for all input pairs check the component they belong to (aka color) and add it to that group. Sort each group individually and output. Time complexity Let n be the number of pairs in input. Traversal: O(n). There are O(n) nodes and O(n) edges in the graph we built. For given C++ code below - we will visit each edge at most twice (due to undirected graph). Any already visited node is returned from the first line itself, which happens for each incident edge on that node. Count of such incident edges over all nodes is O(n). Sorting: O(n * log n) since maximum size of group can be O(n) Total: O(n * log n) Sample code in C++17: I am storing the graph as an adjacency list adj and using depth first traversal dfs. Assuming the input integers fit into an int, you can also use vectors instead of unordered_maps if they are further bounded. #include <iostream> #include <unordered_set> #include <unordered_map> #include <vector> #include <algorithm> using namespace std; unordered_set<int> vis; unordered_map<int, vector<int>> adj; void dfs(int u, vector<int>& cur_group) { if (vis.count(u)) return; vis.insert(u); cur_group.push_back(u); for (auto v: adj[u]) { dfs(v, cur_group); } }; int main() { vector<pair<int, int>> input = {{4,3},{1,9},{7,9},{2,4},{3,2},{9,7},{9,9}}; // create undirected graph for (auto [u, v]: input) { adj[u].push_back(v); adj[v].push_back(u); } int component_count = 0; unordered_map<int, int> color; // traverse all nodes and color all nodes reachable. for (auto [u, v]: input) { // If u is traversed v must be traversed as they are adjacent if (vis.count(u) == 0) { vector<int> cur_group; dfs(u, cur_group); for (int v: cur_group) { color[v] = component_count; } component_count++; } } // push input pairs into their corresponding color component vector<vector<pair<int, int>>> components(component_count); for (auto p: input) { components[color[p.first]].push_back(p); } // sort and output each color component separately for (auto& component: components) { sort(component.begin(), component.end()); for (auto [u, v]: component) { cout << '(' << u << ',' << v << "),"; } cout << endl; } return 0; } Output: (2,4),(3,2),(4,3), (1,9),(7,9),(9,7),(9,9),
71,359,084
71,359,181
String subscript out of range error for code that traverses string c++
I am trying to count the count the number of positive numbers, negative numbers and zeros in a string of space separated integers. The number of integers in the input string is specified by the user. The code compiles fine, however every time I try to run it, it crashes with the error "Debug Assertion Failed. ... Expression: String subscript out of range". #include <iostream> #include <string> #include <iomanip> int main() { int i = 0; int n, x; int positives = 0; int negatives = 0; int zeros = 0; std::string ip; char space = ' '; std::cin >> n; std::cin >> ip; while (i < n) { if (ip[i] != space) { x = (ip[i]); if (x > 0) { positives++; } else if (x < 0) { negatives++; } else if (x == 0) { zeros++; } } i++; } }
For a start std::cin >> some_string_var is going to stop at the first white space character it finds, so there's little point in using that to search for spaces separating words. You would be better off just reading in integers and just comparing them directly with zero. Here's how you could do with with the MNC (minimum necessary change) on your code: #include <iostream> int main() { int i = 0; int n; int positives = 0; int negatives = 0; int zeros = 0; int value; std::cin >> n; while (i < n) { std::cin >> value; if (value > 0) positives++; else if (value < 0) negatives++; else zeros++; i++; } std::cout << "p=" << positives << ", n=" << negatives << ", z=" << zeros << '\n'; } A sample run follows, keeping in mind the initial 4 is a count rather than one of the values: pax:~> ./prog 4 0 1 2 -99 p=2, n=1, z=1 If you were looking for something a little robust, you could use something like this: #include <iostream> int main() { int quant, pos = 0, neg = 0, zer = 0, value; std::cout << "How many input values? "; if (! (std::cin >> quant )) { std::cout << "\n*** Invalid input.\n"; return 1; } if (quant < 0) { std::cout << "\n*** Negative quantity input.\n"; return 1; } for (int count = 1; count <= quant; ++count) { std::cout << "Enter value #" << count << ": "; if (! (std::cin >> value )) { std::cout << "\n*** Invalid input.\n"; return 1; } if (value > 0.0) pos++; else if (value < 0.0) neg++; else zer++; } std::cout << "Positive value count: " << pos << '\n'; std::cout << "Negative value count: " << neg << '\n'; std::cout << "Zero value count: " << zer << '\n'; } It's a little more user friendly on communicating with the user (both in terms of what is requested, and the results generated). It's also a little more robust in detecting bad input.
71,359,227
71,359,267
Is it safe to use a reinterpret_cast if I can guarantee the correct type was used to allocate the memory?
I am trying to make my C++ code cross platform. On Windows I am using the Windows.h header file and on macOS and Linux I use the unistd.h header file. I am calling a function if the OS is windows which takes a char* type. The equivalent call for mac and linux takes char**. I currently have a function that takes a void* type so that I can have 1 function for both cases. I then check the operating system and reinterpret_cast to the correct type. void DoSomething(void* thing) { #if defined(__APPLE__) || defined(__linux__) // Init thing as char** thing = new char*[...]; thing[0] = new char[...]; . . . UnixFunction(reinterpret_cast<char**>(thing)); #elif defined(_WIN32) // Init thing as char* thing = new char[...]; WindowsFunction(reinterpret_cast<char*>(thing)); #endif } int main() { void* thing; DoSomething(thing); return 0; } Regardless if I should do this, is this safe or is this undefined behavior?
It sounds like what you're asking about would be safe. However, your code looks a bit off: void DoSomething(void* thing) { thing = new char*[...]; That will leave the caller with no access to the allocated memory, because thing is an addressed the caller passed in but then you immediately overwrote the address, so you have no way to write into the memory the caller gave you, and/or the caller has no way to know what memory you allocated. You could take (void*& thing) so that your changes to the pointer are visible to the caller, for example. Or just return the pointer from the function instead. If you fix that design error, reinterpret_cast won't itself be a problem. You can even cast pointers to uintptr_t or intptr_t and back again using reinterpret_cast if you want a way to just pass addresses around without needing to know the type until you use them again.
71,359,388
71,359,448
How to construct a class with user inputs and no variables?
One of my assignments involve creating a class using a constructor with parameters, where the arguments sent to create the object are based on user input. #include <iostream> #include "HRCalc_lib.h" HeartRates::HeartRates(const std::string &first, const std::string &last, int day, int month, int year){ firstName = first; lastName = last; setBirthYear(year); setBirthMonth(month); setBirthDay(day); } Note: This is from a .cpp file where member functions are fully written. All other class syntax is in a header file. I approached creating an object with this constructor using std::cin with variables through main. #include <iostream> #include "HRCalc_lib.h" int main(){ std::string first, last; int Bday, Bmonth, Byear; std::cout << "enter your name (first last) & date of birth (dd mm yyyy) seperated by spaces" << std::endl; std::cin >> first >> last >> Bday >> Bmonth >> Byear; HeartRates person1(first, last, Bday, Bmonth, Byear); //further code would be implemented here return 0; } Is there a more direct way of creating the same object without the need for variables in main?
Is there a more direct way of creating the same object without the need for variables to store user inputs in main? Yes, there is. You can use operator overloading. In particular, you can overload operator>> as shown below: #include <iostream> #include<string> class HeartRates { private: std::string first, last; int day = 0, month = 0, year = 0; //friend declaration for overloaded operator>> friend std::istream& operator>>(std::istream& is, HeartRates& obj); }; //implement overloaded operator<< std::istream& operator>>(std::istream& is, HeartRates& obj) { is >> obj.first >> obj.last >> obj.day >> obj.month >> obj.year; if(is)//check that input succeded { //do something here } else //input failed: give the object a default state { obj = HeartRates(); } return is; } int main(){ HeartRates person1; //NO NEED TO CREATE SEPARATE VARIABLES HERE AS YOU WANT std::cout << "enter your name (first last) & date of birth (dd mm yyyy) seperated by spaces" << std::endl; std::cin >> person1; //this uses overloaded operator>> return 0; } The output of the above program can be seen here. Here when we wrote: std::cin >> person1; we're using the overloaded operator>> and so you don't need to create separate variables inside main.
71,359,572
71,372,935
How do I use Serial Monitor in Arduino to give word like my name, "DASH" and only that to blink an LED?
So,I have a task at hand and that is to use a word, like my name "DASH" as input to Serial Monitor in Arduino so that the LED in the ESP32-WROOM-32 blinks and otherwise, it won't. I am fairly new to the Arduino side and would really appreciate any guidance at all, even though it may be very little info so feel free please. I am using ESP32-WROOM-32 module and no outside LED, the one that blinks blue in the module itself. Here's what I have tried: String incomingString; int LED_BUILTIN=2; void setup() { Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); } void loop() { if (Serial.available()>0) { String incomingString=Serial.readString(); Serial.println("Enter 'Dhaval' to blink thy LED in hue of blue!"); if (incomingString=="Dhaval"){ Serial.println("You have entered 'Dhaval', needless to say enjoy the beautiful baby blue LED."); digitalWrite(LED_BUILTIN, HIGH); } else { Serial.println("Seems that you've entered anything else but Dhaval, please just enter 'Dhaval'."); } } } I am aware that in this code it would be best to use for loop and if conditions to make it take each character once at a time, but not sure how to achieve that, plus I have a feeling that it may just work with this string defined as when I get to read the entry as to what I have entered and get to print it with Serial.print command it shows exactly the same string. What I have also thought about is using the above loops as mentioned giving them input parameters as ASCII values by each turn and confirm it and then let the final output say the whole word DASH and that only when verified lets the LED blink. Thank you in advance.
So, upon carefully reading and understanding more about Arduino and serial monitor, I feel ready to say that the problem wasn't the code, in fact it was fine. The problem was me and the serial monitor showing the output options. It should have been "No new line" and in my case it had always been "Newline" which is what made the string input given by the user add new line to the string entered increasing the length of the string. Here is the code, and it works just fine given that the setting of the Serial Monitor output has been changed to "No line ending": #include<string.h> String s1; String s2("Dhaval"); int LED_BUILTIN=2; void setup() { Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); } void loop() { if (Serial.available()>0) { String s1=Serial.readString(); Serial.println("Enter 'Dhaval' to blink thy LED in hue of blue!"); Serial.println(s1); if (s1.equals(s2)){ Serial.println("You have entered 'Dhaval', needless to say enjoy the beautiful baby blue LED."); digitalWrite(LED_BUILTIN, HIGH); delay(500); digitalWrite(LED_BUILTIN, LOW); delay(1000); } else { Serial.println("Seems that you've entered anything else but Dhaval, please just enter 'Dhaval'."); } } } Hope it helps some day, to someone. And if you want to use "Newline" the string input will have an extra length than original intention in which case, you can just trim the string by the .trim function of the string. No issues.
71,359,610
71,359,664
Templating a Derived class of a Base class that is already templated
I get the compiler error "Use of undeclared identifier '_storage'" #include <iostream> struct Storage{ int t; }; struct DerivedStorage : Storage{ int s; }; struct DerivedStorage2 : DerivedStorage{ int r; }; template<typename DS = Storage> class Base{ public: DS* _storage = nullptr; Base(){ _storage = new DS(); } void m(){ _storage->t++; } }; template<typename DS = DerivedStorage> class Derived : public Base<DS>{ public: void m2(){ _storage->s++; //error here } }; template<typename DS = DerivedStorage2> class Derived2 : public Derived<DS>{ public: void m3(){ _storage->r++; //error here } }; int main(int argc, const char * argv[]) { Derived2<DerivedStorage2> t; for(int i = 0;i<3;i++){ t.m3(); } return 0; } Any idea what the problem is ?
Because Derived itself does not have a member variable named _storage, use this->_storage to access Base's _storage instead. void m2(){ this->_storage->s++; } Demo
71,359,638
71,359,749
Thread 1: EXC_BAD_ACCESS (code=257, address=0x100000001) in C++
I've written a program that will check if a given string has all characters unique or not. I usually write in Python, but I'm learning C++ and I wanted to write the program using it. I get an error when I translate Python into C++: Thread 1: EXC_BAD_ACCESS (code=257, address=0x100000001) I am using Xcode. When I run this program, I get the above error: #include <iostream> using namespace std; int isUnique(string str) { int arr[] = {}; for (int i = 0; i < str.length(); ++i) { arr[i] = 0; } for (int j = 0; j < str.length(); ++j) { arr[j] += 1; } for (int k = 0; k < sizeof(arr)/sizeof(arr[0]); ++k) { if (arr[k] > 1) { return false; } } return true; } int main() { string str; cout << "Enter a string: "; getline(cin, str); cout << isUnique(str) << endl; } Here is the original code I wrote in Python: def is_unique(string): chars = [] for i in range(len(string)): chars.append(0) chars[string.find(string[i])] += 1 # I am using find and not just i because I want the first occurrence of the substring in the string to update it to 2 if it happens twice, 3 if it is thrice, etc. for k in chars: if k > 1: # Note that I'm checking for > 1 return False return True # Driver code if __name__ == "__main__": print(is_unique("abcd")) When run, this outputs True, which means that the string has unique characters only. Change print(is_unique("abcd") to something else with a word without only unique characters, such as print(is_unique("hello") to get False. When I translated this into C++, the Xcode terminal shows '(lldb)', and the Xcode editor opens up a file 0_mh_execute_header and its contents are as follows: dsa`_mh_execute_header: 0x100000000 <+0>: .long 0xfeedfacf ; unknown opcode 0x100000004 <+4>: .long 0x0100000c ; unknown opcode 0x100000008 <+8>: udf #0x0 0x10000000c <+12>: udf #0x2 0x100000010 <+16>: udf #0x12 0x100000014 <+20>: udf #0x638 0x100000018 <+24>: .long 0x00218085 ; unknown opcode 0x10000001c <+28>: udf #0x0 0x100000020 <+32>: udf #0x19 0x100000024 <+36>: udf #0x48 0x100000028 <+40>: .long 0x41505f5f ; unknown opcode 0x10000002c <+44>: saddwt z7.h, z10.h, z26.b 0x100000030 <+48>: udf #0x4f52 0x100000034 <+52>: udf #0x0 0x100000038 <+56>: udf #0x0 0x10000003c <+60>: udf #0x0 0x100000040 <+64>: udf #0x0 0x100000044 <+68>: udf #0x1 0x100000048 <+72>: udf #0x0 0x10000004c <+76>: udf #0x0 0x100000050 <+80>: udf #0x0 0x100000054 <+84>: udf #0x0 ... NOTE: ... in the above means that it continues on. Stack Overflow allows only 30000 characters in the body, but this will exceed 950000 On line 1, Xcode shows an error: Thread 1: EXC_BAD_ACCESS (code=257, address=0x100000001) on the right side of the file (like it usually does when there are compiler issues). Do you know how to solve this?
The problem is here: int arr[] = {}; The array you're creating has length 0 which you can verify using cout << "sizeof(arr): " << sizeof(arr) << endl; The error occurs when you try to access values beyond the size of the array here: arr[i] = 0; What you need to do is specify a size of the array, for example int arr[128]; which creates an array that can hold 128 ints, which covers the range of 7-bit-ASCII. Or use a vector, which you can change the size of. I will also point out that the logic as it is doesn't work, what you might want to do is int isUnique(string str) { // Create an array that holds 128 ints and initialize it to 0 int arr[128] = {0}; // First loop no longer needed for (int i = 0; i < str.length(); ++i) { // Increment count for cell that corresponds to the character char c = str[i]; arr[c] += 1; } // Note that you can reuse variable name when previous one // has fallen out of scope for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); ++i) { if (arr[i] > 1) { return false; } } return true; } I suggest you read more on the C++ memory model.
71,359,686
71,360,087
Is there a scenario where adding a const qualifier to a local variable could introduce a runtime error?
Here's an (admittedly brain-dead) refactoring algorithm I've performed on several occasions: Start with a .cpp file that compiles cleanly and (AFAICT) works correctly. Read through the file, and wherever there is a local/stack-variable declared without the const keyword, prepend the const keyword to its declaration. Compile the .cpp file again If any fresh compile-time errors are reported, examine the relevant lines of code to determine why -- if it turns out the local-variable legitimately does need to be non-const, remove the const keyword from it; otherwise fix whatever underlying issue the const keyword's addition has revealed. Goto (3) until the .cpp file again compiles cleanly Setting aside for the moment whether or not it's a good idea to "const all the local variables", is there any risk of this practice introducing a run-time/logic error into the program that wouldn't be caught at compile-time? AFAICT this seems "safe" in that it won't introduce regressions, only compile-time errors which I can then fix right away; but C++ is a many-splendored thing so perhaps there is some risk I haven't thought of.
If you're willing to accept a contrived example, you could enter the world of undefined behavior. void increment(int & num) { ++num; } int main() { int n = 99; increment(const_cast<int&>(n)); cout << n; } The above compiles and outputs 100. The below compiles and is allowed to do whatever it wants (but happened to output 99 for me). Modifying a const object through a non-const access path results in undefined behavior. void increment(int & num) { ++num; } int main() { const int n = 99; increment(const_cast<int&>(n)); cout << n; } Yes, this is contrived because why would someone do a const_cast on a non-const object? On the other hand, this is a simple example. Maybe in more complex code this might actually come up. Shrug I won't claim that this is a big risk, but it does fall under "any risk", as stated in the question.
71,359,711
71,359,836
Efficient way to perform summation to infinite in c++
I am new to c++ and I am trying to implement a function that has a summation between k=1 and infinite: Do you know how summation to infinite can be implemented efficiently in c++?
Do you know how summation to infinite can be implemented efficiently in c++? Nothing of this sort, doing X untill infinity to arrive at any finite result can be done in any language. This is impossible, there is not sugar coated way to say this, but it is how it is for digital computers. You can likely however make approximations. Example, a sin x is simply an expression that goes on to infinity. But to compute sin x we don't run the loop till infinity, there will be approximations made saying the terms after these are so small they are within the error bounds. And hence ignored. You have to do a similar approach. Assuming t-t1 is always positive, there will come a k where the term (k.pi/2)^2 is so big that 1/e^(...) will be very small, say below 0.00001 and say you want your result to be in an error range of +- 0.001 and so if the series is convergent (look up converging series) then you can likely ignore these terms. Essentially it's a pen and paper problem first that you can then translate to your code.
71,359,894
71,359,941
Why is my bool return statement returning something other than 0 or 1?
I have a bool function that performs some calculations and checks to see if certain conditions are true. If so, it returns true or false, as a bool function should. However, when it is true, instead of returning 1, it returns random numbers, such as 48, 240, 112, 224, etc. I'm sure you want the code ... here it is: bool isHappy(int n) { if (n < 10) return false; int sumSquares = 0; vector<int> nums; string length = to_string(n); for (int i = 0; i < length.size()-1; i++) { nums.push_back(n % 10); if (n >= 10) n = n / 10; } for (int i = 0; i < nums.size(); i++) { sumSquares += (nums[i] * nums[i]); } sumSquares += (n * n); if (sumSquares == 1) { return true; // <--This is the line that seems to cause the problem } else { isHappy(sumSquares); } return 0; } int main() { int testNumber = 19; cout << isHappy(testNumber); }
Looks like your attempt to implement recursive function is not correct. isHappy(sumSquares); should probably be return isHappy(sumSquares);
71,359,982
71,359,992
Is there a way to limit the number of times we type template <typename T> in the cpp file?
In my cpp file, before every function I need to include the line: template <typename T> Is there some short hand notation so that, instead of typing this before every function, I can type the statement just once for a group of functions ? Also, I need to include <T> after the class name, for example: void MyClassName<T>::setDefaultValues() Is there some way I can group all the template functions so I don't have to repeatedly type this for each function ?
Nope. If you need it for each function, then the compiler needs to be told this directly before each function. A slightly shorter way is of course template <class T> And we could get even shorter if we resort to macros.
71,360,562
71,360,728
do-while in fibonacci sequence repeating answer
I made a program about Fibonacci program. I would like to repeat the program so I used do-while loop. However, it seems like the last two numbers from the previous result keep coming. It is supposed to reset back to the first term. Please help me how to get there. #include<iostream> using namespace std; void printFibonacci(int n){ static int n1=1, n2=1, n3=0; if(n>0){ n3 = n1 + n2; n1 = n2; n2 = n3; cout<<n3<<" "; printFibonacci(n); } } int main(){ int n; cout<<"Enter the number of elements: "; cin>>n; cout<<"Fibonacci Series: "; cout<<"0 "<<"1 "; printFibonacci(n-2); //n-2 because 2 numbers are already printed return 0; }
When you are running the code for first time, the values of variables t1,t2 and nextTerm are changing. So before repeating the same code again you need to set the default values of those variables again. Simply try this: #include <iostream> using namespace std; int main (){ int i, n, t1=1, t2=1, nextTerm=0; cout << "Fibonacci Program" << endl; do{ t1=1; t2=2; nextTerm=0; cout << "How many elements? "; cin >> n; if(n>=1){ cout << "Sequence: "; for (int i = 1; i <= n; ++i){ if(i == 1) { cout << t1 << " "; continue; } if(i == 2) { cout << t2 << " "; continue; } nextTerm = t1 + t2; t1 = t2; t2 = nextTerm; cout << nextTerm << " "; } cout << endl; } else{ cout << "Thank you for using the program." << endl; } } while(n>=1); return 0; }
71,360,576
71,360,661
The meaning of __ and __ in clang variables and functions
In clang's standard library, what do the _ and __ on variables mean? Here is a part of string_view. inline void __throw_out_of_range(const char*__msg) { throw out_of_range(__msg); } // __str_find_first_not_of template<class _CharT, class _SizeT, class _Traits, _SizeT __npos> inline _SizeT __str_find_first_not_of(const _CharT *__p, _SizeT __sz, const _CharT* __s, _SizeT __pos, _SizeT __n) _NOEXCEPT
_ and __ are just part of the identifier. They don't have any other special meaning. However, identifiers containing a double underscore or starting with an underscore followed by an upper-case letter are reserved for the standard library. The user code is not allowed to declare them or define them as macro. The standard library uses only such reserved identifiers for internal use to make sure that it doesn't interfere with any user code that is supposed to be valid. For example this is a valid program: #define sz #define SizeT #include<string_view> int main() {} If the standard library implementation shown in the question was using just sz and SizeT instead of __sz and _SizeT, this would fail to compile. However #define __sz #define _SizeT #include<string_view> int main() {} is not a valid program and therefore it is ok if it fails to compile.
71,360,650
71,360,722
How to pass a set of different kinds of templated components to a function?
I have components: struct ComponentStorage : Storage{ ... }; template<typename T = ComponentStorage> class Component{ public: T* storage; ... } There are derived classes of the form: struct Component2Storage : Storage{ ... }; template<typename T = Component2Storage> class Component2 : public Component<T>{...} There are multiple levels of inheritance both for Component and for Storage. My question has to do with functions that with take a Component as input, for example: void myFunction(unordered_set<Component*> components){...} // This won't compile How do I modify my function so I can pass a set containing different kinds of components which may be using different kinds of storage? The actual function doesn't treat different kinds of components differently.
If you need to store different components in the same container, you need polymorphism. So you need your Components to have a common base class, to be able to treat them as such. struct ComponentStorage : Storage{ ... }; class ComponentBase { // ... define your common interface } template<typename T = ComponentStorage> class Component : public ComponentBase{ public: T* storage; ... } Now you could treat all components as ComponentBase* and handle them through the common interface defined. Storing a std::variant<...all the component types> or std::any in the set could also be an option, but it comes with it's own set of pros and cons.
71,360,896
71,360,934
Is this gcc and clang optimizer bug with minmax and structured binding?
This program, built with -std=c++20 flag: #include <iostream> using namespace std; int main() { auto [n, m] = minmax(3, 4); cout << n << " " << m << endl; } produces expected result 3 4 when no optimization flags -Ox are used. With optimization flags it outputs 0 0. I tried it with multiple gcc versions with -O1, -O2 and -O3 flags. Clang 13 works fine, but clang 10 and 11 outputs 0 4198864 with optimization level -O2 and higher. Icc works fine. What is happening here? The code is here: https://godbolt.org/z/Wd4ex8bej
The overload of std::minmax taking two arguments returns a pair of references to the arguments. The lifetime of the arguments however end at the end of the full expression since they are temporaries. Therefore the output line is reading dangling references, causing your program to have undefined behavior. Instead you can use std::tie to receive by-value: #include <iostream> #include <tuple> #include <algorithm> int main() { int n, m; std::tie(n,m) = std::minmax(3, 4); std::cout << n << " " << m << std::endl; } Or you can use the std::initializer_list overload of std::minmax, which returns a pair of values: #include <iostream> #include <algorithm> int main() { auto [n, m] = std::minmax({3, 4}); std::cout << n << " " << m << std::endl; }
71,361,112
71,361,186
Structured bindings in foreach loop
Consider fallowing peace of code: using trading_day = std::pair<int, bool>; using fun_intersection = vector<pair<int, bool>>; double stock_trading_simulation(const fun_vals& day_value, fun_intersection& trade_days, int base_stock_amount = 1000) { int act_stock_amount = base_stock_amount; for(auto trade : trade_days) { if (trade.second == BUY)// how to change it to trade.action? { } else { } } } What I would like to do is to instead of referring to pair as .first and .second I would want to refer to them as .day and .action, is it possible in any practical way to use c++17 or earlier versions? I tried doing something like this: for(auto[day,action] trade : trade_days) however it does not compile.
As said by user17732522, you can use range-based for loops for this purpose as such: #include <iostream> #include <vector> using trading_day = std::pair<int, bool>; using fun_intersection = std::vector<std::pair<int, bool>>; int main() { fun_intersection fi({ {1, true}, {0, true}, {1, false}, {0, false} }); for (auto& [day, action] : fi) { if (day == 1 && action == true) std::cout << "Success!" << std::endl; else std::cout << "Fail!" << std::endl; } } Output: Success! Fail! Fail! Fail!
71,361,149
71,361,212
C++ concept: check if a method/operator exists no matter what return type is
Suppose I am writing a template function that wants to call operator+= on its template parameter and does not care whether it returns the new value (of type T), a void, or whatever else. For example: template<class T> void incrementAll(T *array, int size, T value) { for (int i = 0; i < size; ++i) { array[i] += value; } } I want to have a constraint on this function: to make it require a concept on T. However, I couldn't find one that does not have any requirement on the return type. The only idea I could come up with was std::convertible_to<void> (because we can convert any value to void, right?), but it fails: #include <concepts> template<class T> concept Incrementable = requires(T a, T b) { {a += b} -> std::convertible_to<void>; }; template<class T> requires Incrementable<T> void incrementAll(T *array, int size, T value) { for (int i = 0; i < size; ++i) { array[i] += value; } } int main() { int arr[] = {1}; incrementAll(arr, 1, 1); } nikolay@KoLin:~$ g++ another_tmp.cpp -std=c++20 -fconcepts-diagnostics-depth=10 another_tmp.cpp: In function ‘int main()’: another_tmp.cpp:17:21: error: no matching function for call to ‘incrementAll(int [1], int, int)’ 17 | incrementAll(arr, 1, 1); | ~~~~~~~~~~~~^~~~~~~~~~~ another_tmp.cpp:9:6: note: candidate: ‘template<class T> requires Incrementable<T> void incrementAll(T*, int, T)’ 9 | void incrementAll(T *array, int size, T value) { | ^~~~~~~~~~~~ another_tmp.cpp:9:6: note: template argument deduction/substitution failed: another_tmp.cpp:9:6: note: constraints not satisfied another_tmp.cpp: In substitution of ‘template<class T> requires Incrementable<T> void incrementAll(T*, int, T) [with T = int]’: another_tmp.cpp:17:14: required from here another_tmp.cpp:4:9: required for the satisfaction of ‘Incrementable<T>’ [with T = int] another_tmp.cpp:4:25: in requirements with ‘T a’, ‘T b’ [with T = int] another_tmp.cpp:5:12: note: ‘a += b’ does not satisfy return-type-requirement, because 5 | {a += b} -> std::convertible_to<void>; | ~~^~~~ another_tmp.cpp:5:10: error: deduced expression type does not satisfy placeholder constraints 5 | {a += b} -> std::convertible_to<void>; | ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ another_tmp.cpp:5:10: note: constraints not satisfied In file included from another_tmp.cpp:1: /usr/include/c++/11.2.0/concepts:72:13: required for the satisfaction of ‘convertible_to<decltype(auto) [requires std::convertible_to<<placeholder>, void>], void>’ [with decltype(auto) [requires std::convertible_to<<placeholder>, void>] = int&] /usr/include/c++/11.2.0/concepts:72:30: note: the expression ‘is_convertible_v<_From, _To> [with _From = int&; _To = void]’ evaluated to ‘false’ 72 | concept convertible_to = is_convertible_v<_From, _To> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~ So, what is the correct concept to define here?
If you don't care what its return type is, then you can simply use the requires-clause to require the expression a += b to be well-formed: template<class T> concept Incrementable = requires(T a, T b) { a += b; }; However, such a concept seems too loose for the incrementable type, and it seems more appropriate to require the return type to be T& like {a += b} -> same_as<T&> and name it AdditionAssignable or something.
71,361,574
71,361,617
Creating a suitable begin() and end() function for a class
I have the following class: template<typename DataType> class Bag { DataType* arr; int len, real_size; public: // Class methods }; I have implemented different methods such as add, remove, etc. for Bag. I have also overloaded the operator[]. While testing this out, I wanted to print all the elements of an object of type Bag. So I tried this: #include <iostream> #include "bag.h" int main() { sgl::Bag<int> bag{}; bag.add(12); bag.add(14); bag.add(16, 0); for (auto& i : bag) // this range-based 'for' statement requires a suitable "begin" function and none was found { } } As I got this error, I tried implementing begin() and end() as such: DataType begin() { return arr[0]; } DataType end() { return arr[len - 1]; } But then I got the following error: the iterator type in this range-based 'for' statement is "int", which is not a pointer type or an iterator-like class type So my question is that how do I properly implement a suitable begin() and end() function for my class Bag?
begin and end need to return iterators/pointers to the first and the last+1 element, whereas you return the first and last element. DataType *begin() const { return arr; } DataType *end() const { return arr+len; } should work, assuming that len is the number of elements in your array. Note: end needs to point beyond the last element of your array, not at the last element. See cppreference.
71,361,839
71,362,109
Constness and comparison concepts in generic code
Taking a look at cppreference template<class T, class U, class Cat = std::partial_ordering> concept three_way_comparable_with = std::three_way_comparable<T, Cat> && std::three_way_comparable<U, Cat> && std::common_reference_with< const std::remove_reference_t<T>&, const std::remove_reference_t<U>&> && std::three_way_comparable< std::common_reference_t< const std::remove_reference_t<T>&, const std::remove_reference_t<U>&>, Cat> && __WeaklyEqualityComparableWith<T, U> && __PartiallyOrderedWith<T, U> && requires(const std::remove_reference_t<T>& t, const std::remove_reference_t<U>& u) { { t <=> u } -> __ComparesAs<Cat>; { u <=> t } -> __ComparesAs<Cat>; }; In all comparison concepts, the operands (t and u here) are always const-qualified references. This means that if I have an "unorthodox" class struct S { int i; auto operator<=>(const S&) const = default; void* operator<=>(S&) = delete; }; then S models std::three_way_comparable but the following fails S a, b; a <=> b; Does this mean that I must enforce constness for comparisons in any generic code? template<typename T, typename U> requires std::three_way_comparable_with<T, U> auto foo(T&& t, U&& u) { // if(t <=> u > 0) // wrong! if(static_cast<const std::remove_reference_t<T>&>(t) <=> static_cast<const std::remove_reference_t<U>&>(u) > 0) return bar(std::forward<T>(t)); else return baz(std::forward<U>(u)); }
As hinted by @StoryTeller in the comments: According to the "implicit expression variations" in [concepts.equality]/6, because the expression t <=> u is non-modifying (the operands are const lvalue references), variations of the expression expecting non-const lvalue references instead of const lvalue references are implicitly also required. However, it is unspecified whether these requirements are validated. I don't see any exceptions to this rule for std::three_way_comparable_with in [cmp.concept]. Your type S violates this additional requirement because the variation requires(std::remove_reference_t<T>& t, std::remove_reference_t<U>& u) { { t <=> u } -> __ComparesAs<Cat>; { u <=> t } -> __ComparesAs<Cat>; }; is not satisfied. It therefore doesn't model std::three_way_comparable_with. There is even a very similar example under the referenced clause.
71,361,923
71,361,974
how to implement unique func on a string in c++
Excuse me does anyone here know how can we remove duplicates from a string using unique func or any other func? for example if i want to turn "fdfdfddf" into "df" I wrote the code below but it seems it doesn't work #include <bits/stdc++.h> using namespace std; int main() { vector<int>t; int n; cin>>n; string dd; vector<string>s; for(int i=0;i<n;i++) { cin>>dd; s.push_back(dd); sort(s[i].begin(),s[i].end()); unique(s[i].begin(),s[i].end()); cout<<s[i]<<"\n"; } }
According to the documentation, unique: Eliminates all except the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range. If you want to get rid of the excessive elements, you have to do that explicitly, e.g., by calling erase (as in the example in the documentation): auto last = std::unique(s[i].begin(), s[i].end()); s[i].erase(last, s[i].end());
71,362,123
71,363,681
Visual Studio's gtest unit calculates incorrect code coverage
I try to use gtest in visual studio enterprise 2022 and generate code coverage. // pch.h #pragma once #include <gtest/gtest.h> // pch.cpp #include "pch.h" // test.cpp #include "pch.h" int add(int a, int b) { return a + b; } TEST(a, add) { EXPECT_EQ(2, add(1, 1)); } This image is my test coverage report: Such a minimalist code. I think its code test coverage should be 100%. But in reality it's only 26.53%. I think it might be because a lot of stuff in the header file "gtest/gtest.h" is not executed. Please tell me how to write a hello world project with 100% coverage.
You should write tests in dedicated files and exclude test sources from analysis by test coverage tools. Unit tests are not subjects of any test coverage tools by their nature. // First file, a subject for a tool int add(int a, int b) { return a + b; } // Second file, excluded from analysis by a tool TEST(a, add) { EXPECT_EQ(2, add(1, 1)); } TEST produces a lot of code that include several conditional branches, exception handlers and other stuff. EXPECT_EQ produces at least two branches if (2 == add(1, 1) ... else .... Of course add(1, 1) gives a single result and is unable to cover all branches in the unit test.
71,362,259
71,365,752
Building boost::log::formatter on runtime condition
I want to build boost::log::formatter conditionally, however, formatter objects do not seem to behave as 'normal values'. For example: auto sink = boost::log::add_console_log(std::clog); auto format = expr::stream << expr::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S.%f"); boost::log::formatter formatter = format; if (condition) { auto t = "msg=" << expr::smessage; formatter <<= t; } sink->set_formatter(formatter); However, operator<<= (or even operator= for that matter) doesn't seem to modify formatter object which is very surprising for me! What is the proper way of doing this?
Formatting streaming expression constructs a function object that will be executed when a log record is formatted into string. The function object type is final in the sense that you cannot modify it by adding new formatting statements to it. In fact, any streaming statement effectively creates a new formatter function object of a distinct type. boost::log::formatter is just a type erasure helper that encapsulates the formatter function object, similar to how std::function encapsulates a lambda function that you assign to it. If you want to modify the formatter, you must create a new formatter that will have the original formatter as its left part and the added streaming statements on the right. This new formatter can then be assigned to boost::log::formatter. auto sink = boost::log::add_console_log(std::clog); boost::log::formatter formatter; auto common_format = expr::stream << expr::format_date_time(timestamp, "%Y-%m-%d %H:%M:%S.%f"); if (condition) { auto format = common_format << "msg=" << expr::smessage; formatter = format; } else { formatter = common_format; } sink->set_formatter(formatter); Note that this will only work with streaming expressions. This will not work with Boost.Format-style formatters based on boost::log::expressions::format. Also note that condition will be evaluated once - when the formatter is constructed, not when it is executed to format log records. If you want to test a condition when the formatter is executed then you should look into conditional formatters.
71,362,412
71,363,503
QT creator get the time from another time zone (not local time zone)
I was trying to find how to get a current time, however, I am looking to get a time from another time zone. I tried to play with it, even trying to simply add hours to the current time, to make up to what I am trying to get, but it did not work well MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()),this, SLOT(showTime())); timer->start(); QDate date = QDate::currentDate(); QString dateTimeText = date.toString(); ui->date->setText(dateTimeText); } void MainWindow::showTime() { QTime time = QTime::currentTime(); QString time_text = time .toString("hh : mm : ss"); if((time.second() % 2) == 0) { time_text[3] = ' '; time_text[8] = ' '; } ui->Digital_clock->setText(time_text); }
To get QTime for different time zone, you could just create new QTime object based on currentTime() with specific offset. To do that you can just call addSecs(int) function like below: QTime currentTimeZoneTime = QTime::currentTime(); // Your time zone current time QTime differentTimeZoneTime = localTime.addSecs(3600); // Add +1 hour to your time zone current time
71,362,575
71,364,195
Can't use QFont type property values when extending QML properties?
here is my code mytext.cpp #ifndef MYTEXT_H #define MYTEXT_H #include <QObject> #include <QtQml/qqml.h> #include <QFont> class MyText:public QObject { Q_OBJECT Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QString fontFamily READ fontFamily WRITE setFontFamily) Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize) QML_ELEMENT public: MyText(QObject* object = nullptr); QString fontFamily()const{return family;} void setFontFamily(const QString& fy){family = fy;} int fontSize()const{return ftSz;} void setFontSize(int sz){ftSz = sz;} QFont font()const{return ft;} void setFont(const QFont& f){ft = f;} private: QFont ft; QString family = "default family"; int ftSz = 12; }; main.qml import QtQuick 2.15 import MyText 1.0 MyText{ fontFamily:"asdasdad" fontSize:20 //how to set the value of 'font' property ?? } main.cpp #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlComponent> #include "mytext.h" int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QQmlEngine engine; QQmlComponent component(&engine, QUrl("qrc:/main.qml")); auto *pMytext = qobject_cast<MyText *>(component.create()); if (pMytext) { qWarning() <<"mytext family is = "<< pMytext->fontFamily() <<"fontSize = "<<pMytext->fontSize() <<"font is = "<<pMytext->font(); return EXIT_SUCCESS; } qWarning() << component.errors(); return EXIT_FAILURE; } when i runing ,i get output: mytext family is = "asdasdad" fontSize = 20 font is = QFont(,-1,-1,5,50,0,0,0,0,0) so,my question is how could i set the value for the property of 'font'? if no way,how qquicktext work for the element of 'Text'? and one more question,if i change the type QFont to QFont*,is there any way to setting in qml file?
You can use the font method of Qt Qml type: font: Qt.font({family: "Arial", pixelSize: 20}) https://doc.qt.io/qt-5/qml-qtqml-qt.html#font-method Or setting the font's properties individually: font.family: "Arial" font.pixelSize: 30 Note, that the two methods cannot be mixed, so if you set the font property you cannot override font.pixelSize for eg. Edited: fixed typo in the font method example
71,363,061
71,363,248
How to check if datetime object in CPP is null or not
I am using std::chrono::system_clock::time_point; this in my abstract class (header file) . my code is as below using datetime = std::chrono::system_clock::time_point; class datetime _endDate; Now in my cpp file, I want to check if it has a value different than epoch .How can I do that?
I did as it said in comment secion. I used _endDate != datetime{}
71,363,164
71,498,322
OpenVR: Implementation of virtual API functions (GetProjectionMatrix)
I couldn't find the implementation (aka. source) of the pure virtual functions from the openvr header. I am mainly interested in the GetProjectionMatrix() function. Where I searched (with no results): Simple goole search Searched the repo for the function name In the extracted symbols, import and export tables of most of the included libraries (.dll and .lib) What I found so far: https://github.com/ValveSoftware/openvr/issues/103 , but this seems to deal with problems generated by different compilers. The error of this issue is generated in vrclient.dll provided by SteamVR. There seems to be no public source for both of them. Any idea, how (/where) these virtual functions are implemented?
You won't like the answer, because the sad reality is that it has no open sources available to us. OpenVR is a purely virtual interface library, yes interfaces are open source, but the actual implementations of those interface are not. In case of libopenvr_api (it looks like) those are appended as a binary blob to the interface build. The way that works is through factory functions that are declared in the interface library, but defined somewhere else, those externally defined parts are like a black box to us, and unless Valve suddenly change their minds it'll remain that way. Those factory functions are declared and used in the OPENVR_INTERFACE_INTERNAL sections of openvr.h and openvr_driver.h (also in case of openvr.h those factory functions are defined in openvr_capi.h, but they use factory functions that are defined in a shared library which is just loaded at runtime and the entire pattern is very similar to the one in openvr.h). EDIT: (also in case of openvr.h those factory functions are defined in openvr_capi.h, but they use factory functions that are defined in a shared library which is just loaded at runtime and the entire pattern is very similar to the one in openvr.h) My memory is clearly failing me, the internal factory functions are defined in openvr_api_public.cpp which is one of the source files libopenvr_api is build from, not in openvr_capi.h (in my defense i didn't look at libopenvr_api sources in a while).
71,363,309
71,364,719
FPC: file not recognized: file format not recognized
I have something that need to link some C++ codes to main Pascal program. I followed this tutorial, now I have: download.h #include <iostream> #include <curl/curl.h> using namespace std; // function goes here int downloadsrc(char* pkg_name){ // do stuff } download.pas: unit download; {$link download.obj} // fpc may overwrite download.o Interface uses ctypes; function downloadsrc(pkg_name:string):integer; Implementation // I leave this empty end. My main program: program myprog; uses warn, download, test; var i:integer; begin if ParamCount = 0 then help() else for i:= 1 to ParamCount do begin if ParamStr(i) = 'download' then downloadsrc(ParamStr(i+1)) else if ParamStr(i) = 'test' then test(); end; end. I tried g++ to compile .h file, change the output.. but when build the program FPC says that: download.obj: file not recognized: file format not recognized Compiling download.pas manually still works. Am I do something wrong here? Am I need to do some other things, like add a compile flag or modify the code?
FPC, like GCC, uses COFF objects. Make sure your .obj is COFF not OMF. If you fix that, you probably must also link some C++ runtime library, and declare downloadsrc in a C callable way, and alter the FPC declaration to match (cdecl)
71,363,361
71,363,947
Unqualified lookup of operators in standard library templates
namespace N { struct A {}; template<typename T> constexpr bool operator<(const T&, const T&) { return true; } } constexpr bool operator<(const N::A&, const N::A&) { return false; } #include<functional> int main() { static_assert(std::less<N::A>{}({}, {}), "assertion failed"); } See https://godbolt.org/z/vsd3qfch6. This program compiles on seemingly random versions of compilers. The assertion fails on all versions of MSVC since v19.15, but succeeds on v19.14. It succeeds on GCC 11.2 and before, but fails on current GCC trunk. It fails on Clang with libstdc++ in all versions. It succeeds with libc++ in all versions, including current trunk, except version 13. It always succeeds with ICC. Is it specified whether or not the static_assert should succeed? The underlying issue here is that std::less uses < internally, which because it is used in a template will find operator< overloads via argument-dependent lookup from the point of instantiation (which is the proper method), but also via unqualified name lookup from the point of definition of the template. If the global overload is found, it is a better match. Unfortunately this make the program behavior dependent on the placement and order of the standard library includes. I would have expected that the standard library disables unqualified name lookup outside the std namespace, since it cannot be relied on anyway, but is that supposed to be guaranteed?
What matters here is whether the unqualified lookup from inside std finds any other operator< (regardless of its signature!) before reaching the global namespace. That depends on what headers have been included (any standard library header may include any other), and it also depends on the language version since C++20 replaced many such operators with operator<=>. Also, occasionally such things are respecified as hidden friends that are not found by unqualified lookup. It’s obviously unwise to rely on it in any case.
71,363,478
71,363,543
CDT C++ library: How to define an edge?
I'm trying for a while to define an edge in CDT. Below is my code. The first function works fine, but the compilation of the second function throws this error: no matching function for call to CDT::Edge::Edge(). I also attempted numerous other trials, with no luck. typedef CDT::V2d<double> Vertex; typedef CDT::Edge Edge; typedef CDT::Triangulation<double> Triangulation; arma::umat Rcpp_delaunay(const arma::mat & points){ Triangulation cdt(CDT::VertexInsertionOrder::AsProvided); size_t npoints = points.n_rows; std::vector<Vertex> vertices(npoints); for (size_t i = 0; i < npoints; ++i) { const arma::rowvec row_i = points.row(i); vertices[i] = Vertex::make(row_i(0), row_i(1)); } cdt.insertVertices(vertices); cdt.eraseSuperTriangle(); const CDT::TriangleVec triangles = cdt.triangles; arma::umat out(triangles.size(), 3); for(size_t i = 0; i < triangles.size(); ++i){ const CDT::VerticesArr3 trgl = triangles[i].vertices; out(i, 0) = trgl[0]; out(i, 1) = trgl[1]; out(i, 2) = trgl[2]; } return out; } arma::umat Rcpp_constrained_delaunay( const arma::mat & points, const arma::umat & edges ){ Triangulation cdt(CDT::VertexInsertionOrder::AsProvided); size_t npoints = points.n_rows; std::vector<Vertex> vertices(npoints); for (size_t i = 0; i < npoints; ++i) { const arma::rowvec row_i = points.row(i); vertices[i] = Vertex::make(row_i(0), row_i(1)); } size_t nedges = edges.n_rows; std::vector<Edge> Edges(nedges); for (size_t i = 0; i < nedges; ++i) { const arma::urowvec row_i = edges.row(i); Edge edge = Edge(row_i(0), row_i(1)); Edges[i] = edge; } cdt.insertVertices(vertices); cdt.insertEdges(Edges); cdt.eraseOuterTrianglesAndHoles(); const CDT::TriangleVec triangles = cdt.triangles; arma::umat out(triangles.size(), 3); for(size_t i = 0; i < triangles.size(); ++i){ const CDT::VerticesArr3 trgl = triangles[i].vertices; out(i, 0) = trgl[0]; out(i, 1) = trgl[1]; out(i, 2) = trgl[2]; } return out; }
Edge does not have a default constructor, so you can’t give a vector<Edge> an initial size (since that would require each element to be initially default-constructed). Instead, make the vector empty to begin with (you can reserve() capacity for it if you like) and then add edge with push_back()… or, better yet, construct it in-place with emplace_back().
71,364,060
71,386,916
Design pattern for isolating parsing code?
I have C++ class Foo: class Foo { public: [constructor, methods] private: [methods, data members] }; I want to add to class Foo the possibility for it to be constructed by reading data from a text file. The code for reading such data is complicated enough that it requires, in addition to a new constructor, several new private methods and data members: class Foo { public: [constructor, methods] Foo(const std::string& filePath); // new constructor - constructs a Foo from a text file private: [methods, data members] [several methods used for text file parsing] // new methods [several data members used for text file parsing] // new data members }; This works, but I feel it would be better to isolate the new parsing code and data members into their own entity. What would be an adequate design pattern in order to achieve this goal?
I think this would be a good opportunity to use the so-called Method Object pattern. You can read about that pattern on various web sites. The best description I have found, though, is in Chapter 8 of Kent Beck's book Implementation Patterns. Your use case is unusual in the sense that this pattern would apply to a constructor instead of a regular method, but this is of secondary importance.
71,364,236
71,364,315
Run C++ on MacOS without xcode
I don't have Xcode installed on my Mac OS 13.6 but I would like to run c++ on vs code. Is there a way to do that without the need for Xcode to be installed? Also, can I run an older version of Xcode and run c++ without problems? Note: Would be great if someone posted a link for a tutorial.
You may download and install LLVM 13.0.1 for Darwin or a small part of Xcode, Xcode command line tools: xcode-select --install. Both will result in installing clang++.
71,364,272
71,364,387
C++ FlatBuffers - Assertion failed: (finished), function Finished
Here is my schema: namespace Vibranium; enum GameObject_Type:uint { STATIC = 0 } table GameObjectDatabase { gameobjects:[GameObjectsTemplate]; } table GameObjectsTemplate { id:int; name:string; prefab:string; type:GameObject_Type; position_x:float; position_y:float; position_z:float; rotation_x:float; rotation_y:float; rotation_z:float; map_id:int; event_id:int; } root_type GameObjectDatabase; Here is my code: flatbuffers::FlatBufferBuilder fbb; std::vector<flatbuffers::Offset<Vibranium::GameObjectsTemplate>> gameobjects_template; Field* fields = result->Fetch(); auto id = fields[0].GetInt32(); auto name = fbb.CreateString(fields[1].GetString()); auto prefab = fbb.CreateString(fields[2].GetString()); auto type = static_cast<Vibranium::GameObject_Type>(fields[3].GetInt32()); auto position_x = fields[5].GetFloat(); auto position_y = fields[6].GetFloat(); auto position_z = fields[7].GetFloat(); auto rotation_x = fields[8].GetFloat(); auto rotation_y = fields[9].GetFloat(); auto rotation_z = fields[10].GetFloat(); auto map_id = fields[11].GetInt32(); auto event_id = fields[12].GetInt32(); auto go1 = Vibranium::CreateGameObjectsTemplate(fbb, id, name, prefab, type,position_x,position_y,position_z, rotation_x,rotation_y,rotation_z,map_id,event_id); gameobjects_template.push_back(go1); this->_container.push_back(go1); auto go_db = fbb.CreateVector(gameobjects_template); Vibranium::GameObjectDatabaseBuilder go_builder(fbb); go_builder.add_gameobjects(go_db); go_builder.Finish(); auto gt = Vibranium::GetGameObjectDatabase(fbb.GetBufferPointer()); I get this error: Assertion failed: (finished), function Finished, file /opt/homebrew/include/flatbuffers/flatbuffers.h, line 1226. It is caused by this line: auto gt = Vibranium::GetGameObjectDatabase(fbb.GetBufferPointer()); Why is that and how can I fix it?
If you get an assert, it is always good to check the assert code, it may give you a hint as to why: void Finished() const { // If you get this assert, you're attempting to get access a buffer // which hasn't been finished yet. Be sure to call // FlatBufferBuilder::Finish with your root table. // If you really need to access an unfinished buffer, call // GetCurrentBufferPointer instead. FLATBUFFERS_ASSERT(finished); }
71,364,817
71,364,849
Library that includes undefined behavior function working on a certain compiler is portable?
If I compiled a library that includes an undefined behavior function guaranteed to work on a certain compiler, is it portable to other compilers? I thought that the library has already generated assembly, so, when other programs call UB function, the function assembly well-defined to a certain compiler would be executed. What am I getting wrong here?
Do not look to the C++ standard for all your answers. The C++ standard does not define the behavior when object modules compiled by different compilers are linked together. The jurisdiction of the C++ standard is solely single C++ implementations whose creators choose to conform to the C++ standard. Linking together different object modules is covered by an application binary interface (ABI). If you compile two functions with two compilers that both conform to the same ABI and link them with a linker that conforms to the ABI, they generally should work together. There are additional details to consider, such as how various things in the language(s) bind to corresponding things in the ABI. For example, one compiler might map long to some 32-bit integer type in the ABI while the other compiler might map long to some 64-bit integer type, and this would of course interfere with the functions working together unless corresponding adjustments were made.
71,364,829
71,365,568
Generating an NxN magic square using a dynamically allocated 2D array in C++ with user-input dimension
I'm trying to generate and solve an NxN odd-numbered magic square through dynamic memory allocation but whenever I run the code, it displays nothing on the terminal and the programme ends. I reckon it has something to do with the dynamic allocation of the 2D array, as when I make a normal NxN array with a constant size, the programme runs fine. I'd appreciate any help regarding this! #include<bits/stdc++.h> #include<cmath> using namespace std; void calcuateMagicSquare(int N) { int **Array; Array=new int*[N]; for(int i=0; i<N; i++) { Array[i]=new int[N]; } memset(Array, 0, sizeof(Array)); int nSquare=N*N; int i=N/2; int j=N-1; for(int k=1; k<=nSquare;) { if(i==-1 && j==N) { j=N-2; i=0; } else { if(j==N) { j=0; } if(i<0) { i=N-1; } } if(Array[i][j]) { j=j-2; i++; continue; } else { Array[i][j]=k++; } j++; i--; } int SolutionMagicSquare=N*(N*N+1)/2; cout << "Solution of the magic Square: " << SolutionMagicSquare << endl; cout << "MAGIC SQUARE: \n" << endl; for(int i=0; i<N; i++) { for(int j=0; j<N; j++) { cout << setw(4) << Array[i][j] << " "; cout << endl; } } } int main() { int N; cout << "Please enter the dimension of the magic square:" << endl; cin >> N; calcuateMagicSquare(N); }
This isn't too bad. int ** Array=new int*[N]; for(int i=0; i<N; i++) { Array[i]=new int[N]; } memset(Array, 0, sizeof(Array)); The memset is causing your trouble, and it's wrong for two reasons. First, let's say you really wanted to do that. You don't, but let's say you did. How big is sizeof(Array). Array is an int **. On a 64-bit machine, that's 8 bytes. So conveniently, you only destroyed the first pointer. What you really need to do is this: int ** Array=new int*[N]; // Don't do this memset, but showing you what it should look like) memset(Array, 0, sizeof(int *) * N); for(int i=0; i<N; i++) { Array[i]=new int[N]; // But this one is safe memset(Array[i], 0, sizeof(int) * N); } Your version was erasing the first pointer -- Array[0]. I put that first memset in there so you could see what it would look like if you needed it. It's the second one you need. You're clearing out the size of an int times the number of ints that you have.
71,365,310
71,365,388
Defining a struct method with function parameter in C++
Looking at C++ interface code. I do not have access to the implementation. I made a small example to show the behavior. struct MessageInfo{ MessageInfo() : length{}, from{}, to{} {} MessageInfo(int _length, string _from, string _to) : length{_length}, from{_from}, to{_to} {} int length; string from; string to; using IsEnumerableTag = void; template<typename F> void enumerate(F& fun) { fun(this->length); fun(this->from); fun(this->to); } }; Can somebody explain to me what is the usage of enumerate struct function member in this struct definition? Based on my understanding the enumerate in this struct can take a function type as input parameter (function pointer?) Does it mean that whenever we create an object of MessageInfo struct we can call this method like below? How can define the function type, In other words what should i use instead of "???" in following code? What is the advantage of this model of coding (more specifically about enumerate method)? MessageInfo messageInfo (1000, "A", "B"); messageInfo.enumerate<???>(printFrom(messageInfo.From); void printFrom(string f) { cout<<"the msgInfo is sent from "<< f<<endl; }
It expects you to pass a generic callable, e.g. a lambda. You don't have to specify the template argument. It can be deduced from the function argument. For example: MessageInfo messageInfo (1000, "A", "B"); auto printFields = [](auto&& f){ std::cout << "Value of this field is " << f << ".\n"; }; messageInfo.enumerate(printFields); which should print Value of this field is 1000. Value of this field is A. Value of this field is B. As you can see from this, enumerate can be used to apply the same operation to every member without having to repeat yourself for each one. The signature is a bit unusual. You would normally expect F or F&& instead of F&. With either F or F&& you could put the lambda expression directly into the call instead of having to store it in a variable first.
71,365,319
71,365,385
Unique combinations of dice
I'm trying to model Yahtzee (a dice game). As a first step, I'm trying to enumerate all possible combinations of 5 dice being rolled simultaneously. I only want unique combinations (e.g. 5,5,5,4,4 is the same as 5,5,4,5,4 and so on). Is there an easy way to do this in Python, C++, or Mathematica?
You can use itertools.combinations_with_replacement() in Python: from itertools import combinations_with_replacement options = list(range(1, 7)) print(list(combinations_with_replacement(options, 5)))
71,365,756
71,365,939
When reusing a variable assigned to a class, why is only the last destructor call causing a crash?
I have case where I have a class that allocates memory in the constructor, and frees it in the destructor -- pretty basic stuff. The problem happens if I reuse the class instance variable for a new instance of the class. When the final (and only the final) instance gets destroyed when it goes out of scope, it will crash with a SIGABRT on the call to free/delete: malloc: *** error for object 0xXXXXX: pointer being freed was not allocated I feel like I'm missing something fundamental and I'd like to understand my mistake so I can avoid it in the future. Here's a simple repro: class AllocTest { public: AllocTest(const char *c) { this->data = new char[strlen(c) + 1]; strcpy(this->data, c); } ~AllocTest() { if (this->data != NULL) { delete[] data; } } private: char* data; }; int main(int argc, const char *argv[]) { const char* c = "test test test"; AllocTest t(c); t = AllocTest(c); t = AllocTest(c); return 0; } I can see in the debugger that the destructor being called each time t gets reassigned against the previous instance, why does only the final destructor cause a crash? It doesn't matter if I use new/delete or malloc/free -- it's the same behavior either way -- and only on the final deallocation. It also doesn't matter if I move the scopes around or anything -- as soon as the final scope leaves, the crash happens. This does not reproduce if confining the variable 't' to its own scope and not trying to reuse it -- for instance, everything's fine if I do this: for (int i = 0; i < 100; i++) { AllocTest t(c); } Working around the issue is simple enough but I'd much rather understand why I'm having this problem to start with. SOLUTION: Thanks to the answer from @user17732522, I now understand what the problem is here. I didn't realize that when I was reassigning t that it was actually making a copy of the class -- I was working on an assumption that like other languages that I typically work with that the assignment overwrites it. Upon realizing this things all made sense as I was unwittingly stumbling into a classic "double free" problem. The documentation on copy initialization and the pointers to the documentation about the rule of three pattern helped fill in the rest of the gaps here. Simply modifying my class to define the implicit copy semantic was enough to allow the code to work as expected: AllocTest& operator=(const AllocTest& t) { if (this == &t) { return *this; } size_t newDataLen = strlen(t.data) + 1; char* newData = new char[newDataLen]; strcpy(newData, t.data); delete this->data; this->data = newData; return *this; } Thanks, folks!
First of all the constructor itself has undefined behavior, because you allocate only enough space for the length of the string (strlen(c)) which misses the additional element required for the null-terminator. Assuming in the following that you fix that. The destructor on an object/instance is only ever called once. In your code t is always the same instance. It is never replaced with a new one. You are only assigning to it, which uses the implicit copy assignment operator to copy-assign the members from the temporary object to t's members one-by-one. The destructor on t is called only once, when its scope ends after the return statement. This destructor call has undefined behavior because the destructor of the last AllocTest(c) temporary object has already deleted the allocated array to which t.data points at this point (it had been assigned that value with t = AllocTest(c);). Additionally, the first allocation in AllocTest t(c); has been leaked, since you overwrote the t.data pointer with the first t = AllocTest(c);. With just AllocTest t(c); you are not copying any pointer and so this can't happen. The underlying issue here is that your class violates the rule of 0/3/5: If you have a destructor you should also define copy/move constructor and assignment operators with the correct semantics. The implicit ones (which you are using here) are likely to do the wrong thing if you need a custom destructor. Or even better, make the rule-of-zero work by not manually allocating memory. Use std::string instead and you don't have to define either the destructor or any special member function. This also automatically solves the length mismatch issue.
71,365,895
71,365,930
Acces private static member variable in namespace from another class C++
I have a problem. In the following example, there is a static private member variable called private_b of class A inside namespace a. And then I'm trying to access that variable from class B, which I have declared to be a friend of class A, but it doesn't work, with a compile error from GCC: error: ‘B* a::A::private_b’ is private within this context class B; namespace a { class A { private: static B* private_b; friend class B; }; B* A::private_b = nullptr; } class B { public: void foo() { B* foo = a::A::private_b; // Error here } }; I don't understand why I can't access it, and how to get around this problem. I really want class A to be inside that namespace, and class B doesn't make sense to be inside that namespace. I searched for this on the internet, but couldn't find this exact case, or couldn't find a solution for this case.
friend class B; declared friendship with B in the same namespace a. You may want friend class ::B;. Note, friend class B; does not refer to the global forward declaration class B, it has own forward declaration class B after the keyword friend.
71,366,866
71,366,972
Do inlined pass-by-reference functions still create reference variables?
I am writing a loop that has some state variables. int MyFunc(){ int state_variable_1 = 0; int state_variable_2 = 12; while(state_variable_1 != state_variable_2){ BodyOfWhileLoop(state_variable_1, state_variable_2); } } As you can see, I have written the body of the while loop in a separate function, BodyOfWhileLoop. This is to keep the code clean and to aid in debugging. BodyOfWhileLoop will need to modify state_variable_1 and state_variable_2. I could pass these by reference, for example, void BodyOfWhileLoop(int& state_variable_1, int& state_variable_2); This is functionally exactly what I want, however, each use of the state variables in the body of the function requires a dereference (I believe). I could do something like this: void BodyOfWhileLoop(int& state_variable_1_ref, int& state_variable_2_ref){ int state_variable_1_copy = state_variable_1_ref; int state_variable_2_copy = state_variable_2_ref; // Do stuff with state variables state_variable_1_ref = state_variable_1_copy; state_variable_2_ref = state_variable_2_copy; } I see two things to be true: Copying the state variables costs memory since you allocate space for the copy. Not copying the state variables will cost time because there is an extra dereference in the body of BodyOfWhileLoop each time you access the state variable. So I have two questions: If the compiler inlined BodyOfWhileLoop, would it still create a state_variable_1_ref and state_variable_2_ref (requiring a dereference to access the ints)? Would the cost of accessing state_variable_1 be the same as accessing it within MyFunc? Are there alternative solutions I have not seen?
No, they do not. Demonstration: https://godbolt.org/z/qc1ne7ezM. References are typically implemented as pointers under the hood (though they do not have to be). Once the function is inlined the compiler will eliminate the indirection. In LLVM, this optimization is performed as part of SROA. Any function with only one callsite should be inlined by the optimizer but note that if a function has external linkage the compiler may not inline it: It could be used in other translation units so the compiler doesn't know it's only used once. To avoid this, mark it static or inline, or use link-time optimization.
71,366,901
71,376,243
Is searching a string using a switch inside a for loop inefficient?
Recently did an online programming assessment, where the question was essentially "search a number for specified integers and increment a count". My solution was to convert the given number to a string, and then search through the string using a for loop and a switch statement. So basically: for (int i = 0; i < str.length(); i++;) { switch(str[i]) { case '1': count++; break; case '4': count++; break; case '8': count++; break; // etc } } What I'm wondering is, is this an inefficient way of accomplishing this? I believe the time complexity is O(n), but I could be wrong. If it is inefficient, what is a better solution? **Edited for clarification, added cases '4' and '8'
switch is generally not inefficient; internally it is typically implemented either as a jump-table to the various options, or as a binary search, or as a series of if-then statements, depending on what the compiler/optimizer thinks will execute fastest. However, you could gain some efficiency in this case by avoiding the switch/case block altogether and using a lookup-table instead, like this: #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int, char **) { const int BUFSIZE=1024*1024*10; // 10MB char * str = new char[BUFSIZE]; for (int i=0; i<BUFSIZE; i++) str[i] = (rand()%127)+1; str[BUFSIZE-1] = '\0'; unsigned char mask[256]; memset(mask, 0, sizeof(mask)); mask['1'] = 1; mask['4'] = 1; mask['8'] = 1; for (int i=0; i<BUFSIZE; i++) count += mask[(unsigned)str[i]]; printf("count=%i\n", count); return 0; } On my computer, doing it this way executed a little more than twice as quickly than the original (switch-based) approach did.
71,367,332
71,367,352
Can't sum a vector of integers using for loop c++
I am writing a function that takes a vector of integers as input, and iterates through the vector to obtain the maximum and minimum values in the vector, as well as the sum. The maximum possible integer in the argument vector is 1000000000. void miniMaxSum(vector<long> arr) { long sum = 0; long min = 1000000000; long max = 0; for (int i = 0; i < arr.size(); i++) { cout << arr[i] << endl; sum += arr[i]; if (arr[i] < min) { min = arr[i]; } if (arr[i] > max) { max = arr[i]; } } cout << sum << endl; } Using the following input vector as argument: vector<long> x = {793810624,895642170,685903712,623789054,468592370 }; The sum is a negative number: -827229366
long is usually a 32-bit type on most operating systems (at least 32-bit). So the maximum value it can hold is 2,147,483,647. The sum of your numbers is 3,467,737,930. So it overflows. Consider using unsigned long or long long (at least 64 bits) or unsigned long long for larger numbers. Or you could even use intmax_t or uintmax_t to get the biggest integer that is supported.
71,367,385
71,368,919
Stack allocating intermediate objects in contructors
When a constructor allocates intermediate objects that need to be passed to other constructors with longer lifetimes, can the intermediate objects be stack-allocated? For example, I have a class Reader that has various utilities build atop an std::wistream that has several constructors for various use cases: Reader(std::unique_ptr<std::istream> bytestream) Reader(char buffer[], size_t count) Reader(const std::string str&) The only relevant member data that Reader has is: std::unique_ptr<std::wistream> m_character_stream Note: wistream, not istream. The constructors construct the wistream in various ways depending on their argument types. For example, the first constructor form, looks like this: Reader::Reader(std::unique_ptr<std::istream> bytestream) { auto conversion = std::wbuffer_convert<std::codecvt_utf8<wchar_t>, wchar_t, std::char_traits<wchar_t>>(bytestream->rdbuf()); m_character_stream = std::make_unique<std::wistream>(&conversion); } My questions are: I guess since I'm being passed a unique_ptr, that I have no choice but to std::move it to some otherwise useless member variable to keep it alive until we're destructed? Even though the rest of my class will never use that variable directly, but only indirectly through m_character_stream? The conversion object is stack-allocated. Is that going to be a problem? I assume that when the constructor returns, that this object will be deleted. Will that cause std::wistream to malfunction? Does that mean I have to store conversion as otherwise useless member data to keep it alive as well? If so, is there a common pattern or naming convention for useless member data that exist only to keep things alive? Since I have multiple constructors, I'd rather not have a bunch of constructor-specific member data attached to my class since that data won't be initialized most of the time. This just all smells wrong, but this is my first C++ project, so move semantics, ownership semantics, smart pointers, RAII, and all that crazy stuff is all pretty new to me and I'm trying to wrap my brain around it all. I come from a Java/Python/Go background.
Yes, you have to keep bytestream alive and the typical way is storing it in a unique_ptr member variable. Yes it is a problem that m_character_stream is going to use the pointer you pass beyond the lifetime of conversion. So yes, make conversion a member variable. C++ does not have garbage collection. Lifetime management is absolutely essential when programming in C++. Read about RAII.
71,367,464
71,367,565
Why isn't my char* shrinking after popping a char
For context, I'm rewriting the string class in C++ to use on microcontrollers, specifically Arduino, so that it doesn't use the standard library functions not supported by Arduino. I've looked at several answers here that show how to pop a char off a char*. However, within my function it doesn't seem to correctly edit the char*. My string class #include <stdlib.h> // malloc namespace micro_std { class string { private: const int MAX_SIZE = 4096; // Maximum size on 16bit controllers. char* data = nullptr; int _length = 0; public: string(char* data) { this->data = data; for (int i = 0; data[i] != '\0'; i++) _length++; } int size(void) const { return _length; } int length(void) const { return _length; } int max_size(void) const { return MAX_SIZE; } bool empty(void) const { return _length == 0; } char at(int index) const { return data[index]; } char back(void) const { return data[_length - 1]; } char front(void) const { return data[0]; } char* str(void) const { return data; } void clear(void) { _length = 0; data = nullptr; } // removed for brevity // char pop_back(void) { _length--; char character = data[_length]; data[_length] = '\0'; return character; } // removed for brevity // }; } And how I'm testing my code, specifically the pop_back function. #include <stdio.h> // printf #include "micro_std/string.h" int main(int argc, char** argv) { micro_std::string x = "abcdef"; // Testing pop_back function printf("%d %s\n", x.length(), x.str()); for (int i = 0; i < 5; i++) { char res = x.pop_back(); printf("%d %c %s\n", x.length(), res, x.str()); } //printf("%s\n", x.str()); return 0; } And, if needed, my compiler arguments g++ -w -std=c++2a -O3 program.cpp -o program Running this program gives me the following output: 6 abcdef 5 f abcdef 4 e abcdef 3 d abcdef 2 c abcdef 1 b abcdef Instead of the output I want: 6 abcdef 5 f abcde 4 e abcd 3 d abc 2 c ab 1 b a Where the output is formatted like "(length) (char popped) (result string)". Why isn't the data member data being altered when calling the pop_back function?
Why isn't the data member data being altered when calling the pop_back function? Even if the code compiles (which it shouldn't, since you are trying to construct x with a string literal, which is a const char[] array that cannot be assigned to a non-const char*), x would be pointing its data member at a string literal, thus data[_length] = '\0'; inside of pop_back() would invoke Undefined Behavior trying to alter read-only memory. To make your code work, you MUST make a copy of the input data, eg: #include <stdlib.h> // malloc namespace micro_std { class string { private: const int MAX_SIZE = 4096; // Maximum size on 16bit controllers. char _data[MAX_SIZE]; int _length = 0; public: string(const char* str) { for (int i = 0; str[i] != '\0'; ++i) { data[i] = str[i]; ++_length; } data[_length] = '\0'; } ... void clear(void) { _length = 0; } ... }; }
71,367,676
71,367,804
Using a pointer to a member function as a key in unordered_map
I have a unordered map std::unordered_map<void (MyClass::*)(), double> used to store the time that has elapsed since a function has been called. I'm getting an error saying that error: use of deleted function ‘std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map() [with _Key = void (MyClass::*)(); _Tp = double; _Hash = std::hash<void (MyClass::*)()>; _Pred = std::equal_to<void (MyClass::*)()>; _Alloc = std::allocator<std::pair<void (MyClass::* const)(), double> >]’ What is causing this, and how do I fix it? Is there a better way to do what I trying to do?
std::unordered_map stores its data using some calculations involving std::hash function. As described in the documentation for std::hash, under subsections "Standard specializations for basic types" and "Standard specializations for library types", there are only limited types that std::hash can perform on and void (MyClass::*)() is not one of them since its non-static and a non-static method pointer can not be used without an object. One possible solution is to use std::string as the key and when a function is called use the __func__ as the key inside the function. This is a working solution: #include <unordered_map> #include <iostream> #include <chrono> #include <thread> class MyClass { public: using FuncPtr = void (MyClass::*) (); using WrapperPtr = void (*) (MyClass&, void (MyClass::*) ()); void func1() { } void insert(std::pair<WrapperPtr, unsigned long long> pair) { m_functionMap.insert(pair); } void printTime() { std::hash<WrapperPtr> hashKey; std::hash<unsigned long long> hashValue; for (auto itr{ begin(m_functionMap) }; itr != end(m_functionMap); ++itr) { std::cout << hashKey(itr->first) << " " << itr->second << std::endl; } } private: std::unordered_multimap<WrapperPtr, unsigned long long> m_functionMap; }; void methodWrapper(MyClass& myClass, MyClass::FuncPtr funcPtr) { myClass.insert({ &methodWrapper, std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() }); (myClass.*funcPtr)(); // Actual call. } int main() { MyClass myObj; methodWrapper(myObj, &MyClass::func1); std::this_thread::sleep_for(std::chrono::milliseconds(100)); methodWrapper(myObj, &MyClass::func1); myObj.printTime(); } Why do we need to use methodWrapper? Why can't we just pass FuncPtr as key type to the m_functionMap? Because non-static method pointers can not be used without an object. That's the reason for this strange-looking line: (myClass.*funcPtr)(); and the static method solution which I belive makes more sense: #include <unordered_map> #include <iostream> #include <chrono> #include <thread> class MyClass { public: static void func1() { m_functionMap.insert({ &MyClass::func1, std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() }); } static void printTime() { std::hash<decltype(&MyClass::func1)> hashKey; std::hash<unsigned long long> hashValue; for (auto itr{ begin(m_functionMap) }; itr != end(m_functionMap); ++itr) { std::cout << hashKey(itr->first) << " " << itr->second << std::endl; } } private: static std::unordered_multimap<decltype(&MyClass::func1), unsigned long long> m_functionMap; }; std::unordered_multimap<decltype(&MyClass::func1), unsigned long long> MyClass::m_functionMap{}; int main() { MyClass::func1(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); MyClass::func1(); MyClass::printTime(); } In conclusion my suggestion is using __func__.
71,367,695
71,371,709
How to implement Big Int in Javascript?
I am working on open-source project. It doesn’t properly meet its specs due to the representation as JavaScript numbers ie let,const... I want to add support for Int, Long Int, and Big Ints similar to c++. Can anyone please suggest any resource or approach to achieve this? Thank you
JavaScript has gained BigInt support as a feature a couple of years ago. By now, most users have browsers new enough to support it: https://caniuse.com/bigint. If you want to support even older browsers, there are a variety of pure JavaScript implementations with different pros and cons, for example JSBI, MikeMcl's bignumber.js, Peter Olson's BigInteger.js, Yaffle's BigInteger. You can study their sources to learn how they're implemented. For learning about how native BigInt is implemented, this V8 blog post gives some insight. Side note: JavaScript is perfectly capable of expressing 32-bit integers à la C++ int/int32_t, no BigInts or libraries are required for that. Bitwise binary operations cause JavaScript numbers to behave like 32-bit integers, so you can write (a + b) | 0 to make the addition behave like a C++ int addition. If all you need is 64-bit integers, it's not difficult to represent them as pairs of 32-bit numbers. There are also several existing libraries that do that (just use your favorite search engine). If you don't actually need arbitrarily big integers, that may be a nice alternative.
71,368,541
71,368,677
Defining "hidden" constants in c++ header-only libraries
I'm creating a C++ header-only implementation of a library in which I defined multiple constants (defined as static constexprs) that I only want to use in the library, to make my code more clear and readable. I thought having internal linkage would be enough to "hide" these constants from any other source files in which I include this library. However, after including this header in another file where I am writing unit tests for it, I'm getting errors like redefinition of '<constant_name>' (the test source file has its own constants with the same name since they would be useful in some of the test cases, also defined as static constexprs). After some further reading, I now understand that internal linkage means the constants will not be available outside the translation unit, but the translation unit includes the source file as well as any headers it includes. This would explain why I'm getting that redefinition error, as constants with the same name exist in both the test source file and the library header file, and they end up being a single translation unit. Currently, I have wrapped said constants in a namespace to avoid the clashing. However, this is not ideal. For example, I still get autocomplete suggestions for these constants in other files when I prefix with the namespace. I would instead like them to be completely hidden. My question is regarding whether there is any way around this. Is there some way to make these constants truly visible only within the header itself, and invisible to any of the files which include it? EDIT: Here's some code to demonstrate what I mean. library.hpp static constexpr int USEFUL_CONSTANT = 5; namespace library { ...library implementation here... } tests.cpp #include "library.hpp" // Constant happens to be useful in tests too, but I don't // want to expose it for everybody, so I redefine it here static constexpr int USEFUL_CONSTANT = 5; ...tests here... I get the redefinition error since both constants would be part of the same translation unit.
A couple of viable approaches: inner namespace, (boost-style) namespace mylib { namespace detail { inline constexpr int const goodenough{42}; } int foo(void) { return detail::goodenough; } } conversion into private static fields of some class with access granted by friend declaration namespace mylib { int foo(void); class detail { friend int ::mylib::foo(void); static inline constexpr int const goodenough{42}; }; int foo(void) { return detail::goodenough; } } Note: constexpr implies inline and const.
71,368,645
71,368,722
difficulty in understanding c++ function that resolves function names by ordinals
I am following a malware analysis course. And I came across this code which I found confusing. The first two sections make sense but the part where the if statement starts is very difficult for me to understand. This "if" statement is supposed to resolve function names by ordinals. I have put my questions in the comments. FARPROC WINAPI myGetProcAddress(HMODULE hMod, char * sProcName) { char * pBaseAddress = (char *) hMod; // get pointers to main headers/structures IMAGE_DOS_HEADER * pDosHdr = (IMAGE_DOS_HEADER *) pBaseAddress; IMAGE_NT_HEADERS * pNTHdr = (IMAGE_NT_HEADERS *) (pBaseAddress + pDosHdr->e_lfanew); IMAGE_OPTIONAL_HEADER * pOptionalHdr = &pNTHdr->OptionalHeader; IMAGE_DATA_DIRECTORY * pDataDir = (IMAGE_DATA_DIRECTORY *) (&pOptionalHdr->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]); IMAGE_EXPORT_DIRECTORY * pExportDirAddr = (IMAGE_EXPORT_DIRECTORY *) (pBaseAddress + pDataDir->VirtualAddress); // resolve addresses to Export Address Table, table of function names and "table of ordinals" DWORD * pEAT = (DWORD *) (pBaseAddress + pExportDirAddr->AddressOfFunctions); DWORD * pFuncNameTbl = (DWORD *) (pBaseAddress + pExportDirAddr->AddressOfNames); WORD * pHintsTbl = (WORD *) (pBaseAddress + pExportDirAddr->AddressOfNameOrdinals); // function address we're looking for void *pProcAddr = NULL; // resolve function by ordinal if (((DWORD_PTR)sProcName >> 16) == 0) { // why shift by 16 WORD ordinal = (WORD) sProcName & 0xFFFF; // why & 0xFFFF DWORD Base = pExportDirAddr->Base; if (ordinal < Base || ordinal >= Base + pExportDirAddr->NumberOfFunctions) return NULL; // not sure what this part does pProcAddr = (FARPROC) (pBaseAddress + (DWORD_PTR) pEAT[ordinal - Base]); } ... ... ... } I would very much appreciate some explanation.
This allows you to split a number (here dword or double word) in two parts using bit operations, e.g: 0x12345678 >> 16 = 0x1234 (hi order word) 0x12345678 & 0xFFFF = 0x5678 (lo order word) Why is the code doing that? It's documented with GetProcAddress's lpProcName parameter: The function or variable name, or the function's ordinal value. If this parameter is an ordinal value, it must be in the low-order word; the high-order word must be zero.
71,368,658
71,368,789
How to move an element in std::list to the end using std:move and back inserter?
In my std::list, i have 10 elements, and i want to move the number 1000 to the back of the list. https://leetcode.com/playground/gucNuPit is there a better way, a 1 liner using std::move, back inserter or any other C++ syntax to achieve this with consciously? // Move the number 1000 to the end of the list #include <iostream> #include <algorithm> #include <list> using namespace std; int main() { list<int> myList({2,3,4,1000,5,6,7,8,9,10}); cout << "List before " << endl; for(auto e : myList) cout << e << " "; // get iterator to the number 1000 in the list list<int>::iterator findIter = std::find(myList.begin(), myList.end(), 1000); int val_to_move_to_end = *findIter; myList.erase(findIter); myList.push_back(val_to_move_to_end); cout << endl << endl << "List after " << endl; for(auto e : myList) cout << e << " "; return 0; }
You can use the std::list::splice(..) to achieve this myList.splice(myList.end(), myList, std::find(myList.begin(), myList.end(), 1000)); Check out the documentation
71,368,669
72,119,435
Cannot get gfwl source package to work in vscode
I wanted to learn OpenGl because I was just getting into c++ and I thought it would be cool to learn but now I'm stuck and I don't know what to do. So basically I am not using the microsoft version of VScode, I am using your basic VScode application. I install MinGw and added it to the path. and i created a folder, in that file i created a main.cpp file and downloaded the source folder (source package) of gfwl from the main page and I tried different ways of including it into my cpp file i tried the path of gfwl from the system <GFWL/gfwl3.h> the files directory to gfwl3.h and none of them seem to work, I either get a "directory or file path invalid" or errors on it failing to import its functions like gfwlinit how could i make this work?
Make sure to add it to the path and use a MakeFile to compile and to connect everything!
71,368,709
71,369,074
How to use an enum attribute of a class for an argument of a setter function for that class?
I have a class method that needs to know the value of a variable named mode which takes the values 1 an 0 and is a private attribute of the class. I want to write a setter function that can change mode to 1 or 0. However, I must use an enum to determine the new value that I should set mode to: enum sequence {error=0,active =1}; I want sequence to be an attribute (I was hoping to make it private) of the class. How can I write a setter function that takes as input active or error and sets the value of mode accordingly. Here is the basic structure of my code: #include <iostream> class Blink{ public: void setter(...){ } private:() int mode = 0; enum sequence {error = 0, active = 1}; }; Blink b; int main() { b.setter(active); } PS: I'm having a hard time coming up with a good title for this question, suggestions are appreciated!
It's pretty straight forward. This is how I would do it in C++11 and above: class Blink { public: enum class Sequence { Error, Active }; void setter(Sequence s) { if (s == Sequence::Active) { mode = 1; } else { mode = 0; } } private: int mode = 0; }; Blink b; int main() { b.setter(Blink::Sequence::Active); } The main difference is that Sequence is declared publicly. Note that mode is still a private variable so there is no harm. Sequence becomes part of the public interface because it needs to be understood from outside. The second change is that I use enum class. Yes, you could also use a plain enum that implicitely casts to the integer, but see Why is enum class preferred over plain enum? In this simple example, I would instead use private member Sequence mode = Sequence::Error; instead of int mode = 0;.
71,369,087
73,994,605
Why does temporary struct member not have the expected value in C++?
Consider this code: #include<iostream> struct A { int b; }; int main() { int c = (A() = A{2}).b; // Why is c zero after this? std::cout << "c = " << c << std::endl; std::cout << "A.b = " << (A() = A{2}).b << std::endl; } In my mind this is two equivalent ways to print the same value, but I get this result (on GCC 7.3.0 under MinGW): c = 0 A.b = 2 I would have expected c to be 2. Can anyone explain why it is 0?
As mentioned by @StoryTeller-UnslanderMonica, this is a GCC bug. I tested several versions on godbolt.com. Here's what I found: works as expected on gcc 6.* with c++ 11 and 14 fails on gcc 7.*, 8.*, 9.1-4 with c++14 works on gcc 7.*, 8.*, 9.* with c++11 works on gcc 9.5 with c++14 works on gcc 10 with c++ 11 and 14 I compiled with -O3, and tested some with -O0, and optimization level didn't make a difference where I tested. I'm not sure where to find the bug ticket. Here's a link to the change summary for GCC 9 versions, and Here's a link to the bugzilla tickets resolved by 9.5. I didn't see anything that looked like an exact match. Either I missed it, or the ticket didn't get put in that list (which the change summary page mentions is a possibility). This list might not be complete (that is, it is possible that some PRs that have been fixed are not listed here).