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
74,300,516
74,300,949
The while loop doesn’t stop on a boolean condition
I wrote a simple code to solve an artificial problem. I want the program to exit the loop body after N =< 3, but the iterations continue after the condition isn't met. Where did i go wrong? int main(){ uint8_t N = 0; int power = 1; std::cin >> N; while (N >= 4){ power *= 3; N -= 3; ...
uint8_t is char type. In stdint.h, typedef unsigned char uint8_t; '4' will be resulted in integer 52 due to implicit casting. You may just use int type if you are accepting number.
74,300,697
74,300,770
while loop doesn't loop in c++
So i just started C++ yesterday, I had a fair bit of java experience so that be the cause idk, I try to run this code and for some reason the while loop isn't looping, i tried changing the if break statement from ask==false to ask=false, that just ends up with an infinite loop without even taking user input. Here's the...
Call clear on cin before the input and make sure the input is only 0 or 1, From cppreference: If the type of v is bool and boolalpha is not set, then if the value to be stored is ​0​, false is stored, if the value to be stored is 1, true is stored, for any other value std::ios_base::failbit is assigned to err and true...
74,301,738
74,302,037
cpp vector erase by indices too slower than python
I want to delete items in vector by indices in cpp code. However it is too slow cpp version long remove_cnt = 0; for (auto &remove_idx : remove_index) { mylist.erase(mylist.begin() + (long) remove_idx - remove_cnt); remove_cnt++; } python version new_mylist = [item for i, item in enumerate(mylist) if i not...
Your question is a good example of why a 1-1 translation between languages usually doesn't work. To efficiently erase items from a vector you don't do it by index. Assuming you got your indices in python by evaluating some condition (a predicate). You can directly use this predicate in C++. Say you want to remove all i...
74,301,886
74,302,056
How to sort integer array in descending order (but starting at index 0 and moving up)?
my question has to do with sorting an integer array into descending order, but I've got a very specific problem and was wondering if there's a way to solve it without destroying the binary search function I also implemented. My project overall is perfect, but has one problem which is a dealbreaker according to my instr...
In the code, you sort the array with sort(array1, array1 + n); That will be ordered using the less-than < operator, which will sort it in ascending order. But when you display it: for (int n = 19; n >= 0; n--) cout << array1[n] << " "; which you do in reverse order (making it seem like it's sorted in descending o...
74,302,290
74,344,336
How to disable DPI scaling in wxWebview in wxWidgets?
I am working with the wxWebView of wxWidgets 3.2.1 in Windows 10. I am also using the Edge backend (WebView2). I have a problem in High DPI monitors and that's the automatic scaling of the Edge. I don't want this automatic scaling and prefer to set the font size manually with the use of some helpful functions like From...
It seems that there is not any way to disable scaling feature in Edge via wxWidgets. Therefore because of this automatic upscaling in Edge, I had to downscale my font size first with the use of GetDPIScaleFactor().
74,302,381
74,303,303
boost::lexical_cast can convert hex inside string to int?
I see in this topic C++ convert hex string to signed integer that boost::lexical_cast can convert hexadecimal inside string to another type (int, long...) but when I tried this code: std::string s = "0x3e8"; try { auto i = boost::lexical_cast<int>(s); std::cout << i << std::endl; // 1000 } catch (boost:...
As per the answer from C++ convert hex string to signed integer: It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings. Also, as per boost::lexical_...
74,302,474
74,302,557
Initializing std::map with MFC objects doesn't compile
MFC beginner here. I've tried to initialize std::map like this: (in the header of CView) // myprogramView.h std::map<int, CStatic> myMap = {{10,{}}, {11,{}}}; But the compiler complains "no instance of constructor ... matches the argument list". (Edit for future reference) The above message was an error from IntelliSe...
MFC objects that derive from CObject (like CStatic) cannot be copied; they have a deleted copy constructor. But initialization from an initializer list requires objects that are copy-constructible.
74,302,653
74,317,902
fmt lib check variadic templates arguments with FMT_STRING at compile time
I'm creating my own logger implementation. To format the log message I'm using the great FMT lib. I'd like to check all passed format arguments at compile time using FTM_STRING. I'm having 2 problems The following results in a compiler error "call to immediate function is not a constant" is it possible to combine def...
The problem is that you are calling FMT_STRING with a runtime string_view which cannot be checked at compile time. Moreover FMT_STRING is a legacy API for older compilers. It is recommended to use fmt::format_string instead: template<typename... Args> void LoggerTask::log(fmt::format_string<Args...> fmt, ...
74,304,193
74,304,563
QRandomGenerator gives all the time same values
im new in QT/c++ so i have one question, QRandomGenerator genereate same numbers all the time ? I try to make something, random choice a vectors: int index; QRandomGenerator num = QRandomGenerator(); index = num.bounded(6); if (index == 0){ return dmpcY1; }else if (index == 1){ retur...
Please consider taking another look at the documentation for QRandomGenerator: You are always creating a new random generator while using the default constructor with seed value of 1, resulting in always the same pseudorandom number to be generated QRandomGenerator::QRandomGenerator(quint32 seedValue = 1) Initializes ...
74,304,301
74,304,572
Invalid constraint expression
The following code example doesn't compile with Clang 15 or Clang trunk, in contrast to GCC 12.2 and MSVC 19.33. Is the contraint expression in the nested required clause invalid? struct t { constexpr auto b() const noexcept { return true; } }; template<typename T> concept c = requires(T t) { requires t.b(...
[expr.prim.req.general] (emphasis mine) 4 A requires-expression may introduce local parameters using a parameter-declaration-clause ([dcl.fct]). A local parameter of a requires-expression shall not have a default argument. Each name introduced by a local parameter is in scope from the point of its declaration until th...
74,305,847
74,306,250
stringstream operator>> fails to assign a number in debug
I have this simple function that, given a string str, if it is a number then return 'true' and overwrite the reference input num. template <typename T> bool toNumber(string str, T& num) { bool bRet = false; if(str.length() > 0U) { if (str == "0") { num = static_cast<T>(0); ...
Your code is made too complicated, you can simplify it to this: template <typename T> bool toNumber(std::string str, T& num) { return !!(std::istringstream { std::move(str) } >> num); } https://godbolt.org/z/Pq5xGdof5 Ok I've missed that you wish to avoid zero assignment in case of failure (what streams do by defa...
74,305,853
74,306,215
Failing to generate X509 CSR with OpenSSL
I am trying to generate a signing request. Apparentely there is an error somewhere in the code (or UB most likelly) which leads to: garbage output locally returned code 139 on godbolt #include <memory> #include <stdexcept> #include <string> #include <iostream> namespace { std::string make_csr(); } // namespace in...
The root issue is here, the typo: unsigned char *request = request; It is initialized with an unspecified value and should be unsigned char *request = nullptr; Otherwise i2d_X509_REQ tries to realloc the invalid pointer. CRYPTO_free(request); // does not compile should be OPENSSL_free(request); https://godbolt.org/...
74,306,531
74,306,740
Linked List: Moving a Node to Start of the Linked List(C++)
The question is to find the key in a linked list and if it is present then move the node containing key to the front struct Node { int data; Node *next; Node(int data, Node *next_node) { this->data = data; this->next = next_node; } }; void display(Node *h...
In improvedSearch(), you are passing in the head parameter by value, so a copy of the caller's head is made, and any new value assigned to the head parameter by improvedSearch() will be only to that copy and not reflected back to the caller. But, improvedSearch() still modifies the contents of the list, and upon exit ...
74,306,914
74,306,938
c++ std::string use overwrites values
What am I doing wrong here? Apparently aval is overwritten when I call getbbb. Expected output is: test A aval: "aaa" test B aval: "aaa" Actual output is: test A aval: "aaa" test B aval: "bbb" File testb.c: #include <string> // g++ -o tempa testb.c && ./tempa std::string getaaa() { return std::string("aaa"); } ...
const char * aval = getaaa().c_str(); leads to undefined behavior. getaaa() returns a temporary string object that is destroyed when the full expression that created it is finished (ie, on the ;), which is after you have grabbed the string's data pointer. Thus, the pointer is left dangling, pointing at freed memory. A...
74,307,601
74,307,937
Apple METAL C++ problem with MTL::CopyAllDevices();
I'm trying to get C++ code working with Metal. I get the array of MTL:Device by calling NS::Array *device_array = MTL::CopyAllDevices(); Next, I want to get the only element of the MTL::Device array by calling MTL::Device *device = device_array->object(0); I get an error: Cannot initialize a variable of type 'MTL::De...
NS::Array just contains NS::Objects, it doesn't know what it contains, therefore by default .object(index) returns NS::Object* which is a base class of MTL::Device and therefore not automatically castable. Fortunately object is a template so you can just do: MTL::Device *device = device_array->object<MTL::Device>(0); ...
74,308,250
74,309,345
C++ How to pass array to a print function?
The program asks the user for a number of random numbers, then gives a menu of what to do with the arrays. I want to print the arrays to the standard output device. How do I pass "baseArray[i]" and "copyArray[i]" to "arrayPrint(int arr[], int size)" ? void randN() { int n; cout << "Enter a number (in the set of...
I made the local array variables into global variables. I also updated the random number generator based off of this: std::uniform_int_distribution
74,308,262
74,308,772
Why do partial and full C++ template specializations, that look almost the same, produce different results?
I haven't written many C++ templates till recently, but I'm trying to take a deep dive into them. Fixing one developer's code I managed to produce some compiler behavior that I can't explain. Here is the simplified program. ( When I try to simplify more, I lose that "strange" behavior). Let's think of some class Depend...
An explicit (full) specialization is not itself a templated entity and all name lookup etc., as well as ODR, is done for it as if it wasn't a template. MainDependee is not complete at the point you wrote it and therefore IsCompleteType<MainDependee> is inherited from std::false_type at this point. A partial specializat...
74,308,519
74,308,569
How do i make different responses to different user inputs?
I'm a beginner, so please excuse my silly mistakes. I'm trying to get a specific output when I input a specific name using strings, but I keep getting an error that my name wasn't declared in the scope. I also want to be able to add different responses for different inputs. I tried looking up how to use strings, and I ...
First, std::cout << firstname; is a no-op since firstname is empty at that point. Second, there is no name in your code. Is the error referring to leo? That should be wrapped in double-quotes since you meant it to be a string literal, not a variable. Try something more like this: #include <iostream> #include <string>...
74,308,720
74,308,786
Binary tree: root remains NULL after addition
The problem is my root stays NULL when I need it to change after the first call of my addContact function. I have tried pointer to pointer but got an access error... This 0x28... Is all I remember about the error. I have also tried using *& in the parameter of my addContact function but to no avail. What I will show in...
In addContact you have modified the root parameter, but that is local to the function and has no bearing on the value passed in. Sticking with raw pointers, you may want to pass in a pointer to a pointer, so you can modify the pointer you're pointing to. Node* addContact(Node** root, Transaction data) { if (*root =...
74,308,933
74,309,050
Address of static data member
Why C++ doesn't allow taking the address of a static data member when the data member is initialize within the class and doesn't have an out-of-class definition? How is the storage allocated for static member in this case? The below minimum program demonstrate the issue. #include <iostream> class Test { public: st...
This line is a declaration: static const int a = 99; It is not a definition. For storage to be allocated, you need a definition. That's where your commented line comes into play. You can use Test::a even if it has no definition because it is treated as a compile-time constant. In general, a static const T variable (wh...
74,309,235
74,309,609
How to define equivalent rule for non type template arg
After some time of figuring out my question I have found it's really fascinating how compiler can deduce template arguments from set of "tags" (non-type template args). But it looks like the compiler only understands "byte by byte" equality rule. What I mean is this code: struct S1 { constexpr S1(int v) : _v(v) ...
Template parameter deduction, and other template-related things, use the concept of type equivalence. The parts relevant to your question are these: temp.type/1 Two template-ids are the same if ... (1.3) - their corresponding non-type template-arguments are template-argument-equivalent (see below) after conversion to ...
74,309,326
74,310,178
Print backwards all the positive even integers starting with 100 using loop
How do I print only the even integers using a loop? so far I have: for (int i = 100; i > 0; i--) { cout << i << ", "; } which prints all the numbers, even and odd. How do I print just the even numbers?
Sigh. All the comments (and the close vote) seem hung up on checking whether an integer is even. That's not needed; instead of skipping odd values, don't generate them in the first place: for (int i = 100; i > 0; i-=2)
74,309,382
74,309,666
cmake: target_link_libraries - /usr/bin/ld: cannot find X No such file or directory
I'm trying to include this library in my project: https://github.com/kuafuwang/LspCpp.git I'm using FetchContent which succesfully populates _deps/lspcpp-build, _deps/lspcpp-src, _deps/lspcpp-subbuild: FetchContent_Declare( lspcpp GIT_REPOSITORY https://github.com/kuafuwang/LspCpp.git ) FetchContent_GetProperti...
You are missing a step for FetchContent, to build the library. FetchContent_Declare( lspcpp GIT_REPOSITORY https://github.com/kuafuwang/LspCpp.git ) FetchContent_GetProperties(lspcpp) if(NOT lspcpp_POPULATED) FetchContent_Populate(lspcpp) add_subdirectory(${lspcpp_SOURCE_DIR} ${lspcpp_BINARY_DIR}) # add...
74,309,472
74,309,935
SendMessage COPYDATASTRUCT wrong string when recive in delphi
I send the following c++ application request: string data_to_send = "Hello World"; PCSTR lpszString = data_to_send.c_str(); COPYDATASTRUCT cds; cds.dwData = 0; // can be anything cds.cbData = sizeof(TCHAR) * (data_to_send.size()); cds.lpData = &lpszString; cout << lpszString << endl; SendMessage(Output, WM_COPYDATA, (W...
On the C++ side: cds.dwData should not be 0. Use a more unique value, such as the result of calling RegisterWindowMessage(). Many apps, and even the VCL internally, use WM_COPYDATA for different purposes, so you don't want to get confused with someone else's message by mistake. sizeof(TCHAR) should be sizeof(char) i...
74,309,702
74,310,210
Merge several linked lists (smth with memory)
I've made my own linked list and now I am trying to implement function which will merge all lists. However, unfortunately I get this error: "linkedList(28488,0x102a88580) malloc: *** error for object 0x600003a70010: pointer being freed was not allocated linkedList(28488,0x102a88580) malloc: *** set a breakpoint in mall...
issue is here List list; makeList(list, nums); vecOfLists.push_back(list); list will be destructed after that push_back and hence delete all its allocated nodes, but then when you exit main the destructor is called again for the copy of List head in that vector. YOu need to make the copy operation (used b...
74,309,802
74,309,993
Compile time hints/warnings on struct changes
I have a basic POD struct with some fields struct A{ int a, int b, }; The nature of my use case requires that these fields change every so often (like 1-2 months, regular but not often). This means that I want to check the field usages of the struct after the changes to make sure everything is still fine. The ...
One possibility is to put a version number into the struct itself, like so: struct A{ int a; int b; static constexpr int major_version = 1; }; Then, in calling code, you place assertions that check the value of the major version: void doSomething(A a) { static_assert(A::major_version == 1, "Unexpected...
74,310,316
74,310,407
Using variables from a class's constructor in one of its member functions?
I'm learning C++ and I want to know if there is a way you can use variables defined in a class's constructor in a member function. I've tried looking online and in my textbook but I can't find a definitive answer. For example: class Item { public: Item(std::string str) { std::string text = str; int pos =...
I want to know if there is a way you can use variables defined in a class's constructor in a member function. No, you can't. Variables defined in the constructor goes out of scope at the end of the constructor. The normal way is to initialize member variables in the constructor. These can then be accessed in the memb...
74,310,514
74,310,596
How to create the instance of a concrete implementation of a class in C++ as in Java?
Maybe it's a little weird question, but: I'm not so much familiar with C++. Let's say we have an abstract class A and a class B that extends it: abstract class A { abstract void foo(); } class B extends A { @Override void foo() { // . . . } } Then, in the Test class, we can create an instance ...
In C++ you can't construct an abstract class, but you can make a pointer to an abstract class. Here's a direct translation of your code to C++: #include <iostream> struct A // structs are classes that are default public { // having at least one method be // "= 0" flags the class as abstract: virtual void f...
74,310,697
74,310,728
C++ undefined behavior with too many heap pointer deletions
I wrote a program to create a linked list, and I got undefined behavior (or I assume I did, given the program just stopped without any error) when I increased the size of the list to a certain degree and, critically, attempted to delete it (through ending its scope). A basic version of the code is below: #include <iost...
It is a stack overflow caused by recursive destructor calls. This is a common issue with smart pointers one should be aware of when writing any deeply-nested data structure. You need to an explicit destructor for Node removing elements iteratively by reseting the smart pointers starting from the tail of the list. Also ...
74,311,243
74,311,448
How to avoid duplicated code when using recursive parameter packs C++
How do you avoid code duplication when using varadic parameters in c++? Notice that I'm using templates recursively to achieve my goals, therefore I need some base cases and a recursive case. This creates a lot of code duplication, are there ways I could reduce this duplication? Below, an example is provided of code th...
The only difference between a single-dimension tensor and a multiple-dimension tensor is the type of std::array, T for single and Tensor<T, M...> for another. template<typename T, std::size_t N, std::size_t... M> class Tensor<T, N, M...> { using InnerT = std::conditional_t<(sizeof...(M) > 0), ...
74,311,733
74,311,785
C++ Sum parameter pack into a template argument
How can I sum all the std::size_t parameters passed through the template into one std::size_t value that will define the size of the array. template<typename T, std::size_t... N> class Example { std::array<T, N + ...> data; // std::array<T, sum of all N...> };
You almost have it. You need to use a fold expression for this which is the same syntax, just surrounded with (). That gives you template<typename T, std::size_t... N> struct Example { std::array<T, (N + ...)> data; // std::array<T, sum of all N...> }; And in this example you'll get an error that tells you the a...
74,311,777
74,311,805
When is it ever useful to use negative indexing of a C array?
C arrays allow for negative indexing, but I can't think of a use for that, seeing that you'll never have an element at a negative index. Sure, you can do this: struct Foo { int arr1[3] = { 1, 2, 3 }; int arr2[3] = { 4, 5, 6 }; }; int main() { Foo foo; std::cout << foo.arr2[-2] << std::endl; //output is 2 }...
Remember that when you index an array, you get the element at index N which is the element at &array[0] + sizeof(array[0]) * N. Suppose you have this code: #include <stdio.h> int main() { int a[5] = {5, 2, 7, 4, 3}; int* b = &a[2]; printf("%d", b[-1]); // prints 2 }
74,312,356
74,312,455
C++20 How to get the last element of a parameter pack of std::size_t
I've seen many answers online such as this one, but they do not seem to work when the parameter pack is of std::size_t. template <typename ...Ts> struct select_last { using type = typename decltype((std::type_identity<Ts>{}, ...))::type; }; template<std::size_t... N> class Example { private: using type = selec...
The template<std::size_t... N> is based on a non-type template parameter, so you cannot extract the type (or more precisely, there is no sense in trying to extract the type - I can just tell you it is std::size_t!), you may however extract the value, into a static constexpr. Here is the proposed code: template<std::siz...
74,312,956
74,313,430
Dynamically allocate a vector using new keyword
I was wondering if it is possible to dynamically allocate a vector using new keyword, similar to an array. what I mean is this: vector<int> *vptr = new vector<int>; I could not find proper reference about this problem over the internet. I would like to know what the below statement means. Both are valid syntax. Also h...
#include <iostream> #include <vector> using namespace std; int main() { // v is pointer toward a vector<int> vector<int> *v = new vector<int>(); // So we should use '->' to dereference // and use the method push_back v->push_back(1); v->push_back(2); v->push_back(3); for (auto i = 0u;...
74,313,180
74,313,261
How to prevent floating-point being implicitly converted to integral value at function call in c++?
How to prevent floating-point being implicitly converted to integral value at function call? #include <iostream> void fn(int x) { std::cout<<"fn("<<x<<")\n"; } int main() { std::cout<<"Hello, this is 301014 :)\n"; fn(2); fn(3.5); return 0; } Here the outputs are 2 and 3 respectively. I am compili...
There are multiple ways to handle this in c++11. Method 1: You SFINAE the function template fn by using std::enable_if. template<typename T> typename std::enable_if<std::is_same<T, int>::value>::type fn(T x) { std::cout << "fn(" << x << ")\n"; } int main() { std::cout << "Hello, this is 301014 :)\n"; fn(2)...
74,313,313
74,313,489
To transform std::bind to std::function?
See the code below queue<function<void()> > tasks; void add_job(function<void(void*)> func, void* arg) { function<void()> f = bind(func, arg)(); tasks.push( f ); } func is the function I want to add to the tasks which has argument is arg. How can I do to use std::bind to bind its argument so that it can be as...
How can I do to use std::bind to bind its argument so that it can be assigned to the object of function<void()>? The std::bind returns an unspecified callable object, which can be stored in the std::function directly. Therefore you required only function<void()> f = bind(func, arg); // no need to invoke the callable ...
74,313,612
74,313,663
declared ‘[[noreturn]]’ but its first declaration was not
I recently learned about the [[noreturn]] attribute and wanted to try and implement it on one of my existing code snippets. I added the attribute to a void return type function with no return; keyword on it whatsoever. However, I'm getting this error: [ 17%] Building CXX object CMakeFiles/Renderer.dir/src/opengl/text_r...
The attributes needs to be in the actual declaration of the function, the one you have in the header file inside the Text class. For the definition (implementation) of the function you don't need to use the attribute again. On a couple of different notes, using the const qualifier for a void return type makes no sense...
74,313,768
74,323,162
How to add shared or static library using PyTorch C++ extension?
How do I use torch.utils.cpp_extension.load to link shared or static library from external source? I wrote some function in C++, and am using it in PyTorch. So I am using load function from torch.utils.cpp_extension to load a PyTorch C++ extension just-in-time (JIT). This is the wrapper.py file's content: import os fro...
I've figured this out. extra_ldflags argument in torch.utils.cpp_extension.load can handle this. In my case, I've added libzstd.so file in my repository and added -lzstd in above argument.
74,314,363
74,315,347
How to delete memory for object created by *new
I have question regarding memory management in c++ In below example is there any memory leakage. If so how to clear memory. Also defining int by * new is the only option to use and not int num = 25; int main() { for(int i = 0;i < 200;i++) { int num = * new int(25); } I tried many ways but delete and free doe...
OP: Also defining int by * new is the only option to use and not int num = 25; No, in C++ you have different ways of create new data. In short, you can create new data automatically, dynamically or statically. automatic storage duration A a obj; Here you're creating an object with automatic storage duration, this me...
74,314,609
74,314,707
Clang build an executrion file in vscode
I've been searching whole internet but I can't find the solution for building my c++ project with clang compiler. I'm new to all this stuff and sorry for misunderstanding. I have default tasks.json file: { "version": "2.0.0", "tasks": [ { "type": "shell", "label": "clang++ build ...
If you read the documentation (which is for MinGW but it's exactly the same for Clang for Windows), you need to explicitly add the .exe suffix to your output file. So your "executable" file is the one named main, without any suffix or "extension". You need to change your tasks.json file to add the .exe suffix: "${fileD...
74,315,382
74,315,527
does C++ have spread operator?
can you do this in C++: vector<int> v1={1,2}, v2={3,4}; vector<int> v3={...v1, ...v2, 5}; //v3 = {1,2,3,4,5} What is the simplest way to do this with C++ ?
No spread operator in C++. Probably the simplest way would be a sequence of inserts std::vector<int> v3; v3.insert(v3.end(), v1.begin(), v1.end()); v3.insert(v3.end(), v2.begin(), v2.end()); v3.insert(v3.end(), 5); Various range libraries have a concat function auto v3 = ranges::views::concat(v1, v2, { 5 }) | ...
74,315,771
74,316,003
How to delete strings from a file containing multiple lines in C++?
I tried this code but it deletes data if a file has only one line. When file contains multiple lines this code throws an exception. How to fix it? int main() { string deleteline; string line; ifstream fin; fin.open("Test1.txt"); ofstream temp1; temp1.open("temp.txt"); deleteline="|start|"; ...
Could you please try this one ? #include <iostream> #include <fstream> #include <string> int main () { std::ifstream in_file("input.txt"); std::ofstream out_file("output.txt"); std::string str; const std::string removed_str = "|start|"; while (std::getline(in_file, str)) { std::size_t ind = str.fin...
74,316,130
74,316,159
C++ function that deletes dynamic linked list
I'm currently working on a class project where we make a linked list and we're supposed to create a function that clears the list then deletes it (with "delete LIST_NAME;"). I have implemented the function as instructed by my professor, also forcing the list to become null after the delete. The function works within it...
You take list by value so it's local to the function. If you'd like to make changes to it that are visible at the call site, take it by reference: // `list` is now a reference to the pointer at the call site: void Destroy(LinkedList*& list) { Clear(list); delete list; list = nullptr; // this now sets the re...
74,316,550
74,323,390
C++: Is there any bijective mapping between types and any other data type defined by the standard?
I am working on a project that makes heavy use of static polymorphism. A particular use-case that I am interested in would be made possible by static reflection, but we still don't have this in C++. The use case looks something like this: I have a functions that read/write a data structure to/from a binary file: templa...
No. Nor does the problem seem to benefit from one. Serialization is not generically possible in C++, so you will have customization points whether you implement them or your user does to serialize and deserialize and they will be type-specific. In other words, in: template <typename data_t> void write_binary(const my_t...
74,316,851
74,316,971
C++ Bitshift in one line influenced by processor bit width (Bug or Feature?)
I encountered a strange problem, but to make it clear see the code first: #include <stdio.h> #include <stdint.h> int main() { uint8_t a = 0b1000'0000; // -> one leftmost bit uint8_t b = 0b1000'0000; a = (a << 1) >> 1; // -> Both shifts in one line b = b << 1; // -> Shifts separated into two i...
What you're seeing is the result of integer promotion. What this means is that (in most cases) anyplace that an expression uses a type smaller than int, that type gets promoted to int. This is detailed in section 7.6p1 of the C++17 standard: A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t...
74,316,883
74,317,081
How to delete those string from file which is followed by "|" and end with "|"?
This code only deletes a string which I provide it in removed_str variable but I want to delete all the string which start from "|" and ends with "|". How should i do it? int main() { std::ifstream in_file("Test-1.txt"); std::ofstream out_file("output.txt"); std::string str; const std::string removed_str =...
Could you please try this one ? #include <iostream> #include <fstream> #include <regex> int main () { const std::regex pattern("\\|(.*?)\\|"); std::ifstream in_file("input.txt"); std::ofstream out_file("output.txt"); std::string str; while (std::getline(in_file, str)) { str = std::regex_...
74,317,702
74,317,905
Multiple functions with the same name but their parameters are either constant or received by value or by reference
The title is a bit lengthy, but it's best explained by an example: Suppose we have the following functions in C++: void SomeFunction(int num) { //1 } void SomeFunction(int& num) { //2 } void SomeFunction(const int& num) { //3 } void SomeFunction(const int num) { //4 } All of these are called the same way: SomeF...
1 and 4 have the same signature, so you'll need to drop one of those. The other functions cannot be called directly, but you could add a template function that allows you to specify the desired parameter type: template<class Arg> void Call(void f(Arg), Arg arg) { f(arg); } // Driver Program to test above functions...
74,317,971
74,435,993
Cannot format an argument. To make type T formattable provide a frormatter <T>
So im creating a game engine in accordance to thecherno's tutorial and I am adding GLFW Error handling(This is c++) and I cannot figure out where and how to add a formatter for SPDLOG Here is my Log.h: #define PL_CORE_TRACE(...) ::Pluton::Log::GetCoreLogger()->trace(__VA_ARGS__) #define PL_CORE_WARN(...) ::...
Add #include <spdlog/fmt/ostr.h> to Log.h file. With this spdlog would be able to use operator<< in Event.h
74,318,075
74,318,245
Can we have a map like this in c++ >> map <vector<int>,vector<int>> m;
Just a tought came in mind till now i have make maps of strings and vectors Like this map<int,int> m; map <int,vector<int>> m; map <string,vector<int>> m; and various combinations are possible with other data types also. But what will happen If I do map <vector<int>,vector<int>> m; or map <vector<int>,vector<vector<in...
It's perfectly fine to use std::vector<int> as a key in std::map but you'll need take a look at the requirements for a given type to be used as a key in std::map. From the documentation: std::map is a sorted associative container that contains key-value pairs with unique keys. Keys are sorted by using the comparison f...
74,318,341
74,318,507
CoderPad C++ Hashmap did not work during job interview. Can you explain to me why?
So I had a job interview two days ago and they used coderPad.io for it, which is pretty common for job interviews. As a matter of fact, I have another job interview coming up that uses coderPad as well, so I really need to ask this question. Essentially what happened was that my algorithm was written correctly. My inte...
Per https://en.cppreference.com/w/cpp/container/unordered_map/insert, the insert method "inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key." The call to insert in the following section won't actually change the contents of the unordered_map. if (map.find(a...
74,318,422
74,318,436
does this C++ function produce a memory leak
If, in a function, I have the following code: someClass *x = new object(); x = nullptr; is this a memory leak? Or, is the memory reallocated due to its local scope? Thanks! Not sure how to test this on my own.
This is a memory leak. It is about the clearest example as one can get.
74,319,138
74,319,467
how do i make a console menu (c++) that i can return to after selecting something?
i made a simple menu and i know how to make choices and stuff but once i select a choice i don't know how to make it so that it returns to the selection menu. #include <cmath> #include <iostream> #include <string> int main() { std::cout << "+====| LEO'S CALCULATOR |=========+\n\n"; std::cout << "1 - Addition\...
With a loop (do while for example) and an option to exit the loop. #include <iostream> int main() { int choice; do { std::cout << "+====| LEO'S CALCULATOR |=========+\n\n"; std::cout << "1 - Your menu...\n"; std::cout << "5 - Quit\n\n"; std::cout << "+=======================...
74,319,413
74,319,657
How to make a copy constructor for different types within a template class?
I need to make my Iterator< isConst = false> convert to Iterator<isConst = true>. That is, I need a separate method Iterator< true >(const Iterator< false > &). My Iterator class: template < typename T > template < bool isConst > class ForwardList< T >::Iterator { using value_type = std::conditional_t< isConst, const...
Rather than having a constructor that takes an Iterator<false>, you can have a conversion operator that returns an Iterator<true>. operator Iterator<true>() const { return Iterator<true>(nodePtr_); } You will need to friend class Iterator<false>; to access your private constructor. See it live
74,319,497
74,319,557
c++ left shift operator used inside array declaration
I found this array declaration in open source software. It reads data from csv files, compares the tuples, and outputs the best tuples. static const uint32_t SHIFTS[] = { 1 << 0, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7, 1 << 8, 1 << 9, 1 << 10, 1 << 11, 1 << 12, 1 << 13, 1 << 14, 1 << 15, 1 << 16, 1 <<...
The compiler will almost certainly generate the same static data for the two definitions. The difference is readability to human users. The declaration using the shifts actually presents a human-readable intent, that the array ought to be full of consecutive powers of two. In fact, it's sufficiently readable that many ...
74,319,524
74,319,711
What does "when the member is then reinitialized re initialized otherwise in the constructor" mean in cplusplus.com tutorial?
I'm reading classes tutorial in cplusplus.com. I got confused by the following paragraph. Default-constructing all members of a class may or may always not be convenient: in some cases, this is a waste (when the member is then reinitialized otherwise in the constructor), but in some other cases, default-construction i...
All objects are initialized before the body of the constructor is entered, so let's walk this through step-by-step: int age; Son() // age initialized here (does nothing) { age = 1;// age assigned new value here } But what if age is something more complicated than an int? What if it is a class with very expensive c...
74,320,014
74,321,085
How to convert c++ string with russian (cyrillic) letters to jstring
I am trying to convert a c++ string with russian letters to jni jstring But in the output of the java program i getting a different string How i converting: const char* msg = "привет"; return env->NewStringUTF(msg); This returns in java: ïðèâåò How to do it right?
First, you have to make sure your input char* string is encoded in UTF-8 to begin with (which it isn't, in your example). Second, JNI's NewStringUTF() method requires the input string to be encoded in modified UTF-8, not in standard UTF-8. When dealing with non-ASCII chracters, you are better off using a UTF-16 encoded...
74,320,233
74,323,478
Deleted function template in requires-expression, differing compiler behavior
Consider a function template f<T> with the primary template deleted but some specializations defined. We can use a requires-expression to test if f<T> has been specialized: template <typename T> int f() = delete; template <> int f<int>() { return 1; } template <typename T> int g() { if constexpr (requires { f...
Well, MSVC is definitely wrong. It thinks the requires-expression is actually true. But [dcl.fct.def.delete]/2 says: A program that refers to a deleted function implicitly or explicitly, other than to declare, it, is ill-formed. [Note 1: This includes calling the function implicitly or explicitly and forming a pointer...
74,320,718
74,320,932
Why I am getting an error that no member show is declared in the class, whereas it is declared in the class
class "bankdeposit" has no member "show" Here is the code: #include <iostream> using namespace std; class bankdeposit { int principal, years; float interest, returnvalue; public: bankdeposit(){}; bankdeposit(int p, int y, float r); // can be 2.00 bankdeposit(int p, int y, int r); ...
Inside the bankdeposit(int, int, int) constructor, the expression void show(); is in the wrong place. It needs to be inside the bankdeposit class declaration instead: class bankdeposit { ... public: ... void show(); // <-- move to here }; bankdeposit::bankdeposit(int p, int y, int r) { ... // ...
74,321,038
74,329,203
Trying to save unusual data type to file in binary and then write it to the vector
I wanted to create simple todo like program in console where you can input your task ((name) (level) (interesting level)) and it will save it from the vector to the binary file. I have this program, but when I try to save tasks to the file and then read from it, it gives me an error Segmentation fault (core dumped) and...
As mentioned on the comments you cannot do what you are trying to do with a dynamic object such as a std::string. You will never know how big such an object is when you are loading it. Because of that, your program may start loading part of another object on to the std::string. Your simplest solution in my opinion is t...
74,321,198
74,326,600
NtProtectVirtualMemory return STATUS_ACCESS_VIOLATION?
I'm tried to invoke NtProtectVirtualMemory from my dll, that was attached to application using followed code: typedef NTSTATUS(__stdcall* tNtProtectVirtualMemory) (HANDLE, IN OUT PVOID*, IN OUT PULONG, IN ULONG, OUT PULONG); ... HMODULE Ntdll = GetModuleHandle("ntdll.dll"); if (!Ntdll) { char outtxt[64]; sprint...
Unlike VirtualProtectEx, the NtProtectVirtualMemory function takes a pointer to the pointer that points to the address of the region whose protection is to be changed, and a pointer to the size: ULONG oldProtect; ULONG size = sectionData->size; PVOID address = sectionData->address; NTSTATUS sts = OrigNtProtectVirtualMe...
74,321,386
74,321,549
does the value I did allocate to an adress inside the memory stay?
lets say I initialized a value (ex 10) to a variable A in c++ after that I ended my program and coded another program, in that program I declared a variable B and by a miracle it was allocated at the same address of the variable A that I located in my first program so, does the value of the first variable (A) will be g...
Firstly, your process is almost certainly working with virtual memory addresses. That means the address 0x0001FBDC does not necessarily refer to the same physical memory across runs (or even during a single run). Ignoring that, in general, your program has to share the same physical memory with all other applications (...
74,322,155
74,323,321
Passing array of class objects
I've been trying for a long time to pass an array of objects to another class object. In settingUp.cpp: //** Status classes and their functions **// void settingUp(){ dataClass prueba0; dataClass prueba1; dataClass prueba2; const dataClass * arrayPrueba[3]; prueba0.setValues(1); prueba1.setVa...
In statusClass::setValues(), *_array is the same as _array[0]. You are storing only the first dataClass* pointer from the input array. Later, when using array[1], you are mistreating array as-if it were a pointer to an array of objects, when it is really a pointer to a single object instead. You are thus reaching past...
74,322,508
74,322,854
How to push string in a given range in stack in C++?
int main() { istringstream iss(dtr); Stack <string> mudassir; mudassir.push1(s1); string subs; do { iss >> subs; if (subs == "|post_exp|") { iss >> subs; while (subs != "|\\post_exp|") { mudassir.push(subs); ...
the inner while loop which has hello (just for testing) in it is running infinitely. I don't know why. Your inner while loop is not taking into account when the stream reaches the end of its data. When operator>> reaches the end of the stream, it will put the stream into the eofbit state, and subs will be set to what...
74,322,604
74,324,649
How can I load an image from the OpenGL/Glfw clipboard?
I am making a program that loads images and displays them with OpenGL / Glfw. I have managed to load the images from a path but I also want to do it from the windows clipboard. With text it works for me to read it. But when I copy an image from windows explorer nothing comes up or it tells me that the clipboard is empt...
GLFW doesn't provide that functionality at the moment. See issue #260, "Support for clipboard image data". GLFW's Windows implementation of glfwPlatformGetClipboardString() lives in src/win32_window.c if you feel like taking a stab at adding CF_BITMAP/CF_DIB/CF_DIBV5 support.
74,322,768
74,323,090
Is it possible to access a variable template without the template parameter?
I am not sure if this is viable. I want to initialize a variable template inside a constructor of my class. template<typename T> T var_tem; Struct A { template<typename U> A(U u) { var_tem<U> = u;} }; I am wondering if it's possible to access var_tem<U> later without knowing the type U. Also, I know whenever I ac...
The information of the type U is not available after the call to constructor. However, at the point of access, you also need to be aware of the type, otherwise you wouldn't know what you can do with it. So either you specify the type directly, or you're passing a visitor. Now, for visitors, as long as there's a compile...
74,323,099
74,323,310
How can I return unordered_map with a hash function to something expecting just `unordered_map<string, string>`
I want to implement an unordered_map<string, string> that ignores case in the keys. My code looks like: std::unordered_map<std::string, std::string> noCaseMap() { struct hasher { std::size_t operator()(const std::string& key) const { return std::hash<std::string>{}(toLower(ke...
You can't. There's a reason it's part of the type: efficiency. What you can do is e.g. store everything lowercase. If you need both lowercase and case-preserving, you might need two maps; but, at this point, I'd consider requesting an interface change.
74,323,131
74,323,312
Why doesn't sort this code the German words?
I'm trying to sort German words with their articles, but it don't work perfectly. Can you help me? Code: #include <iostream> #include <fstream> #include <cstring> #include <stdio.h> using namespace std; struct asd { string ne; string fn; }; int main() { asd szavak[50]; ifstream be("nemet.txt"); int ...
I haven't checked the validity of your code (it's a bit hard to read), but you should always resort to the algorithms supplied by the standard library (unless of course you want to learn how to write sorting algorithms). This helps to prevent bugs like this. In your case you can use the std::sort algorithm if you provi...
74,323,238
74,323,301
How to use preprocessor IF on DEFINE that is an ENUM member?
I am struggling with this for a while now, and cant get it to work! I have a preprocessor define for LOG_LEVEL which defines what logs my program should emit. I Have a lot of LOG points, so performance is needed, therefore, no use of runtime check for log_level. I trimmed my code to the minimal problematic construct wh...
You don't need the preprocessor for this. A normal if (LOG_LEVEL <= LOG_WARNING) will not create a runtime test when the condition involves only constants and the build has any optimization at all. Modern C++ allows you to force the compiler to implement the conditional at compile-time, using if constexpr (...). Thi...
74,323,336
74,323,481
Partial template specialization on class methods using enable_if
I have a templated class, for which I want to specialize one of the methods for integral types. I see a lot of examples to do this for templated functions using enable_if trait, but I just can't seem to get the right syntax for doing this on a class method. What am I doing wrong? #include <iostream> using namespace st...
Some fixes are required to your code. First, this isn't partial specialization. If it was specialization then you could only specialize the whole class template not just one method of it. You placed the ! in the wrong place. std::enable_if<....>::type is a type, !std::enable_if<....>::type does not make sense. You want...
74,323,453
74,323,519
compiler error in Visual Studio when std::reduce is invoked for different iterator and init types
Please consider the follownig simple code snippet: template<typename T> struct point2{ T x, y; }; template<typename T> std::complex<T> foo(std::vector<point2<T>> const& x) { std::reduce(std::execution::par_unseq, x.begin(), x.end(), std::complex<T>{}, [&](std::complex<T> const& first, point2<T> const& seco...
std::reduce allows elements in the set to be grouped and rearranged in any order to allow for more efficient implementations. It is required that all combinations of *first and init are valid arguments to the binary_op (quote from 27.10.4 Reduce #5): Mandates: All of binary_­op(init, *first), binary_­op(*first, init),...
74,323,723
74,323,838
Is there a technical reason why an enumerator is not a literal?
I thought that the enumerators of an enum [class] were literals, because, to my understanding, they represent for their enum [class] what 1 represents for int, true for bool, and "hello" for char const*. However, they are not, because the standard lists only these literals, literal: integer-literal character-li...
Is there a technical reason why an enumerator is not a literal? You'll notice that the term "literal" is defined in the C++ standard chapter "Lexical conventions". "Lexical" here refers to Lexical analysis, which takes a sequence of characters and generates a sequence of tokens. These tokens then undergo grammatical ...
74,325,702
74,331,910
Is it possible to make a vector of ranges in cpp20
Let's say I have a a vector<vector<int>>. I want to use ranges::transform in such a way that I get vector<vector<int>> original_vectors; using T = decltype(ranges::views::transform(original_vectors[0], [&](int x){ return x; })); vector<int> transformation_coeff; vector<T> transformed_vectors; fo...
It is not possible in general to store different ranges in a homogeneous collection like std::vector, because different ranges usually have different types, especially if transforms using lambdas are involved. No two lambdas have the same type and the type of the lambda will be part of the range type. If the signatures...
74,325,837
74,347,183
Import a std::vector<Mat> to specific index of 3D cv::Mat
I have a vectorimageSlices and a 3D : cv::Mat RTstruct3D(3,DImensions3D, CV_8U, Scalar(0)) I want to put my vector into the specific index of 3D cv::Mat. //Make a 3D Organ int programCounter = 0; vector<Mat>imageSlices; for (size_t k = 0; k < Npoint_Z.size(); k++) { ...
//Add Organ to RTSTRUCT 3D vector<Mat>RTstruct3D(DImensions3D[0], Mat(DImensions3D[1], DImensions3D[2], CV_8U)); for (size_t i = 0; i < Npoint_Z.size(); i++) { RTstruct3D[Npoint_Z[i][1]] = imageSlices[i]; }
74,326,065
74,326,195
C++ coder for marks need help fixing it
I was trying to learn c++ i wanted to find marks using the code the issue is that it is not giving me the correct output and i wanted it to loop if the marks are less i wawnted to repeat it . This is the code that i wrote #include <stdio.h> #include <stdbool.h> #include <string.h> void mygrade(int grades) { if (g...
If you want the program work as you write in the picture, there are three things to do: You can just use if (grades >= 90) // … else if (grades >=80) // … // and so on since else if statement will be trigger only if all cases above it are not true. You need to call mygrade() function in the main() function ...
74,326,353
74,326,595
printing the below pattern using just one loop
ive got the below code to print a pattern (attached below). However i'd like to just use one loop #include<iostream> using namespace std; int main(){ int n; cin>>n; for(int i=1;i<=n;i++){ for(int j=1;j<=i;j++){ cout<<"*"; } for(int j=1;j<=n-i;j++){ if(j%2!=0){...
Try this and see how it does what you want to understand the step you did not find on your own: #include<iostream> using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n*2-1; i++) { if (i <= n) { for (int j = 1; j <= i; j++) { cout << "*"; ...
74,326,803
74,326,863
C++ Reuse out-of-class comparsion operators of base for derived class
Snippet struct A { int a; }; bool operator==(const A& lhs, const A& rhs) { return lhs.a == rhs.a; } template <typename T> bool operator==(const A& lhs, const T& rhs) { return lhs.a == rhs; } template <typename T> bool operator==(const T& rhs, const A& lhs) { return lhs.a == rhs; } struct B : public A { ...
Is it possible to make the last comparison b1 == b2 work without a static_cast? Yes, you can use SFINAE as shown below: bool operator==(const A& lhs, const A& rhs) { return lhs.a == rhs.a; } template <typename T> typename std::enable_if_t<!std::is_same_v<T, B>, bool > operator==(const A& lhs, const T& rhs) { ret...
74,327,569
74,327,604
Error C++: no operator matches these operands. operand types are: std::ostream << void
I'm getting the error in my GetInfo() method: void Quadrangle::GetInfo() { cout << "Area = " << GetArea() << endl; cout << GetPerimeter() << endl; //!!!error: no operator matches these operands. operand types are: std::ostream << void } double Quadrangle::GetArea() { return 1.0 / 2 * (d1 * d2 * sin(angle *...
You are trying to output a message twice. You are trying to output the message from the GetPerimeter function. void Quadrangle::GetPerimeter() { cout << "Not enough information provided to calculate a perimeter for a quadrangle" << endl; } And you are trying to output the return value of GetPerimeter cout << GetPe...
74,327,782
74,327,982
How can I find the number of scores entered by a user are greater than 80?
I have been trying to code a program that takes input from the user for scores and then calculated the average with an input validation. The only thing I am unable to figure out is how to tell the number of scores entered which are greater than 80. Also I have to do this without using arrays. Here's what I currently ha...
You mixed up the sequence of statements in your code. Strong hint: If you write comments, then you will avoid such problems. Please see below your corrected code #include <iostream> #include <limits> using namespace std; int main() { int score, sum = 0, greater = 0; // Get 5 values from user for (int i = ...
74,327,997
74,328,332
c++ No instance of overloaded function "std::async" matches argument list
i'm trying to run a listener Method async with std::async but i get the following error: No instance of overloaded function "std::async" matches argument list auto listener = std::async(std::launch::async, server.Listen()); The server.Listen() returns void (nothing) I've already read throu https://en.cppreference.com/w...
Solution thanks y'all for your answers, both solutions worked! and also thanks for the comment on the <redacted> 'practice' the working code: auto listener = std::async( std::launch::async, &myprojectlibrary::IPC::UnixSocket::Server::Listen, std::ref(server) ); auto listener = std::async( std::launch...
74,328,144
74,346,658
c++ ole automation how to clear excel cell contents
I am using the following function call of IDispatch interface to successfully write Hello World! to a cell in excel sheet excel. LPOLESTR ptName = L"Value"; //What is the key for clearing the cell contents? DISPID dispID; xlCell->GetIDsOfNames(IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID); LCID lcid =...
While I could not find the unique DISPID for clearing a cell/cell range, the thing that did work was to modify the VARIANT passed to the Invoke(). All I did was to change the VARIANT from this vArgArray[0].vt = VT_BSTR, vArgArray[0].bstrVal = SysAllocString(cellVal.c_str()); to this vArgArray[0].vt = VT_EMPTY; Hope i...
74,328,372
74,328,460
Is there any difference between `inline constexpr bool` and `concept`
template<typename T> inline constexpr bool is_int_v1 = std::is_same_v<T, int>; template<typename T> concept is_int_v2 = std::is_same_v<T, int>; In this code block whats the difference between the inline constexpr bool format and the concept format. Is one better over the other or are they equivalent?
There are many differences. Variables are variables; even if they are inline constexpr, they are still variables. They represent objects and you can take their addresses. A concept is not a variable at all. You cannot take its address or do anything of the kind with it. concepts get special grammatical rules like void ...
74,328,526
74,328,547
Write a C++ program which will print (half pyramid) pattern of natural numbers
The task: Write a C++ program which will print (half pyramid) pattern of natural numbers. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 I have tried using this code, but its not giving the output: #include <iostream> using namespace std; int main() { int rows, i, j; cout << "Enter number of rows: "; cin >> row...
j in your inner loop is the 1 based index of the element in the current row (1,2,3 etc.). Instead of printing it, you should print a counter that is increased over all the iterations. Something like: #include <iostream> int main() { int rows, i, j; std::cout << "Enter number of rows: "; std::cin >> rows; ...
74,328,792
74,329,048
C++ reset locale to state at program start?
I crawled the web a lot and got not, what I searched for even not in SO. So I consider this a new question: How to reset the locale settings to a state when the program is starting (e.g. first after main()) ? int main( int argc, char **argv ) { // this is start output I like to have finally again std::cout << 2...
A few points to start with: calls to std::setlocale do not affect C++ iostream functions, only C functions such as printf; calls to std::locale::global only change what subsequent calls to std::locale() return (as far as I understand it), they do not directly affect iostream functions; your call to std::wcerr.imbue do...
74,329,127
74,389,104
(Clang Error) compilation error: ld: library not found for -lcrt0.o. Any ideas?
The full terminal output is as follows: >g++ -std=c++98 -static mainP1.o -o mainP1 > >ld: library not found for -lcrt0.o > >clang: error: linker command failed with exit code 1 (use -v to see invocation) > >make: *** [mainP1] Error 1 I'm on a 2020 MacBook Pro with an intel CPU using Visual Studio Code. When I write b...
The problem was my compiler path in Visual Studio Code. I changed it to clang++, and now all my code compiles and executes without any problems. How I changed it: CMD + SHIFT + P Typed in: C/C++: Edit Configurations (UI) Made sure that "Mac" was selected under configuration name. Changed Compiler Path to: /usr/bin/cla...
74,329,440
74,329,879
Divisors of a number with exactly 4 divisors
I have a number n (0 < n < 2 * 10^18), and I am given that it has exactly 4 divisors. Is there a way I could get those divisors faster than O(sqrt(n)) ? Using a classical algorithm to find divisors of a number (link) takes O(sqrt(n)) time. sqrt(2*10^18) is around 10^9 and it would take too much time. Also a number with...
Pollard's rho method is simple, and takes expected O(sqrt(sqrt(n)) time. sqrt(sqrt(1018)) is < 32000, so quite fast for numbers in that range.
74,329,448
74,329,670
Reusing of std::unique_lock instead of creating a new one
One way to use std::unique_lock is while (!m_exit || !m_queueOfTasks.empty()) { std::unique_lock<std::mutex> ul(m_mutex); std::cout << "Thread " << std::this_thread::get_id() << " is ready" << std::endl; m_cond.wait(ul, [this]() {return !m_queueOfTasks.empty(); }); std::function<void()> work(std::move(...
There is one thing that can break complex code if you use this pattern (but won't break your snippets): an exception being thrown. Consider this: // static variable, or more realistically a class member static std::unique_lock<std::mutex> ul(m_mutex, std::defer_lock); while (!m_exit || !m_queueOfTasks.empty()) { u...
74,329,729
74,329,745
How to pop all the string from stack and store them in string variable?
This code pop all the required strings from the stack. But i want to store those string elements in a final one string variable. How to do it? #include <sstream> #include <stack> #include <string> #include<iostream> using namespace std; int main() { istringstream iss("abdd hhh |post_exp| a * b / (c + d) ^ f - g |\...
You're almost good, but in the while-loop you'd like to build the string. This can be done multiple ways, what I'd recommend is: std::ostringstream oss; while (!mudassir.empty()) { oss << mudassir.top(); mudassir.pop(); } // if you'd like it in a variable, // std::string result = oss...
74,329,761
74,330,171
infinite loop while trying to insert node before a node in singly linked list
I tried to insert a node before a given node by specifying the position of the node before which I want to insert the newnode. I got the data present inside that node's position and using a while loop, compared this data with each node's data till I reached the point where I was supposed to insert the node. But when I ...
Once you find ptr1, you set preptr and ptr2 to ptr1. Then you get c = ptr2->data, which happens to be the same as ptr1->data. And you go on and check while (ptr1->data != c), which is always false. So that bottom while loop does nothing And you get to the last lines with preptr and ptr1 pointing to the same node n. No...
74,329,770
74,329,838
Searching for a number in a given array using pointers
I need to create a program that searches for a user inserted number from an array using pointers. This is my current code #include <iostream> using namespace std; void FindNumber(int *ptrArr, int size, int *ptr1) { for (int *p = ptrArr; p < ptrArr + size; ++p) { if (ptrArr[*p] == *ptr1) { cout ...
You have 2 small typos in your code. -No need to index the array with "*p" -The index need to be calculated by subtracting p from the original pointer. Please see here the fixed code: #include <iostream> using namespace std; void FindNumber(int* ptrArr, int size, int* ptr1) { for (int* p = ptrArr; p < ptrArr + siz...
74,330,197
74,330,735
c++ socket recv() not writing into buffer fully
I am using a client socket to make a HTTP call to retrieve an image. Even though the recv call receives 36791 bytes, the buffer only has 4 bytes in the response body (the BUFF_SIZE has been set to 50000 for testing purposes). I have tried to make subsequent calls to recv but 0 bytes are returned from the subsequent cal...
Issue was due to null-terminated strings as pointed out by @dewaffled, used std::string(buffer, total) as a solution to create a string that allows embedded null characters inspired by this post
74,330,204
74,331,016
How to get fstream to save to any windows desktop that opens the .exe in c++
I'm making a program for my brother that will display 50,000 proxie variations and will save them all to a .txt. How can I make it so any windows machine that uses this code will get the .txt to save to the desktop. Here's what I have: fstream file; file.open("proxies.txt", ios::out); string line; streambu...
If I get what you are asking you just need to replace "proxies.txt" with an absolute path to a file in the desktop folder. You can get the desktop directory with the Win32 call SHGetFolderPath and put the path together using the standard (C++17) file system calls if you want, as below: #include <iostream> #include <fil...
74,330,255
74,330,341
Number of divisors from prime factorization
I am given prime factorization of a number as a map: std::map<int, int> m, where key is a prime number, and value is how many times this prime number occured in product. Example: Prime factorization of 100 is 2 * 2 * 5 *5, so m[2] = 2, and m[5] = 2 My question is how can I get number of all divisors of a number given i...
Number of divisors is simply equal to product of counts of every prime plus 1. This comes from the fact that you can easily restore all divisors by having several nested loops iterating through all combinations of powers of primes. Every loop iterates through powers of single prime. Number of different iterations of ne...
74,330,356
74,330,733
Different results for overloaded templated equality comparison operator with C++20 between gcc and MSVC/clang
Consider the following implementation of equality operators, compiled with C++20 (live on godbolt): #include <optional> template <class T> struct MyOptional{ bool has_value() const { return false;} T const & operator*() const { return t; } T t{}; }; template <class T> bool operator==(MyOptional<T> const &...
The rewritten candidates are considered at the same time as the non-rewritten ones. There is only a late tie breaker in the overload resolution rules if neither candidate is better by the higher priority rules. (See [over.match.best.general]/2 for the full decision chain.) A candidate is considered better than another ...
74,330,447
74,330,597
I want to use my own random function with std::shuffle, but it is not working
I get an error when I use myRand::RandInt instead of something like default_random_engine. But I don't understand how am I supposed to implement the random_engine function. What I've done works well with std::random_shuffle, but I understand that this function was deprecated, and std::shuffle is preffered. i am trying ...
the last argument to std::shuffle must meet the requirements of UniformRandomBitGenerator. The generator should be an object not a function. For example a minimal implementation would be: struct RandInt { using result_type = int; static constexpr result_type min() { return 0; } static cons...
74,330,859
74,340,347
If I link foo.so to bar.so, do private shared library dependencies need to be found at compile time?
Using cmake language, say I create a target foo, and link it to libbar.so. libbar.so was already compiled on a different platform with a cmake PRIVATE depedency on libbaz.so. So the dependency chain is foo ----> libbar --(PRIVATE)--> libbaz Does libbaz.so need to be present on the system when I compile foo and link it ...
General linking by the compiler toolchain In general it depends on how libbaz got linked to libbar. If libbaz got statically linked when building libbar then there are no compile or runtime dependencies at build-time of foo to libbaz. This is due to the fact that statically linked code gets "copied" into the file that ...
74,330,881
74,330,937
Check if two arrays have same values(they may be with different indexes) c++
Good evening! I have a task: implement any function to sort array and then check if two arrays(the input and the output) are the same(meaning that the values are the same). Values in array are random, so there my be something like [5,2,5,5,6,-1,3,0,84305] I was thinking about checking if elements are in both arrays, th...
If the values are unique, insert all values from the first array in an std::unordered_set and remove all values from the second array from it. If your set is empty at the end, or if any removal fails, then the sets aren't "equal" as per your definition. If the values aren't unique, you'll need to use an std::unordere...
74,331,244
74,331,347
How to insert element using template
I have some doubts about my insert method. it is compiling, but with no result. I presume that it is containing some coding errors. Can you help me resolving this? Thanks in advance. private: T* elements; int capacity; int nbElements; template <class T> void TableDynamic<T>::ins...
I have written some code for you. see if its works for you. #include <iostream> using namespace std; // insert element using template template <class T> class TableDynamic { private: T *elements; int capacity; int nbElements; public: TableDynamic(int capacity) { this->capacity = capacity; ...
74,331,324
74,331,407
C++ Is it right to use constexpr in size declaration
I'm trying to make sizes declaration is it right to use constexpr #define BYTE ((size_t)1) #define KIB (constexpr BYTE * (size_t)1024) #define MIB (constexpr KIB * (size_t)1024) #define GIB (constexpr MIB * (size_t)1024)
The constexpr keyword can't be used as part of an expression. It just makes no syntactical sense in the position you are using it. constexpr is a qualifier on a declaration for a variable or function. There is no point in using a macro like this. You can declare these constants as constexpr variables: constexpr size_t ...
74,331,660
74,331,714
How does typename assignment work in C++ (typename =)?
I came across this example when looking at std::enable_if: template<class T, typename = std::enable_if_t<std::is_array<T>::value> > void destroy(T* t) { for(std::size_t i = 0; i < std::extent<T>::value; ++i) { destroy((*t)[i]); } } In template argument lists, you can put untemplated classes/structs. So the ...
The typename on the 2nd template argument indicates the argument is a type rather than a constant value. The argument has no name specified, but the = indicates it has a default type if the caller doesn't specify one. In this case, that type is the result of enable_if_t<...> (aka std::enable_if<...>::type). std::enable...
74,331,876
74,331,917
How to make a data member const after but not during construction?
Without relying on const_cast, how can one make a C++ data member const after but not during construction when there is an expensive-to-compute intermediate value that is needed to calculate multiple data members? The following minimal, complete, verifiable example further explains the question and its reason. To avoi...
One possible way could be to put a and b in a second structure, which does the expensive calculation, and then have a constant member of this structure. Perhaps something like this: class T { struct constants { int a; int b; constants(int n) { const int expensive = ... something...