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
63,489,974
63,490,040
Why can the template not be instantiated in this piece of C++ code?
As titled, why is the template instantiation in the main function wrong? I use Clang++ with flag "-std=c++2a". Did I use anything in a wrong way here? template<int, int> void f(int) { std::cout << "int"; }; template<class T> void g() { // dependent-name. f<0, T()>(0); } int main() { g<int>(); // wrong here, wh...
This instantiation: f<0, T()>(0); for T=int gives int() for the second explicit template parameter. This is basically a vexing parse, and so the argument is treated as a function type. This is not the same as an int object, which is what f expects for its template parameters. Instead, you can instantiate it like this:...
63,490,075
63,490,133
How to call Operator "" on variable
So I have defined this operator: constexpr double operator"" _deg(double deg) { return deg * M_PI / 180.0L; } So far so good. On constants I can now just write: 90.0_deg But what if we have defined a double and whant to convert it: double foo = 3.14 How do you call the operator on foo? I tried: _deg(foo) but it...
You can explicitly invoke the user-defined-literal (UDL) like this: operator""_deg(foo); Here's a demo. Note that double is not a valid argument type for a UDL. You can change it to long double instead.
63,490,284
63,490,531
wxWidgets Memory Management standard practice
I have started playing around with wxWidgets using c++. I have made a simple hello world application following along with tutorials. Out of curiosity I ran the complied program through valgrind and had the following result. ==92057== LEAK SUMMARY: ==92057== definitely lost: 91,768 bytes in 292 blocks ==92057== in...
I presume that you are doing it on Linux? All those are false positives or leaks coming from system libraries. In terms of wxWidgets you don't need to delete memory allocated for wx object. The library internally works like a smart pointer. When you create a main frame it will be deleted when the application object wil...
63,491,000
63,492,765
Using custom script files with C++ project in Visual Studio 2019
TL;DR My project uses a custom script file at runtime. My project builds fine in VS and runs on the command line. However when running in VS an error is thrown implying the file doesn't exist. Full Details My c++ project uses a custom scripting file to apply some settings at run time: these are javascript like but n...
based on @john 's comment: There is a different current working directory when running from VS and when running from the command line. When run from VS the current working directory is the project directory not the output directory. The script was in project-dir\src not the immediate project dir. Moving the script up t...
63,491,086
63,491,158
Process exits unexpectedly with the return value of 3221225477
my program exits out of the blue with the return value of 3221225477. Below is the code: #include<iostream> using namespace std; const int MAX_VALUE=-1; int main(){ int* numbers= NULL; int capacity=0; int size=0; while(true){ int number; cout<<"Enter number: "; cin>> number; ...
On this line: cout << "You inputted: " + numbers[i]; // ^ incorrect you are adding an int to a char[15]. If the int is greater than the size of the array, cout will try to print an array that lies at invalid memory, which invokes undefined behavior. This can cause the program to crash or return s...
63,491,270
63,492,049
Is it possible to compile a project with two different language standards?
I have a project which is strictly written in C++14 and I want to use it in another project which is C++17. Some of the C++14 features like Dynamic Exception Specification were removed in C++17. Is there any way to use and compile both code bases together? The project is large enough to make refactoring impractical.
This will be platform specific: It is conceivable that substantially different headers are selected according to the standard specified on the command line, etc. That said, here is an answer from Jonathan Wakely which assures you that with gcc there should be no such problem, by design, if you keep away from unstable f...
63,491,490
63,491,810
How to access protected data members of base class of its derived class by passing objects to another derive class
I have already looked up some answers to this problem and got it working, but I can't seem understand how this one answer works, can someone enlighten me what is going on in the line void show(input& obj){cout <<obj.*&output::x <<' ' <<obj.*&output::y <<endl;}. Here is the full code: #include <iostream> using namespace...
The code is legal, albeit convoluted and non-intuitive. The gist of the magic happens here: cout <<obj.*&output::x <<' ' <<obj.*&output::y <<endl; Here, &output::x denotes a pointer-to-member, namely x in the output class. This operation is permitted, since output has baseClass as it's parent and thus has access to it...
63,491,595
63,491,706
Get file size using GetFileSize reports a segv on a valid file
I have an application that scans file and collects meta data about a file. One function is to get the file size of a file. To do so, I am using the winapi function GetFileSizeEx(Handle, PLARGE_INTEGER). The parameters require a file HANDLE and a reference to a PLARGE_INTEGER aka (*LARGE_INTEGER). To get a file HANDLE i...
The type PLARGE_INTEGER is an alias for "pointer to LARGE_INTEGER". And PLARGE_INTEGER() is a default value initialization for the type "pointer to LARGE_INTEGER". And for all pointers such an initialization is a null pointer. That means the definition PLARGE_INTEGER l = PLARGE_INTEGER(); is equivalent to LARGE_INTEGE...
63,491,816
63,495,370
cargo transportation system we are not sure how to display the last part of our task
Here is our code for the task we are almost finishing just the last part we are stuck at "Fastest: 3 trips (1 Van, 3 Mini-lorry, $645) " we are not sure how to display the values in the bracket we only able to display 3 trips. Is there a way to also display the values in the bracket stated as well? we use int min = *m...
Your design is awkward; you create an instance of CTS run; and never use it. Assuming that you do your calculations right, you need to know at what index you found min. If you store the iterator returned by min_element(), you can get an index by subtracting vTrips.begin() from it. Then the corresponding elements in you...
63,492,207
63,493,468
How to change the font and color of QString?
I have a QString like this ">>> This is an Arrow." , now I want to have >>> in bold and red, How to do that ? i have looked over some pages and found this syntax QString redPart = QString("<span style=" color:#ff0000;">%1</span>").arg(">>>"); but it gives some error like ")" missing and, I am not able to figure it out...
your error message means that you are missing a ) because you have to escape the quotes when using them in a string literal (\" instead of ") i.e. do something like QString redPart = QString("<span style=\" color:#ff0000;\">%1</span>").arg(">>>"); on the other hand, Qstring is a class that has nothing to do with widg...
63,492,340
63,492,382
Tideman CS50 C++ Sort function
I have already passed the test but I don't get it. This is the correct code. void sort_pairs(void) { for (int i = 0; i < pair_count-1 ; i++) { for (int j=i+1; j<pair_count; j++) { if (preferences[pairs[i].winner][pairs[i].loser]<preferences[pairs[j].winner][pairs[j].loser]) ...
This is taking the pairs by value: void swap (pair a, pair b) // a is a copy of pairs[i] and b is a copy of pairs[j] The change you make to a and b inside the function will be discarded when the function exits. a and b are local to the function only. Take them by reference (pair&) instead and then swap the correct...
63,492,422
63,493,806
Converting Int to APInt in LLVM [C++]
im trying to build language via LLVM (because i simply must), but was stuck at the simple start. Im trying to make int constants, but: ConstantInt::get method needs APInt class APInt class has no valid convertion from regular int to itself this was my try: Value * val = ConstantInt::get(Context, APInt(m_Lexer.numVal(...
The first argument to ConstantInt::get is an llvm Type not a context. Try this Value * val = ConstantInt::get(Type::getInt32Ty(Context), m_Lexer.numVal(), true); where the last boolean argument determines if val would represent a signed or unsigned i32
63,492,505
63,493,012
How to guarantee a specific set of characters as input to a string_view parameter?
I'm working on a design implementation where I want the input to be selected from a specific set of characters for its string literal representation. Consider the following set of classes: class enum BaseType { BINARY = 2, OCTAL = 8, DECIMAL = 10, HEXADECIMAL = 16 }; template<BaseType BASE = BaseType::...
With <regex>, you might do: static const std::regex binary_regex(R"([01]*\.?[01]*)"); static const std::regex octal_regex(R"([0-7]*\.?[0-7]*)"); static const std::regex decimal_regex(R"([0-9]*\.?[0-9]*)"); static const std::regex hex_regex(R"([0-9a-fA-F]*\.?[0-9a-fA-F]*)"); bool do_match(const std::string& s, const st...
63,492,915
63,492,948
Pointer value loses scope
In the method callTest I declare a pointer to an int called testPtr. I then pass it to the method test where it is assigned. Since the pointer is no longer nullptr I can print the value. However, when I leave the scope of a::test, I see the pointer is null again. I am perplexed as to the reason why. class a { public: ...
You need to pass the pointer by reference: void a::test(const int* & intPtr) const // ^ like this otherwise you are passing it by copy, and changes made inside the function will not be visible to the caller. This is no different than when you pass an int by copy vs by reference, the behavior is ...
63,493,207
63,494,184
Finding and erasing a value from a std::vector holding std::map elements
First, I have the following two objects, both filled with data: std::vector<std::map<std::uint8_t, std::uint8_t>> x1; std::vector<std::map<std::uint8_t, std::uint8_t>> x2; My objective is to search inside x2 (by the key), checking if any value from x1 doesn't exist inside x2, and then erase it from x1. I tried with th...
You can also go a little bit functional: Playground #include <algorithm> #include <functional> // removes maps from x1, that are equal to none of x2 maps auto remove_start = std::remove_if(x1.begin(), x1.end(), [&](const auto& x1_map){ return std::none_of(x2.begin(), x2.end(), std::bind(std::equal_to(), x1_ma...
63,493,502
63,493,576
How to have operator<< for specific template instantiation std::tuple<double, int, int>?
How to create operator<< for specific std::tuple<double, int, int> template instantiation? using FST = std::tuple<double, int, int>; std::string TupleAsStr(const FST & i) { return "(" + std::to_string(std::get<0>(i)) + ", " + std::to_string(std::get<1>(i)) + ", " + std::to_string(...
You can overload operator<< for the FST type. Also, it's better to put the FST type into a namespace as well, to avoid collisions with existing overloads: namespace my { using FST = std::tuple<double, int, int>; std::ostream& operator<<(std::ostream &out, const my::FST & i) { return out << "(" << ...
63,493,577
63,493,719
In C++, what is the best way to do conversions of similar classes between libraries?
I happen to be working on a project that uses the glm and Box2D libraries. Both of these include implementations of, for example, a 2D vector. Sometimes, I'll need to convert values from one library's format to another. I can't just write the appropriate constructors in the classes because that would involve modificati...
the obvious solution is just to write some utility functions that convert one to another should I just do the boring and straightforward thing? Yes, this is a decent approach. Note that in special case of the types being layout compatible, you can simply reinterpret a pointer to one as being a pointer to the other ...
63,493,738
63,493,820
std::vector erasing with first iterator after last
What will happen when erasing a range whose first iterator is after the last iterator? std::vector<int> v{1,2}; v.erase( v.begin() + 1, v.begin() ); What about other containers?
It's undefined behavior to call erase with an invalid range on any container. In practice, it will generally crash the program if you are lucky, or smash adjacent memory if you're unlucky. This should be true for just about any API that accepts an iterator range. If a range is invalid, there is no way for the underlyin...
63,493,811
63,503,569
If statement in python working different just by changing position of condition
I just encountered a weird problem in python: below is an implemntation of the merge sort algorithm that gives me an index error if I try to run it. def mergesort(s1,s2,S): i,j = 0,0 while i+j < len(s1)+len(s2): if (i < len(s1) and s1[i] < s2[j]) or j == len(s2): S.append(s1[i]) ...
The first python program is indeed incorrect: if (i < len(s1) and s1[i] < s2[j]) or j == len(s2): will cause an out of bounds access to s2[j] if j reaches the length of s2 before i reaches the end of s1. The fix is to test for j == len(s2) before (i < len(s1) and s1[i] < s2[j]) as you correctly found out yourself. The ...
63,493,968
63,494,072
Reproducing clang's __builtin_assume for GCC
Recently, I discovered void __builtin_assume(bool) for clang, which can provide additional information about the state of the program to the compiler. This can make a huge difference, like for example: #include <cstddef> // compiles to about 80 instructions at -O3 unsigned sum(unsigned data[], size_t count) { unsi...
I've used __builtin_unreachable() which indicates that it is Undefined Behavior for control flow to reach here. You can wrap it in an if to essentially write an assertion. The condition can be any invariant that is false, so in your case you would put the opposite condition. Example : // Basically `assert(count <= 4);`...
63,494,213
63,504,910
How to install packages when cloning project that uses vcpkg
I am trying out vcpkg package manager but I am running in some issues. I have a c++ project that uses cmake and vcpkg and have used vcpkg to install the cache2 package. Now everything works but as soon as I push the project and clone it I can't find how to restore the installed packages. What I have done is this: inst...
I have found a decent solution using vcpkg manifests, it is still an experimental feature but I haven't had any issues with it yet. In order to use manifests do the following: At your root folder add a vcpkg.json file with the following contents: { "name": "projectname", // should be lowercase, uppercase will give ...
63,494,331
63,494,725
winapi - a standard way to retrieve text from running text editor
Is there a standard message that can be sent to a text editor window or a certain WinApi call, that will retrieve the contents of the currently edited text? For example, to retrieve the current contents of a Notepad window. (assumed that the most up to date text wasn't yet written to a file) I've tried retrieving the t...
In general no there is no standard message for this. But Windows' Notepad has an "Edit" child which responds to WM_GETTEXT and WM_GETTEXTLENGTH - messages normally used to retrieve text from input controls. Here's a PoC demonstrating the idea: #include <iostream> #include <vector> #include <string.h> #include <Windows....
63,494,580
63,494,838
Custom strtoull functions producing invalid results
I do not have access to anything like strtoull on my actual platform, so I need to find/handroll one. I've tried all four from this answer and they all give me the same, wrong answer, on my windows testing platform. I also tried on online compilers. One of the functions is unsigned long long strtoull_simple(const char ...
As mentioned in the comments, the code looks like it is for base-10 numbers but the number you are trying to parse looks base-16. You can add a parameter to specify the base: unsigned long long strtoull_simple(const char *s, int base) { unsigned long res = 0; while (*s) { // TODO: handle invalid chars ...
63,494,903
63,494,912
Why we can have a semicolon in if but not in while loop
Why can I do this: if (int result=getValue(); result > 100) { } but cannot do this: while (int result=getValue(); result > 100) { } Why discriminate against while? A condition is a condition. Why while cannot evaluate it like if can? In order to achieve the desired behavior with while, I'd have to implement it this t...
Because we already have a while-loop-with-initializer. It's spelled: for (int result=getValue(); result > 100;) { }
63,495,134
63,495,208
Why is extern required for forward declaration of global variables but not for functions when using them from other files in C++
From what I already know, both global non-constant variables and functions have external linkage by default. So they can be used from other files with the help of forward declaration . For example: <other.cpp> int myNum{888}; int getAnInt() { return 999; } <main.cpp> #include <iostream> extern int myNum; // "ex...
Because there is a difference between int getAnInt(); and int getAnInt() { ... } Namely the brackets themselves, and as such there is no need for a marker like extern to differentiate between the two. Particularly, the former is a declaration, which just states that getAnInt exists and returns an int etc, whereas th...
63,495,322
63,509,848
Where does an Android app search for shared .so files to load?
To make this a little more complicated I'm loading a native library I've compiled with ndk and cmake into Unity which will be deployed on Android. This was all working fine until I wanted to link another shared library to the library I was building. Now my library fails to load and I believe it is because it can't find...
The imported library may have its own dependencies, which must also be copied to your APK (or AAR). To check this, run objdump -p libusb1.so | findstr "NEEDED".
63,495,621
63,496,511
How can I replace only first found match of regex_search?
I am doing an exercise: add code for the myPrintf template function that checks the matching of parameter types and type specifications in a format string. Limit only to %d as a conversion for int, then %f as a conversion for float and %s as a conversion for const char *. Here is my code: #include <iostream> #include <...
Fixed version of your code: auto myPrintf(const std::string& x){ std::cout<< x; } template<typename T ,typename... Args> auto myPrintf(std::string x, T t, Args... args){ std::regex e("[%]."); std::smatch cm; if (std::regex_search (x,cm,e)) { if constexpr (std::is_integral_v<T> )...
63,496,083
63,504,998
std::string allocate memory 2 times for 1 string
#include <iostream> #include <string> void* operator new(size_t size) { std::cout << "Allocated: " << size << " Bytes\n"; return malloc(size); } void operator delete(void* var) { std::cout << "Deleted\n"; free(var); } int main() { std::string name0 = "Ahmed Zaki Marei"; //std::string name1 = ...
As C.M. already pointed out in the comments: this is MS STL behavior in Debug mode, smth to do with _ITERATOR_DEBUG_LEVEL. Everything is fine in Release. Was curious so I tested it myself and the stack reads this on first breakpoint in new: operator new(unsigned int size) std::_Default_allocate_traits::_Allocate(const ...
63,496,216
63,496,257
AnsiString does not work (AnsiString identifier is not defined)
Here's the code: AnsiString path = "BrowserBot.exe"; ShellExecute(0, TEXT("open"), path.c_str(), TEXT("-parametr"), 0, SW_SHOW); Writes an error that the AnsiString identifier is not defined. I don't know what the problem is. All connected libraries: #include <iostream> #include <conio.h> #include <Windows.h> #include...
AnsiString is a string class that is specific to the C++Builder compiler. If you are using that compiler, make sure you are compiling your project with C++Builder's VCL (Visual Component Library) or FMX (FireMonkey) framework enabled, and that you have a corresponding #include <vcl.h> or #include <fmx.h> statement in ...
63,496,250
63,496,315
Why cin is not getting buffer data after using getline?
To this code: #include <iostream> #include <string> #include <cstring> #include <cstdio> using namespace std; #define p(a) cout << "|" << a << "|" << endl int main() { char a[100]; char b[100]; cin.getline(a, 4, '\n'); cin >> b; p(a); p(b); return 0; } If my input is "1234" 1...
If std::istream::getline can't fit the whole line (and terminating null) into the given buffer, it sets an error flag and becomes unreadable until the error is cleared. std::istream::get's fourth overload is a better choice for this use-case as it doesn't raise a flag if the whole line is not consumed. Replace cin.getl...
63,496,270
63,496,433
Unhandled exception when copying from a std::vector to a thrust::device_vector
I encountered the following error when trying to copy data from a std::vector to a thrust::device_vector using thrust::copy: Unhandled exception at 0x00007FFD7FF43E49 in tryThrustCopy.exe: Microsoft C++ exception: thrust::system::system_error at memory location 0x0000002CB3B9C8B0. occurred I am using Windows 10 with ...
When I compile your code on CUDA 10.2, I get the following warning (truncated): .../targets/x86_64-linux/include/thrust/detail/allocator/allocator_traits.inl(97): warning: calling a __host__ function from a __host__ __device__ function is not allowed You should not ignore a warning like that any time you are doing CU...
63,496,341
63,510,482
How to return a VkPhysicalDevice from vkEnumeratePhysicalDevices
I'm following a game engine tutorial in Vulkan and came across an issue where vkEnumeratePhysicalDevices is populating my 'devices' vector with pointers to the stack. VkPhysicalDevice appears to be the typedef of a pointer, VkPhysicalDevice_T*. I get a warning on Visual Studio about this issue, and I'm wondering if the...
I get this one too. It comes from static analysis related to the newish C++ guidelines. The dispatchable handles in Vulkan are pointer-like things. The modern C++ conventions do not like raw pointers though. The static analyzer seems to incorrectly think the std:vector is tied to the lifetime of whatever is under that ...
63,496,578
63,496,774
Pop method of linked list using unique_ptr
I'm looking at the implementation of a singly linked list using unique_ptr on https://solarianprogrammer.com/2019/02/22/cpp-17-implementing-singly-linked-list-smart-pointers/. My question pertains to the following method: 3 struct List { 4 List() : head{nullptr} {}; 5 6 // ... 7 8 void pop() { 9 ...
I am wondering why the temporary is needed here? It is not really needed, but it is not bad to use, either. Why couldn't you simply do head = std::move(head->next)? Is this because it will result in a memory leak? You can. There will be no leak in this example. When head is reassigned, does unique_ptr automatical...
63,497,277
63,506,232
How to create make file for template library in c++?
I am new to makefile concept and I Having this template library how can i create makefile to install this library on system, can i create makefile for template library. Source code Folder structure(omitted some files): artlib - c++ | |--- include | | | |--- artlib.hpp | |--- source | |-...
Here's a makefile to install a file template.h into /usr/local/include: FILES := template.h DESTDIR := /usr/local/include INSTALLEDFILES := $(addprefix $(DESTDIR)/,$(FILES)) all: $(INSTALLEDFILES) $(DESTDIR)/%: % mkdir -p $(@D) cp $< $@ Since you've not given us any actual details about what you wa...
63,497,482
63,563,882
JNI - Why rt.jar System.load not working but wrapped method working?
And here is a demo (I omit utils, They just check if exception and print message): First try, It should work: C++ part: jclass jClass_java_lang_System = env->FindClass("java/lang/System"); jmethodID jMethodID_java_lang_System_load = env->GetStaticMethodID(jClass_java_lang_System, "load", "(Ljava/lang/String;)V"); env->...
When you load a native library with System.load() the VM will try to bind any JNI functions it finds to their Java counterparts, i.e. the class that declares the native methods. It can only do that when that class is already loaded. If you load the class afterwards you will have unbound native methods, and when you cal...
63,497,591
63,497,648
C++ The value is never used
I have a variable count. Every time a condition is met, I add one to it. However, it says "the value is never used." However, when I move the variable outside the for loop, it works. Is this a scope issue? for (int i = 0; i < farmers; i++) { int count = 0; int temp_work_streak; if (end_times[i] <= end_times...
The problem is indeed one of scoping. The variable count is local only inside the loop, and its life-time is only the current iteration. Each iteration there's a brand new count variable. It will not retain its value between iterations of the loop. The variable is used either in count++ or in i - count, but not both. T...
63,497,705
63,497,885
Why does compound assignment (+=) differ between languages (Java, C++)?
The definitions of += seem to be the same in both Java and C++, however, they perform differently. Consider the following code in C++: #include <iostream> int n; int f(int x) { n += x; return x; } int main() { n = 0; n = n + f(3); std::cout<<n<<" "; n = 0; n += f(3); std::cout<<n<<" "; ...
This has more to do with evaluation order than "what the compound assignment operators do", so you'll find more useful things in the "evaluation order" sections of the specs of both languages. For Java, JLS §15.7: The left-hand operand of a binary operator appears to be fully evaluated before any part of the right-han...
63,497,717
63,504,139
Overload templated class template parameters with only one class definition
Basically I am trying to create a templated class that can take either be instantiated in a user friendly way or in a more complex way offering more configurability. I want to offer these two instantiating methods WITHOUT HAVING TO DUPLICATE THE API. The class would look something along the lines of: // templates that ...
I don't think we can have template which accept type or value at the same type. As workaround, you might wrap your value in a type (std::integral_constant) (and possibly provide UDL to allow 3_c instead of std::integral_constant<int, 3>). template <char... cs> auto operator ""_c () { constexpr int n = [](){ ...
63,497,886
63,497,968
Moving a thread to another thread while both threads are in use
// threadMovedFixed.cpp #include <iostream> #include <thread> #include <utility> int main(){ std::thread t([]{std::cout << std::this_thread::get_id() << std::endl;}); std::thread t2([]{std::cout << std::this_thread::get_id() << std::endl;}); t.join(); t = std::move(t2); t.join(); std::cout <...
Please keep in mind that C++ doesn't implement all the multithreading stuff but delegates that to OS. C++ multithreading classes are just wrappers with a convenient interface that follows C++ idioms. So, there is no problem in moving a running thread to another std::thread object. Otherwise (look on it from another ang...
63,498,109
63,498,557
Pointer to the beginning of Linkedlist is changing while adding a new node to the end
I was playing with the simple Linkedlist traversal code in an iterative way. But I was getting segmentation fault. With some debugging I found that the start pointer through which I was intending to store the address of the first node was changing with each new node addition from a vector. Couldn't figure out why ? #in...
Here is the problem void ab(int data) { Node temp; temp.data = data; temp.link = NULL; ... } The Node object is created in stack, so it will be destroyed at the end of scope. You need create it in heap by new operator. void ab(int data) { Node* temp = new Node; temp->data = data; temp->link...
63,498,267
63,513,680
Best solution of matching C-style multiple line comments in flex?
I have collect a lot of solutions of matching C-style multiple line comments in flex: (1) forgot reference "/*" { BEGIN COMMENT; } <COMMENT>"*/" { BEGIN INITIAL; } <COMMENT>([^*]|\n)+|. { /* skip everything */ } <COMMENT><<EOF>> { fatal_error("unterminat...
None of the patterns given is actually correct for C or C++, because they don't take into consideration line splicing or trigraphs. (You might consider trigraphs unnecessary these days, and I wouldn't disagree, but even though they are now deprecated, you might still need to process legacy files which used them.) (This...
63,498,531
63,498,640
Where is this array value coming from?
So I'm practicing coding before classes begin again and I wanted to create a random array of 10 integers and wanted to find which two numbers, when added together, equal greater than 100. When I run the code below int arr[9]; for(int i = 0; i<=9; i++){ arr[i]=(rand()%100)+1; cout<<arr[i]<<endl; } cout<<endl; ...
I notice that the value of arr[9] is equal to one number but the program has another number for it. Counting in computers starts from 0 and ends at one number less than the total size. For int arr[9] the ninth index is arr[8] the 1st index is arr[0] the 2nd index is arr[1] When you do arr[9], you are crossing the b...
63,498,718
63,498,936
c++ variable size stack array in function that get const
I'm learning now C++ I'm reading the book Effective C++ (Scott Meyers). In the book, there is an item about const variables, and I try to work with them. I notice something very interesting that I what to know if it bug in C++: (I'm working with C++98 standard) void Test(const int i) { int arr[i] = {0}; fo...
To catch this kind of mistake in the future the compiler flag you want for both g++ and clang++ is -pedantic. And always remember to specify your language standard or you don't know what you'll get. $ g++ -std=c++98 -pedantic c++-vla.cpp -o c++-vla c++-vla.cpp: In function ‘void f(size_t)’: c++-vla.cpp:3:30: warning: I...
63,498,746
63,500,092
How can I implement downHeap() function in a min-heap?
I'm trying to write downHeap() function for a min-heap where I will check to see if a root node's child is less than the rootnode and if so, I will swap their values. The class Node is already defined for me and has a 'left' and 'right' child ptrs as well as 'value'. Below is my code so far: void downHeap(Node *n) { ...
You first need to go down in depth, then check for the condition to swap. I would do something like this: void mySwap(Node* a, Node* b) { int tmp = a->val; a->val = b->val; b->val = tmp; } void downHeap(Node* root) { node_t* tmp = NULL; if(root == NULL) return; downHeap(root->left); downH...
63,498,934
63,499,634
Why does Rccp return a list-like output when I was expecting a dataframe output in R?
I am trying to write a .cpp that takes an input vector and outputs a two-column dataframe with all possible combinations from the input vector. My output gives the desired values, but not as a dataframe. What do I change in the .cpp file to get a dataframe output? My possible_combos.cpp file looks like this: #include <...
As the other answer stated, a GenericVector is a List and you cannot create a DataFrame with List columns using the Rcpp DataFrame constructor. You can however create a List and convert it to a data.frame manually, returning it as SEXP: #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] SEXP C_all_combos(Gene...
63,499,104
73,250,259
libcurl simple C file downloader example immediately returns
I tried compiling both the examples on this question: Download file using libcurl in C/C++ Here's one of them: #include <stdio.h> #include <curl/curl.h> int main(void) { CURL *curl; FILE *fp; CURLcode res; char *url = "http://stackoverflow.com"; char outfilename[FILENAME_MAX] = "page.html"; cur...
I had the same issue and I fixed it by: curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true); According to https://curl.se/libcurl/c/CURLOPT_FOLLOWLOCATION.html, true tells the library to follow HTTP location.
63,499,169
63,499,415
error: expected unqualified-id before '.' token
10 struct element 11 { 12 int listnum; 13 char *tablename; 14 char** headl; 15 float** tabledata; 16 struct element *next; 17 }; 18 19 struct element *next = NULL; 20 struct element *start= NULL; 21 22 void add_element(char *tablenameadd, char **headladd, float **tableadd, int hcols, int ...
the statement element.headl is wrong because element is the name of the data type, and what you are trying to do in to manipulate the structure defined under the name pointer so you have to change that to: struct element *pointer; pointer->headl = new char*...
63,499,276
63,499,362
How does ADL affect this piece of C++ code?
Actually, the below code can not be compiled with Clang using this command: clang++ -std=c++11 test.cc -o test. I just want to mimic the same behavior as "swapping idiom" in C++ to use "using-directive" to enable ADL. But where am I wrong with the following code? The expected calling priority should be the: N1::foo > N...
In this case, normal name lookup finds N2::foo, and N1::foo is found by ADL, they're both added to the overload set, then overload resolution is performed and the calling is ambiguous. BTW: Without using N2::foo; in main(), ::foo will be found by normal name lookup, and N1::foo is found by ADL too; as the result the ca...
63,499,281
63,518,054
Adding project reference in VS Code for C++/CLI project
I am currently using VS Code with the C/C++ extension to develop a C++/CLI wrapper module for native code. I am having trouble adding a project reference. I know it is possible in Visual Studio. However, is it possible to add a Project Reference for a C++/CLI project in VS Code?
The solution I require should not change the Visual Studio environment. As it is used as the main build environment. The current workaround that I have done is to add the Project Referenced files as ForcedIncludes in my c_cpp_properties.json file. This solves my issue and changes nothing that will cause the Visual Stud...
63,499,436
63,500,602
How to define function from input string in python at runtime?
I was trying to solve UVA 11036. It requires defining function at runtime. For Example: I have to take input (2*x + 7) % N as a string and define a function at runtime like func = lambda x : (2*x + 7) % N to work on it. Please help me to find out how to convert string to function at runtime.
You could use exec to define a function from a string. However that allows to inject any code into your program. But as it's only for solving that challenge, it might be fine. exec 'func = lambda x : '+input
63,499,626
63,499,777
In C++11, can you declare global variables and function prototypes on the same line?
While I was writing some C++11 code: #include <bits/stdc++.h> using namespace std; int a, b, array[25]; int function(); int main() { ... (not important) out of curiosity, I put the variable declarations in the same line as the function prototype: #include <bits/stdc++.h> using namespace std; int function(), a, b, a...
The declaration says that function(x), a, b, and array[i] are all ints. (This is the "old-school reading" of types - it always works in C, but C++ broke it; int *x can be read "*x is an int", but int &x can't be read "&x is an int".) This has been fine since the early days of C (so, for half a century or so), and it's ...
63,500,537
63,500,927
Without RTTI, in C++ how can I determine at runtime if an object in a collection implements an interface
I have a collection of objects that share a common base class, but additionally some of them implement one or more interfaces. When iterating over them, I want to be able to run the methods of these interfaces only if the object is of a class that implements them. Let's say I have something like this: include <iostream...
One method is to expose interface conversion functions explicitly from the main interface: #include <vector> #include <iostream> struct IFlying; struct IAquatic; struct ITerrestrial; struct IMovable { virtual ~IMovable() noexcept = default; virtual IFlying* canFly() noexcept { return 0; } virtual IAquatic...
63,500,553
63,500,708
Invalid pointer calling destructor on pointer to object containing std::string
I'm using a modified verison of the ECS found on thebennybox's channel (The code for which can be found here), and it works perfectly most of the time. But, when I add an std::string to a component, the program aborts on quit (when the destructor for the ECS class gets called) with the message: free(): invalid pointer....
Your problem is in the ECSComponentFree() function where you call the destructor manually: template<typename Component> void ECSComponentFree(BaseECSComponent* comp) { Component* component = (Component*)comp; component->~Component(); //call the destructor } And when your object goes out of scope, the destructo...
63,500,588
63,502,245
Different template class realizations but same member functions
I have a template matrix class with some typical member functions such as inverse, determinant, operator*, etc.. And I want to reuse the code for these member functions in template realizations for both fixed- and dynamic size matrices. Is this possible? and if yes, how? In the code below, like Eigen, I use "-1" for dy...
This is a very generic way to do such specializations using CRTP. It doesn;t require that there is a simple single condition that can be used to select an implementation of a data member, and leave the rest unchanged. template <class T, class Impl> class MatrixBase { // data is NOT defined here Impl exp() const ...
63,500,671
63,503,465
Shouldn't `randperm` in the PyTorch C++ API return a tensor with default type int?
When I try to generate a list of permuted integer indices with randperm using the C++ PyTorch API, the resulting tensor has the element type of CPUFloatType{10} instead of an integer type: int N_SAMPLES = 10; torch::Tensor shuffled_indices = torch::randperm(N_SAMPLES); cout << shuffled_indices << endl; ...
That's because the default type of any tensor that you create with torch is always float. If you want otherwise, you have to specify it with the TensorOptions parameter struct : int N_SAMPLES = 10; torch::Tensor shuffled_indices = torch::randperm(N_SAMPLES, torch::TensorOptions().dtype(at::kLong)); cout ...
63,500,919
63,501,887
How address of a function will pass to the std::thread
I was debugging a multithreaded application that is using std::thread to run a function. I reach to the following code when debugging. extern "C" uintptr_t __cdecl _beginthreadex( void* const security_descriptor, unsigned int const stack_size, _beginthreadex_proc_type const pr...
The code shown (_beginthreadex function) is part of VC++ CRT (can be found in, e.g. C:\Program Files (x86)\Windows Kits\10\Source\10.0.17763.0\ucrt\startup\thread.cpp). An instance of unique_thread_parameter is a structure that holds the thread procedure pointer, the context argument, and thread and module HANDLEs: // ...
63,500,955
63,501,086
How to iterate std::set based on offset from set.begin()?
I need to get an iterator based on offset. i.e. having the iterator for begin : auto it = set.begin() I need to get to the iterator having offset ofst: it + ofst Is there a way to do that? of I need incremental increase it++ the iterator ofst times.
I need to get to the iterator having offset ofst: it + ofst: is there a way to do that? No, there is no operator+ overload defined for this for std::set::iterator (aka bidirectional iterators). However, you can use std::next, from <iterator> header as follows to achive the same. #include <iterator> // std::next au...
63,501,587
63,505,165
How can I communicate back the result from a std::thread to the Gui main thread in Qt?
In order to learn about threading in Qt and C++ I am creating a small example program. It has a Gui with a button and a text field: When the user presses the Calculate button it calculates pi using a sum formula. In order for the Gui to be responsive during this lengthy operation the calculation will be performed in a...
Add a signal to your instance of StdThreadStrategy, and connect that via an explicitly deferred connection to the handler living in the UI thread. That way, you can safely call the signal from any thread, Qt takes care of sending it where it should go. Also don't forget to join() your thread in the destructor of StdThr...
63,501,664
63,502,919
Current UTC time point in C++
I want to send a time point over a network connection to detect the ping time and for other calculations. The time has to have millisecond precision, but using: auto currently = std::chrono::time_point_cast<std::chrono::milliseconds>( std::chrono::system_clock::now() ); ... returns (of course) the system time whic...
std::chrono::utc_clock exists in the C++20 standard but neither clang nor GCC have implemented it in their standard libraries yet. This is quite common for the latest language standard. Not all features are implemented by all compilers yet. However, since C++20, std::chrono::system_clock has a specified epoch, namely 1...
63,502,237
63,513,951
What is the fastest SHA1 implementation?
I am looking for the fastest SHA1 implementation since I have to compute it millions of times. I tried boost::uuids::detail::sha1 and OpenSSL SHA1 and I find OpenSSL 2.5 times faster than boost. I also checked Crypto++ which is much slower than the other two. Here is what I do to check their performances: OpenSSL SHA1:...
My last experiments confirmed openssl's was fastest among several (including Crypto++ and some lose single-source C implementations that I forgot which ones) Re: the code-review type parts of the question: the boost "implementation" is from a detail namespace and should not be relied on. The CryptoPP take might benef...
63,502,239
63,502,447
Forward declaration within a class (not a nested class)
I came across this odd forward declaration (or something) where instead of having a normal: class A; class B{ A* var; } You can do class B{ class A* var; } Now this might be an elaborated type specifier, but I'm not sure about that. I've tried it myself and I had no issues, even made my code a lot more cleaner...
Now this might be an elaborated type specifier, but I'm not sure about that. It is. In fact, class A; is a declaration to uses an elaborate class specifier. but I'm afraid it may cause scoping issues that I'm currently unaware of The only scoping related point you should be aware of is that if the elaborate type sp...
63,502,473
63,504,086
Different output from Libtorch C++ and pytorch
I'm using the same traced model in pytorch and libtorch but I'm getting different outputs. Python Code: import cv2 import numpy as np import torch import torchvision from torchvision import transforms as trans # device for pytorch device = torch.device('cuda:0') torch.set_default_tensor_type('torch.cuda.FloatTensor...
before the final normalization, you need to scale your input to the range 0-1 and then carry on the normalization you are doing. convert to float and then divide by 255 should get you there. Here is the snippet I wrote, there might be some syntaax errors, that should be visible. Try this : #include <iostream> #include ...
63,502,782
63,506,393
C++ current system time in nanoseconds as long integer in order to send influxdb
I need to get system time in nanoseconds and send it to influxdb as a timestamp. I know std::chrono::high_resolution_clock::now() gives current system time in nanosecodns but I could not manage to convert it to primitive types. When I pass the code below, I see something like 1970-01-09T... in the database std::chrono...
You need to use std::chrono::system_clock instead of high_resolution_clock. Only system_clock reliably measures time since the 1970 epoch (which is what influxdb will be expecting). Secondly, system_clock isn't guaranteed to measure time in units of nanoseconds, but you can correct for that. Here is how to get your pl...
63,502,979
63,503,349
Armadillo eigs_sym(A,k) for complex sparse matrix A
To find the 10 smallest eigenvalue of a sparse matrix 'A', the minimal code below works well: g++ -std=c++17 -o test_sparse.o -c test_sparse.cpp g++ -std=c++17 -o myapp test_sparse.o -larmadillo -larpack #include <armadillo> #include <iostream> int main(){ arma::SpMat<double> A = arma::sprandu(100,100,0.1) ; ...
It is an inherent limitation of the library. According to the documentation (emphasis mine): eigs_sym limited number of eigenvalues & eigenvectors of sparse symmetric real matrix eigs_gen limited number of eigenvalues & eigenvectors of sparse general square matrix You should rather use eigs_gen which allows...
63,503,238
63,503,292
Why doesn't Visual Studio display the print out function?
I'm learning C++ online and working with Visual Studio Community 2019 (version 16.7.2). Sometimes it displays errors or weird results despite using the exact same code as the one the tutor used. Take the code below for instance. It should print out to the console but it doesn't. Instead, it shows an empty console when ...
Because you are only "mentioning" it here printSomething;. To actually call it try the appropriate operator () as in printSomething();.
63,503,371
63,503,436
Space complexity of str.substr() in C++
What is the space complexity of the str.substr() function and how does it compare to str.erase()? Wondering because I was running a code on leetcode, and used 150MB of memory when I used the substr function: num = num.substr(1,num.size()); As soon as I removed this function and instead used the erase function, while ...
num = num.substr(1,num.size()); substr creates a copy of string without the first character, so out of the 1 character less after the call you have (almost) two times the initial string (1) the string are shared, so after the assignment the initial string is deleted if it is not referenced from elsewhere, but before...
63,504,182
63,508,449
How to create real-time etw consumer for TraceLogging provider(kernel)?
I'm trying to create the real-time consumer for the TraceLogging provider which declared in driver: TRACELOGGING_DECLARE_PROVIDER(g_etwProvider); TRACELOGGING_DEFINE_PROVIDER(g_etwProvider, "TraceLoggingProvider", (/*my guid*/)); User-mode provider: EVENT_TRACE_LOGFILEA etwTraceSettings{}; char loggerName[]{"Trac...
You must create ETW session before OpenTrace by StartTrace and EnableTrace functions.
63,504,311
63,507,008
What does the GetWindowLong(hwnd, 0) mean?
LRESULT WINAPI TextViewWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { TextView* ptv = (TextView*)GetWindowLong(hwnd, 0); switch (msg) { case WM_NCCREATE: if ((ptv = new TextView(hwnd)) == nullptr) return FALSE; SetWindowLong(hwnd, 0, (LONG)ptv); re...
Per the GetWindowLong() documentation: nIndex Type: int The zero-based offset to the value to be retrieved. Valid values are in the range zero through the number of bytes of extra window memory, minus four; for example, if you specified 12 or more bytes of extra memory, a value of 8 would be an index to the third 32-b...
63,504,705
73,513,834
In protocol buffers how to `placement new` inside an arena?
Basically any object can be created on an arena with google::protobuf::Arena::Create. How is it possible to allocate another object in place of an already allocated one? I tried the following: class My_stuff{}; int main(){ google::protobuf::Arena arena; My_stuff* ptr = google::protobuf::Arena::Create<My_stuff>(&ar...
For Messages there is no documented way to be removed from the Arena, however Swap() makes it possible to Replace one message with another. For RepeatedFields inside a message according to the docs: The following methods are added or have some special behavior when arena allocation is enabled. Otherwise, accessor meth...
63,505,272
63,505,534
Can't load Image source in QML Image on Raspberry Pi
I'm cross compiling a Qt project using Qt Creator and I'm getting the following error: qrc:/main.qml:26:25: QML Image: Cannot open: qrc:/images/imgA.png The directory structure on target device is: . └── ProjectA/ └── bin/ └── res/ └── images/ ├── imgA.png └── im...
Here is a code snipped for you. qml.qrc <RCC> <qresource prefix="/"> <file>main.qml</file> </qresource> <qresource prefix="/images"> <file alias="logo.jpg">images/logo.jpg</file> </qresource> </RCC> And here is a main.qml import QtQuick 2.14 import QtQuick.Window 2.14 Window { visible: tru...
63,505,426
63,505,819
Variable vector size in all class instantiations in c++
I'm trying to code a chess game for usage in terminal. A game consists of a Board class, consisting of Piece classes. For each piece I want to determine the allowed moves if no other pieces where on the board and put this in a vector<pair<int,int>> (a1 = 1,1). You can image that for a Queen you have more allowed moves ...
for (int i=0; i<sizeof(permMoves)/sizeof(permMoves[0]); i++) This line is incorrect. The number of entries in a std::vector is given by the size() member function: for (size_t i=0; i<permMoves.size(); i++){ cout << permMoves[i].first << ", " << permMoves[i].second << endl; } What you are doing is assuming that std:...
63,505,474
63,506,782
glClearColor is ignored
I am trying to set the background color to blue, but glClearColor is completely ignored. Code: glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(640, 480, "3D Shooter", NULL, NULL); glClearColor(0.5f, 0.5f, 1.0f, 1.0f); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_B...
You seem to be missing a glfwMakeContextCurrent(window); https://www.glfw.org/docs/3.3/quick.html
63,505,838
63,524,996
How to get surf2Dwrite to correctly compile in C++ CUDA
Ignore this question - the code is fine - the problem was with use of C++ header files which are not included in the example shared. I am using Visual studio 2019 with CUDA 11.0 and I have hit a brick wall trying to use a cudaSurfaceObject_t to store the results of a calculation. I recieve the following compiler errors...
The problem arises because I had mangled my header files. I haven't fixed everything yet, but in the process of moving my code into the simpleSurfaceWrite.cu file (as mentioned in the comments) I had to add a header file - at this point I started getting the listed errors again - this time occuring in the simpleSurface...
63,505,867
63,506,055
My SDL_Rect struct gives me errors C3927, C3484, C3613, C3646, C2059 and C2238 when adding members
I am new to SDL and I obviously face difficulties, but I was able to solve them after some research. But this is a different one that I can't solve myself. It may seem stupid, but I have really no idea what could be wrong. I am trying to make a SDL_Rect struct for one of my images that I will hopefully render on the sc...
Write a constructor for your class. class GeneralStuff { public: GeneralStuff() { steve.x = 300; steve.y = 150; steve.w = 445; steve.h = 741; } bool quit; SDL_Renderer* renderer = NULL; // steve is 445 x 741, with no good LCM, in case you forget future me SD...
63,506,161
63,518,341
Do I need an aligned memory storage to load a file?
I need to pass a font that is loaded to the memory from a file with fstream into a FT library function. It needs to be the base char pointer. Now after some reading I am in doubt whether I need to allocate actually aligned memory storage to load the file. I think when a font file is created, it has data of different ty...
After further investigation I've found that I don't need to do aligning explicitly. From the standard about allocation functions [basic.stc.dynamic.allocation]: The pointer returned shall be suitably aligned so that it can be converted to a pointer to any suitable complete object type.. From cppreference.com about st...
63,507,252
64,132,403
Using MATLAB API in C++, matOpen crashing program silently
my problem is similar to this one but it is rather old and I cannot comment or upvote due to my (beginners) reputation. I am trying to compile the matcreat.cpp file from Matlab 2017b like this (using g++ (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0): g++ -c -o matcreat.o -I"C:\Program Files\MATLAB\R2017b\e...
After some time trying to work around the internals of the mex building process I gave up on that route. Mathworks is deliberately trying to make it hard to incorporate their features into your own code. For everyone with the same problems: After some research I found this open source project, which can write MAT files...
63,507,674
63,510,949
Is lambdification of a concept an improvement or bad practice?
It appears that you can put lambda in the concept and then write code in it. Let us take this as an example. I'll prefer the standard concepts for such concepts and bear in mind that this is only for purposes of this example - godbolt template<class T> concept labdified_concept = requires { [](){ ...
This shouldn't be valid. The point of allowed lambdas into unevaluated contexts wasn't to suddenly allow SFINAE on statements. We do have some wording in [temp.deduct]/9 that makes this clear: A lambda-expression appearing in a function type or a template parameter is not considered part of the immediate context for t...
63,508,512
63,508,548
How can I use a bitset on the heap in C++?
If i use a bitset on the stack i can do the following: std::bitset<8> bset_s; bset_s.flip(1); std::cout << "Bitset on stack: " << bset_s << std::endl; std::cout << "Element 1: " << bset_s[1] << std::endl; Output: Bitset on stack: 00000010 Element 1: 1 But when I try to allocate the bitset on the heap: std::bitset<8>...
bset[1] is equivalent to *(bset + 1) as bset is a pointer. This is dereferencing memory that you don't own, so the behaviour of the program is undefined. You need (*bset)[1].
63,508,517
63,511,603
OpenCV CUDA Laplacian Filter on 3 channel image
I am wanting to apply a laplacian filter onto an image using OpenCV's CUDA (current version 4.3.0) namespace. Currently the CUDA version of laplacian filter does not accept 3 channel images: https://docs.opencv.org/4.3.0/dc/d66/group__cudafilters.html#gabf85fe61958bb21e93211a6fcc7c5c3b My thought on this was to split t...
It was a simple fix for a simple mistake :) Needed to allocate channels and lines: std::vector <cv::cuda::GpuMat> channels(3), lines(3);
63,508,710
63,509,703
Error while creating variadic class in C++
I am trying to create a class that when provided with a list of pairs of iterator begin and ends generates a sequence of vectors that give the cartesian product of the elements in the input vectors. The code works when 2 pairs of iterators are given to the initializer of the class. However, when another pair is added, ...
Here's a workup of 1201ProgramAlarm's answer (reduced to a minimal reproducible example). I couldn't find a way to deduce Product's template parameter. #include <iostream> #include <iterator> #include <vector> template <typename InputIterator> class Product{ InputIterator base, end,curr; Product* next = nullp...
63,508,731
63,508,813
What is meant by locality of declaration?
I was reading a book and here, a program is given like this - #include<fstream> #include<string> #include<vector> int main() { string filename; // #1 cout << "Please enter name of file to open : "; cin >> filename; if(filename.empty()) { cerr << "Something..."; } ifstream inFile(f...
the declaration statements occur within the locality of the first use of defined objects. Is another way to say don't declare a thing until you need it. By doing so you bring the declaration to where the object is used and doing so makes it easier to know what that object is. Imagine you have a function that is 1000...
63,508,971
63,509,020
assigning value to a double dimensional vector
vector<vector<int>> queue_and_stack(vector<int> A, int n) { // Write your code here int i, j, k; j = 0; k = 0; vector<vector<int>> myVector; int chec; for (i = 0; i < n; i++) { chec = prime(A[i]); if (chec == 1) { myVector[0][j] = A[i]; j+...
After vector<vector<int> > myVector;, myVector has no elements, so you have to add elements. Try this: vector<vector<int> > queue_and_stack (vector<int> A,int n) { // Write your code here int i; vector<vector<int> > myVector(2); // allocate 2 empty vectors int chec; for(i=0;i<n;i++) { c...
63,508,978
63,509,122
Simple multiple directories CMake
I just would like to create my CMakeLists.txt like this, but the CMake guide is not that user friendly for beginners, I have already researched too much, do not downvote, please. I have seen some solutions including in the add_executable() every source file manually, but I would like to make it more generic. Also, I w...
add_library( Headers H1.h H2.h does not add a include directory to search path. It only adds the headers to sources - and because headers are not compiled, it effectively does nothing. You can do that with target_include_directories. Because cmake doesn't know if these are C or C++ headers, it cannot determ...
63,509,124
63,509,218
C++ `for` loops iterate only once when it should be multiple
I'm trying to go a brute-force route in C++ to solve LeetCode's apparently most popular problem, the "Two Sum" problem, as described at the 0:32 marker in this video: https://youtu.be/KLlXCFG5TnA?t=32. Essentially, I need to iterate through each possible combination of 2-digit sums in the vector until I reach some desi...
The vector vect passed to the function as an argument vector<int> vect{3, 2, 4}; has three elements. So within the function the outer loop for (int i = 0; i < nums.size() - 2; i++) { has only one iteration due to the condition i < nums.size() - 2 that is equivalent to i < 3 - 2 Pay attention to that you shall not u...
63,509,161
65,530,243
How to use QML_ELEMENT with cmake
The doc shows I can use QML_ELEMENT macro to create QML types from C++ by adding some variables in qmake's .pro file. But I'm using cmake
Update (Qt 6.2+) As of Qt 6.2, qt_add_qml_module is a single command for building qml modules that should take care of virtually everything, replacing amongst others the old qt6_qml_type_registration command. Old answer (Qt 6.0/6.1) Now that Qt 6.0 is out this is supported, albeit poorly documented. What you need now i...
63,509,743
63,509,859
Program going on without stopping forever in C++
i am just a beginner and i am trying to learn C++ as my first language. It has been just 2-3 days since i have started learning it so i am truly a novice in this field and that is the reason why this maybe sound a little bit stupid question to you. So, I am still learning the commands in C++ and while trying to learn m...
istream::operator>> will set failbit when what is inputted is invalid. failbit will prevent it from accepting new input. Typically integers larger than 10 digits is considered as invalid because int (32-bit long) can store numbers only upto 2,147,483,647. To overcome this, you can use basic_ios::clear to reset the fail...
63,510,129
63,510,396
How can I reinitiate a singleton?
I know this might sound strange but I would like to reinitiate a singleton to set all its variables back to default. I have the following singleton class: class Singleton { public: static Singleton &getInstance(){ static Singleton instance; return instance; } Singleto...
If you just default the move-assignment operator, but make it private: class Singleton { Singleton &operator=(Singleton &&) = default; public: // ... }; you can write: static void clearSingleton() { getInstance() = Singleton{}; } Here's a demo. You can do this for all the special member function...
63,510,793
63,511,262
Import a text file to std::string at complie time
Google is full of C-ish answers. I'm looking for std::string way to accomplish this task
Google is full of C-ish answers. Those answers will work in C++ as well. C++ doesn't have features that would make this easier... yet 1. An overview of options that are available: Copy the content into a compiled object file. This is not portable across language implementations. May be achieved with a tool such as o...
63,511,281
63,511,521
Ending an input stream with a specified character, such as '|'?
Currently learning C++, newbie. I have an issue when ending the input with the '|' character, my program skips to the end/ends and does not allow for further input. I believe it is because std::cin is in an error state due to inputting a char when expecting an int, so i have tried to use std::cin.clear() and std::cin.i...
When the use enters a "|" (or anything that is not an int), the loop ends and the error handling that is inside the loop does not execute. Just move the error code to outside the loop. Also, you read from stdin twice which will skip every other int. while (std::cin >> input) { numbers.push_back(input); } std::cin.c...
63,511,627
63,511,628
How can I stringify a fraction with N decimals in C++
I want to stringify a fraction of unsigned integers in C++ with variable precision. So 1/3 would be printed as 0.33 using a precision of 2. I know that float and std::ostream::precision could be used for a quick and dirty solution: std::string stringifyFraction(unsigned numerator, unsigned...
It's always possible to just perform long division to stringify digit-by-digit. Note that the result consists of an integral part and a fractional part. We can get the integral part by simply dividing using the / operator and calling std::to_string. For the rest, we need the following function: #include <string> std::...
63,511,894
63,512,031
A Tree structure of base and derived class objects in C++
I have two classes class Base { explicit Base(); virtual void update(); } class Derived : Base { std::shared_ptr<Base> left, right; explicit Derived(std::shared_ptr<Base> left, std::shared_ptr<Base>); virtual void update() override; void special_update(); } I can create a Derived object from tw...
Assuming you intend Derived to be a class publicly derived from Base, you are looking for std::static_pointer_cast which can convert a std::shared_ptr of one type to a std::shared_ptr of another type: Derived(std::shared_ptr<Derived> left, std::shared_ptr<Derived> right) : Derived( std::static_pointer_cast<Base...
63,511,930
63,512,066
Does using compre_exchange with c++20 compare the value representations? (why doesn't this example agree)
From this link Atomically compares the object representation (until C++20)value representation (since C++20) of *this with that of expected, and if those are bitwise-equal, replaces the former with desired (performs read-modify-write operation). Otherwise, loads the actual value stored in *this into expected (performs...
This change (to use value representation instead of object representation) was done as part of P0528R3 (the motivation and story can be found in P0528R0). As you can see under cppreference's compiler support, neither gcc nor clang implement this feature yet. MSVC does on 19.28, but that's not available on compiler expl...
63,512,258
63,512,259
How can I print a human-readable file size in C++ without a loop
I want to print a file size in C++. My input is in bytes and I want to print it in KiB if it gets over 1024, in MiB if it gets over 1024*1024, etc. Alternatively it should print in KB for 1000 and above, and so on. It should also have a fractional part so that I can distinguish between 1.5 GiB and 1.2 GiB. What I know ...
The logarithm base 1000 or 1024 can indeed be used to determine the right unit. We actually just need the integral part of the logarithm, so the part in front of the decimal point. On modern hardware, the integer logarithm can be computed in O(1), so this will be slightly faster than using a for loop to get to the righ...
63,512,609
63,513,160
FindWindow() fails, but GetLastError returns 0
Recently, I decided to improve the error processing in a little app I had made; to test my functions, I tried introducing a basic error by giving a false window name to FindWindow. The error was successfully caught, but my error function told me the last error, given by GetLastError, was 0. I tried introducing errors i...
The consensus from the comments seems to be that FindWindow simply doesn't set an error if no window is found (Though other errors do, which I tested). Personally, this seems like pretty misleading documentation, especially as other function in the windows api will set an error code if they fail to do their job, even i...
63,512,637
63,512,705
What is #pragma region in c++ and VScode?
I found out that we can hide code in VScode using #pragma region and #pragma endregion. I have two questions: How does #pragma region work? Will it affect compilation if I tried to compile the code on any other machine?
The #pragma region is specific to Visual Studio only. Using #pragma region you can specify a block of code where you can expand it and collapse it. It has no affect on compilation. Here is an example: // pragma_directives_region.cpp #pragma region Region_1 void Test() {} void Test2() {} void Test3() {} #pragma endregi...
63,512,723
63,516,083
error: redefinition of 'get_pointer'T* get_pointer(T* p) c++11
error: redefinition of 'get_pointer'T* get_pointer(T* p) I am getting the error you see in the picture. //Itemshop_manager.h #pragma once #include "stdafx.h" //error: 4th line #ifdef ENABLE_ITEMSHOP_SYSTEM class CItemShopManager : public singleton<CItemShopManager> { public: CItemShopManager(); ~CItemShopMan...
You're missing #pragma once (or include guard) from stdafx.h. Possibly stdafx.h is included - directly or indirectly - more than once from one .cpp. If however you intend to use stdafx.h as PCH, then #pragma once is not needed but stdafx.h should only be included from .cpp, not from any header.
63,513,042
63,513,103
Insert a new node in an ordered linked list in C++
I am writing some code in visual studio with c++, it's an ordered linked list but I am having a bit of trouble with the pointers. I have three different methods / functions that carry out this task. /* * insert_head: Insert a node at the beginning of the list. */ book *inserta_head(book *head, book *newNode){ newN...
Your insert function changes the head pointer. But that pointer is a copy of the head pointer you called the function with. So the head pointer outside the insert function is unchanged. That's why nothing gets added to the list. One simple fix is to make the head parameter a reference. void insert(book*& head, int code...
63,513,644
63,513,870
Initializing an array in a object in C++
I'm currently learning C++ and I created a little array-class. Problem: I can't initialize the array in the object with the constructor. What do I need to write, to initialize this member? (I'm sure that something with the syntax is wrong.) Code: ary.h: template<typename T_datatype> class ary { private: T_datatype...
The constructor you have implemented expects an int* pointer as input, but {2, 3, 4} does not decay to an int*, so no, the syntax you have shown will not work given the class you have implemented so far. If you know the exact array size at compile-time, you could do this using std::array instead: #include <array> temp...
63,513,796
64,125,420
How to support two versions of third-party libraries with different namespaces in onecodebase
I have two versions of third-party C++ libs (lib.so and header files) In one version all the classes/enums/structs are in namespace "A" In the other version, they are in namespace "B" The header and lib.so names are same across both versions How can I have the same codebase so that I can support both versions. Somethin...
Using the below code I created two wrapper .so (one with version1 lib and -DVERSION=1 and other with version2 lib and -DVERSION=2) Let's say they are wlib1.so and wlib2.so I wrapped the APIs which were in namespace A OR B (depending on what I am compiling with ) in extern "C" Eg : #define VERSION //your version extern...
63,513,984
63,514,123
Can class template constructors have a redundant template parameter list in c++20
As far as I'm aware, the following code: template<typename T> struct S { S<T>(); }; is well-formed, even though the <T> in the declaration of the constructor is redundant. However, on gcc trunk (but not on gcc10.2), with -std=c++20 this gives an error: error: expected unqualified-id before ')' token 3 | S<...
There was a change, in fact. It's documented in the compatibility section of the C++20 draft. [diff.cpp17.class] 2 Affected subclauses: [class.ctor] and [class.dtor] Change: A simple-template-id is no longer valid as the declarator-id of a constructor or destructor. Rationale: Remove potentially error-prone option for...