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
65,124,148
65,129,911
Why do I need to assign false to each element in BFS but not in DFS
Function definitions are : // DFS algorithm void Graph::DFS(int current) { visited[current] = true; cout<<current << " "; for (int u : adjLists[current]) if (!visited[u]) DFS(u); } // BFS algorithm void Graph::BFS(void){ for(int i=0;i<numVertices;++i) visi...
The visited array never got initialised to fasle before calling the DFS() and that is why the output for the DFS() is only single node (starting node), i.e., 2. Output for the entire code (without initialising visited array to false): DFS 2 BFS 0 2 1 3 SUGGESTION: Define a function init() function and call it be...
65,124,262
65,135,507
How to get live variable updates on a statusbar in C++ with Qt's signals and slots?
I am using a proprietary driver API in my C++ / Qt application. There is an object named "status" which is essentially an integer value, that can be used to monitor errors. A value of 0 indicates all is fine, a negative value is a specific error. I would like to program a statusbar (using Qt's QStatusBar) which will gi...
Cause The statusChanged signal suffers from an unperceived existence. In other words, the driver object screams - STATUS CHAAAAAAANGED!!!!, but no one hears it. Here is why. Your code is executed in the following order: driver = new DriverInterfaceClass(this); Then, as part of the constructor: setStatus(McOpenDriver(N...
65,124,761
65,180,503
Constructing (but not destucting) an object of a class with a deleted or non-user-provided private destructor
Is the following snippet of code well-formed? struct A { ~A() = delete; }; A *pa{new A{}}; class B { ~B() = default; }; B *pb{new B{}}; At a first glace it would seems as if the deleted dtor of A and the private explicitly-defaulted dtor of B are never used (intentional memory leak, if you will), which would arguably...
The snippets are well-formed; this is a GCC bug (59238) To begin with, [class.dtor]/4 explicitly mentions that the selected destructor for a given class may be deleted: At the end of the definition of a class, overload resolution is performed among the prospective destructors declared in that class with an empty argum...
65,125,201
65,125,564
C++ Problem when trying to set bernoulli distribution as an output for function
I need my program to simulate bernoulli (p) random variables with ability to change p. If i write smth like this #include <random> #include <iostream> #include <chrono> int main() { double prob = 0.1; //let it be const for now, no need to change it in this example std::mt19937 gen(std::chrono::steady_clock::now().time_...
You should not create a new random number generator for every roll, that breaks the whole pseudo-randomness. Create a global(-ish) generator and reuse it in every function call: bool coin_flip(int switcher) { static std::mt19937 gen(std::chrono::steady_clock::now().time_since_epoch().count()); switch(switcher)...
65,125,302
65,125,754
Can you use all the ESP32's GPIO pins when the WiFi is working?
I have a weird phenomenon that when I add the WiFi library and all the settings, 2 out of 3 sensors stop working. When I remove the WiFi code it works like it used to. I have an ESP32 devkit v1 board and connected 3 sensors which are a photoresistor (ky-018), a dht-11, and a capacitive soil moisture sensor. dht-11 is ...
The problem is probably that, according to this comment on this issue on GitHub: ADC2 pins can not be used when WiFi is used. On the other hand, ADC1 pins can be used even when WiFi is enabled. This is probably because the ADC2 is used by the WiFi firmware running on the core that has the ADC2 peripheral. This doesn'...
65,125,377
65,125,867
How to extract multiple numbers from a string with numbers of variable length
We have a string which consists of "RESERVE number1,number2,number3,number4" , where number1,number2,number3 and number4 can be any number from 0 to 10, without decimal point. The string's format cannot be changed, and we want to extract each of those numbers into their respective int variables. We have tried, so far, ...
Use sscanf. Example: int num1, num2, num3, num4; std::string s = "RESERVE 11,22,33,44"; sscanf(s.c_str(), "RESERVE %d,%d,%d,%d", &num1, &num2, &num3, &num4);
65,126,110
65,128,924
Segmentation fault caused by SIMD gather?
My project uses SIMD gather for accelerating table lookup. The following is a simplified version, but enough for stating the issue I encountered. #include <x86intrin.h> #include <stdio.h> alignas(32) static int a[256][8] = { 0 }; int main(){ // initialize 32 bytes (as a __m256i) int *s = (int*)_mm_malloc(32, ...
_mm_malloc (size_t size, size_t align) - you're only aligning by 4, then doing an alignment-required dereference of a __m256i*. Presumably that segfaults when _mm_malloc(32, 4) happens to return memory that isn't aligned by 32. Just use _mm256_set_epi32(7,6,5,4,3,2,1,0); like a normal person, or alignas(32) a local ar...
65,126,217
65,126,379
How can I access val1 and val2 in int main?
I have tried using scope resolution with main and get() but it seems like I am not doing anything here right. #include <iostream> using namespace std; class base { public: float val1, val2; void get() { cout << "Enter two values..." << endl, cin >> val1 >> val2; } friend float mean(base ob); }; float mean(ba...
First you need to make val1 and val2 accessible from outside the class: ... class base { public: float val1, val2; public: ... Then you need to specify that you want to access val1 and val2 that belong to object obj: cout<<"Mean of "<<obj.val1<<" and "<<obj.val2<<" is: "<<mean(obj); You can also make ...
65,126,907
65,177,306
Change cuda::GpuMat values through custom kernel
I am using a kernel to "loop" over a live camera stream to highlight specific color regions. These can not always be reconstructed with some cv::thresholds, therefor I am using a kernel. The current kernel is as following: __global__ void customkernel(unsigned char* input, unsigned char* output, int width, int height, ...
As mentioned by @sgarizvi in the comments the cv::cuda::GpuMat already resides in the Gpu, so I had to use cudaMemcpyDeviceToDevice instead of cudaMemcpyHostToDevice. It was also not necessary to allocate new memory, which was achieved deleting the cudaMalloc and cudaFree parts of the code above. At last (just in this ...
65,127,583
65,251,612
Run Python from C++ on Android using NDK
I want to run some Python code from Android through JNI using NDK like this: #include <jni.h> #include <string> #include <stdio.h> #include <Python.h> extern "C" JNIEXPORT jstring JNICALL Java_com_example_mypythonapplication_MainActivity_stringFromJNI( JNIEnv* env, jobject /* this */) { std::strin...
Compile Python for Android with: β”Œβ”€[19:20:55]─[jacob@jacob-pc]─[~] └──> export ANDROID_NDK_ROOT=/path/to/android-ndk β”Œβ”€[19:20:55]─[jacob@jacob-pc]─[~] └──> ./configure CC=$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin/aarch64-linux-android21-clang CXX=$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x8...
65,127,723
65,151,955
How to run functions in different QThreads
How can I run loop functions in different QThreads? I need to run in different threads because if I don't do it, the loops break. How to make the on_pushTurnOn_clicked be executed in other thread, and the loop that pushTurnOn must be able to be canceled by on_pushTurnOff_clicked even on a different thread. MainWindow ....
I will start with a side note. Your memory allocation for timerLoop in on_pushTurnOn_clicked() will cause a memory leak due to absence of deallocation, even though it is a single shot timer. You are creating a new QTimer without destroying the previous allocated one. The better approach is to just allocate memory once ...
65,127,785
65,127,823
Time complexity of std::find() in std::unordered_set or std::unordered_map with no collisions
I know unordered_map has O(1) lookups but std::find() is a searching algorithm(I guess) in other containers.So is it O(1) or O(n) considering there is no collision.
From cppreference for std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::find: Complexity Constant on average, worst case linear in the size of the container.
65,127,821
65,127,970
C++ Find/Substring Bug
I made a c++ string, which would separate into substrings using the find and substring commands, and I keep having the issue where the substrings are more than instructed. They are supposed to be sentences with no numbers. #include <iostream> #include <algorithm> #include <string.h> using namespace std; int main() { ...
The second parameter of substr is a length, not an index - the string class is ancient and has a somewhat surprising interface. (I have lost count of how many times I've got this wrong.) You want string q1 = questions.substr(q1in, q2in - qin1); and so on. You can also strip off the "tag" directly, string q1 = question...
65,127,825
65,148,529
One can call a base class function from a derived class function with the same name. But I can't find a quote from the Standard supporting this
Consider the following snippet: struct Base{ void f() {} }; struct Derived: public Base{ void f() { Base::f(); } }; Derived d; int main(){ d.f(); } The snippet works fine. i.e., d.f() calls Base::f(). But I can't find a quote from the standard supporting this.
All standard references below refer to N4659: March 2017 post-Kona working draft/C++17 DIS. This is [class.qual]/1 [extract, emphasis mine]: If the nested-name-specifier of a qualified-id nominates a class, the name specified after the nested-name-specifier is looked up in the scope of the class [...] In your exampl...
65,127,842
65,128,438
Accessing MultiDim Array gives Seg Fault C++
I am doing a practise problem in which I have to find Number of K-primes(Numbers having K distinct prime factors) between two given integers. I have coded the solution however I am getting a segmentation fault, I have pinpointed the location where I am getting Seg Fault table[prime_factor_nos[i]][i]++; I have created ...
For 30030 and some more values, it has prime_factor_nos[30030] = 6, That's why it is causing a runtime error.
65,127,936
65,128,897
Defining a c++20 concept for hash functions
The CppCoreGuidelines state that concepts should be specified for all template arguments. (see:T.10: Specify concepts for all template arguments) As practice for defining concepts, I am trying to build a hashtable with concepts defined for the Hash function and Key template arguments. I want my hashtable to use two tem...
Does this list appear complete? The list is missing arguably the single most important criteria for a hash function: that if a == b then h(a) == h(b). The 4th criterion on the list is something you want for good hash functions, and is itself somewhat incomplete - you don't just want the likelihood of collision to be ...
65,128,112
65,128,186
friend function using template classes c++
I made a class which has a friend function and when I declare it there are no problems but, when I write its code it returns me the error: "Out-of-line definition of 'change' does not match any declaration in 'MyClass '". Here's the code template <class T> class MyClass { private: T a; public: MyClass(T); ...
friend void change(MyClass); does not declare a member function of MyClass, it is an instruction for the compiler to grant the free functionΒΉ void change(MyClass); access to private/protected members of MyClass. The free function you grant access to MyClass would then have to look that way: template <class S> void chan...
65,128,125
65,128,296
Q: Template specialization with parameter pack
I'll get right to the question. We have template specialization: class TestClass { public: template<typename T> static T fn(const T& a); } // OK template<typename T> T TestClass::fn(const T& a) { // ... magic for any type here ... } // OK template<> int TestClass::fn(const int& a) { // ... magic for int...
In your first example template<> int TestClass::fn(const int& a) { /* ... */ } you have a full specialization, that is permitted for C++ template functions/methods But, given the declaration template<typename T, typename... Args> static T fn(const T& a, Args&& ...b); your second example template<typename... Args> int...
65,128,177
65,128,294
Replace for loop with std::find_if and a lambda
Consider this code: int i{ -1 }; for(i=0; i<size; ++i) if (predicate(i)) break; bool found{ i < size }; This should be simple to replace with std::find_if, but it needs an iterator on integers in the range of 0 to size-1. (The equivalent of C#'s IEnumerable Enumerable.Range(0, size-1).)
Since you tagged your question with boost tag, I assume boost::irange along with boost::find_if will do the work: boost::find_if(boost::irange(0, size - 1), predicate);
65,128,286
65,128,467
I have a question about 'push_back()' with reverse_iterator
#include<string> #include<iterator> #include<vector> #include<iostream> int main(){ std::string str = "abc"; std::string str2 = str; std::vector<int>::reverse_iterator rit = str.rbegin(); for(rit+1; rit != str.rend(); rit++){ str2.push_back('*rit'); } std::cout << str2 << std::endl; } ...
For starters there is a typo (or you wanted to highlight the expression) str2.push_back('*rit'); It seems you mean str2.push_back( *rit); This declaration std::vector<int>::reverse_iterator rit = str.rbegin(); does not make a sense. The declared object and the right expression used as an initializer have different t...
65,128,374
65,128,431
Assignment of objects doesn't work in C++
given the following snippet class Box { public: int name; int length; }; std::ostream &operator<<(std::ostream &os, Box &box) { os << "Box name: " << box.name << " and length: " << box.length; return os; } int main() { Box box1; box1.name = 1; Box box2; box2 = box1; box1.name = 2;...
box1 and box2 are their own objects. They can never refer to any object except themselves. Assignment in C++ is done by value. When you assign box2 = box1; you copy the current, immediate value (the state) of box1 to box2. It does not create a relationship between the two. You may be relying on your experience with oth...
65,128,564
65,128,654
how to refer to object explicitly in method call?
in a method call on an object, how do i refer to the object itself, explicitly? in the below example, i tried to used "this", but that aint good // intended behavior but too "verbose" - // is it really necessary to create the temporary "s"? string s = to_string(rand()); string t = s.substr(s.length() - 6); // explici...
You cannot. Your code is not "verbose" but it is concise and expresses clearly what you want to do. Sloppy speaking, if you want to refer to the same object in different places the way to go is to give it a name: string s = to_string(rand()); string t = s.substr(s.length() - 6); If you like you could wrap the string i...
65,128,818
65,129,001
c++ Multithreading - how writes to a shared variable are handled
As the title suggest - in C++, how writes to a shared variable in threads are handled? Do threads work with their own copy of data? I know what is shared between threads and what is not but I could not find anything on how writes to a variable are handled in multithreading scenario. Let me give you a little background....
Do threads work with their own copy of data? No, not unless the data is declared thread_local. synchronization ensures that the writes are flushed to the main memory. Is similar construct valid for c/c++? If a thread is writing to a variable, are those writes immediately updated to the main memory Yes, but unless y...
65,128,826
65,129,123
How can I acquire the data transferring from signal to slot in Qt5?
Well, I have been a new to Qt and I am now using signals and slots. I would like to define a signal void send(int); and emit this signal in A.cpp with some int val like '5' emit send(5); After that, in B.h, I defined a slot void receive(int i); Using the connect function, I connect the signal and slot connect(a,&a::...
Assuming your B class looks something like this, create a member and store the received value in there. class B : public QObject { Q_OBJECT public: explicit B(QObject *parent = nullptr) noexcept : QObject{parent} {} void received(int value) { m_receivedValue = value; } private: int m_receivedValue{0}...
65,128,830
65,238,619
clang compiler options aren't documented?
For the sake of migrating compiler options to ARM using Xcode, I'm looking for a comprehensive documentation for clang c++ compiler/linker options. The closest I could get was this page, however: Many options aren't explained, e.g. -arch, -arch_errors_fatal, -sub_umbrella and many more. There are options in the Xcode ...
I think that in general, you need to refer to Clang documentation and to the Cross-compilation using Clang. Update: If you cannot find the argument you need, please go to the bottom of the page to Search Page. Paste the argument and press "Search". If the argument is supported, you will see its description. For examp...
65,129,050
65,151,077
Global and Local variable, running into problem with connect()
I have this code: mainclass.cpp file: #include "mainclass.h" #include <QtDebug> #include <QApplication> Domino *domino = new Domino(); int main(int argc, char *argv[]) { qDebug()<< __FUNCTION__; QApplication a(argc, argv); MainClass w; w.show(); return a.exec(); } MainClass::MainClass(QWidget *pa...
I don't have an explanation on what exactly happens, I can only assume that there is some Qt magic happening here with the Win32 API. For GUI (non-console) applications, the starting point is not main, but WinMain, which is why Qt redefines main to qMain (https://code.qt.io/cgit/qt/qtbase.git/tree/src/gui/kernel/qwindo...
65,129,165
65,129,233
why is subtracting an array from lower_bound return a dereferenced value?
int arr[] = {0, 1, 15, 22, 100, 101, 232, 2323}; int n = sizeof(arr) / sizeof(arr[0]); int x = 232; auto a = lower_bound(arr, arr + n, x) - arr; if (a < n && arr[a] == x) { // x found at index a cout << x << " is found " << "at index: " << a << endl; } lower_bound returns an address of the element...
arr is an array, and when an array is used in an expression, it can decay into a pointer. Since lower_bound returns a pointer (that's the iterator type for a raw array), and arr decays into a pointer, you are subtracting the address of the found object from the address of the start of the array which gives you the num...
65,129,361
65,129,424
Returning a reference to a temporary
I'm watching this talk from cppcon17 and am trying to replicate and understand the presented bugs. However, I'm not able to replicate/understand bug #3 in the talk (timestamp is in the link above). I've written this minimal example: #include <iostream> #include <map> const std::string& getDefault(const std::map<int, ...
This code, i.e. std::cout << getDefault(myMap, 3, "pizza") << std::endl; is valid; the temporary will be destroyed after the full expression, i.e. after the ;, the returned reference remains valid when being passed to and printed out by operator<< of std::cout. All temporary objects are destroyed as the last step in e...
65,129,414
65,130,653
Check if every string in a set contains equal number of 'a' and 'b' okay I tried again will some one work something out now?
Will some one explain or make a program in c++ of this for me? Got assignment but don't know how to do it. Question: You are given a set of strings which contain only as and bs, your program should be able to check whether each string has the same number of as and bs in it or not. e.g. The program will respond true if...
This solution is using stack, please refer to the comments written in the code. If you have any doubt you can comment them. Code: #include <iostream> #include <stack> #include <string> using namespace std; void checkString(string s) { if (s.size() % 2 != 0) { cout << "Doesn't satisfy the conditon\n"; ...
65,129,434
65,129,961
What would be the best way to build a Big-O runtime complexity analyzer for pseudocode in a text file?
I am trying to create a class that takes in a string input containing pseudocode and computes its' worst case runtime complexity. I will be using regex to split each line and analyze the worst-case and add up the complexities (based on the big-O rules) for each line to give a final worst-case runtime. The pseudocode wr...
The concept: "I wish to write a program that analyses pseudocode in order to print out the algorithmic complexity of the algorithm it describes" is mathematically impossible! Let me try to explain why that is, or how you get around the inevitability that you cannot write this. Your pseudocode has certain capabilities. ...
65,129,452
65,129,497
How to utilise all cores for C++ program
I translated a Java program into C++, and I was getting very slow performance from C++ as compared to Java. Looking at the activity monitor, I saw that the Java program, which I ran first, was using over 90% of the CPU, while the C++ program was using around 30%. It appears that the JVM is able to harness the full pow...
Read a good C++ programming book then see this C++ reference. Read also the documentation of your C++ compiler (perhaps GCC). Read also some operating system textbook. Consider using frameworks such as POCO or Qt or Wt. With a multi-core processor, you might use C++ threads. You'll need to synchronize them, e.g. using ...
65,129,598
65,172,808
Changing <QBitmap> / <QImage>'s contrast
I've used an example code (source: https://forum.qt.io/topic/11390/increasing-contrast-of-qimage/4) to change contrast of a QImage (I've also edited it a little) : void SetBetween0and255(double& value) { if(value > 255) value = 255; if(value < 0) value = 0; } void...
I just had to set the factor variable from ~1 to ~30 to change the contrast by giving these values to the function and the QSlider returned incorrect values. It is also possible to reverse the image colors by passing values from -1 to -30, to also change the contrast of the reversed image. so the right code will be lik...
65,129,720
65,130,101
Using vector of generic queues
I made a generic safe thread queue- QueueTS And I have a class named PackagedEvent. I want to make a vector of queues. Each queue stores PackagedEvent. But its not possible to push a new queue to the vector and I dont understand why. The compiler says: 1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\...
push_back makes a copy when pushing into a vector, but your QueueTS isn't copyable (it's default copy-c'tor is automatically deleted because std::mutex isn't copyable). One solution is to make QueueTS copyable by adding a copy constructor and a copy assignment operator. For example: class QueueTS { public: // . . ....
65,130,017
65,130,174
Can I unwrap std::map iterator to structured binding of optionals?
Consider following code: #include<functional> #include<iostream> #include<map> const std::map<int, std::string> numberToStr{{1, "one"}, {2,"two"}}; int main() { auto it = numberToStr.find(2); if (it ==numberToStr.end()){ return 1; } const auto&[_, str] = *it; std::cout << str; } Is there a...
You could add a helper function like template <typename Key, typename Value, typename... Rest> std::pair<std::optional<Key>, std::optional<Value>> my_find(const std::map<Key, Value, Rest...>& map, const Key& to_find) { auto it = map.find(to_find); if (it == map.end()) return {}; else return ...
65,130,428
65,153,412
Half of read buffer is corrupt when using ReadFile
Half of the buffer used with ReadFile is corrupt. Regardless of the size of the buffer, half of it has the same corrupted character. I have look for anything that could be causing the read to stop early, etc. If I increase the size of the buffer, I see more of the file so it is not failing on a particular part of the f...
The reason is that you use a buffer array of type TCHAR, and the size of TCHAR type is 2 bytes. So the bufferSize set when you call the ReadFile function is actually filled into the buffer array every 2 bytes. But the actual size of the buffer is sizeof(TCHAR) * fileSize, so half of the buffer array you see is "corrupt...
65,130,564
65,133,107
how to make child process when it finishes to return immediately to run parent process ( when we do fork )?
i wrote a function that simulate cp function (copy in bash ) , basically this function takes a file as an input and copies it to a dest file : cp sourceFile destFile . the cp function can run in fore ground or in back ground if there was a '&' at the end of the line (cp sourceFile destFile & ) in order to support this...
fork doesn't work the way you think it does. The child process exists until it's terminated, and inherits things like the parent's call stack; when you return in the child process, you're just going to the calling function. You need to use exit or something in the same family. For example: if (PID == 0) { set...
65,130,729
65,130,777
Why g++ complains about "invalid declarator before", when passing callable object as argument?
#include <iostream> #include <vector> #include <functional> struct Callable { void operator()() { std::cout << "hello world\n"; } }; std::vector<std::function<void()>> cbs; void register(std::function<void()>&& cb) { // <-- ERROR cbs.emplace_back(std::move(cb)); } int main() { Callable c; register(st...
The error message doesn't really help to spot the problem, but there's actually not much more the compiler could say. The issue is register is a reserved identifier. Just change the name of that function, and your code will work.
65,130,829
65,131,021
Accessing elements of std::vector<std::map<int, unsigned char>>grid gives error "Expression must have a class type"
I've searched far and wide and can't find an answer. Why can't I access the elements? It gives me the error: "Expression must have a class type". I have no idea what this means. Can someone give me a solution to this please? #include <iostream> #include <vector> #include <map> #include <utility> #include <algorithm> in...
It seems you mean std::cout << grid.at(0).at(1); instead of std::cout << grid.at(0).at(0).second; It is the same as std::cout << grid.at( 0 ).begin()->second; provided that the element with the key 1 is the first element in the selected map. That is in the second call of the member function at you have to specify a...
65,131,084
65,131,529
How can I call a function from C# app in a C++/CLI DLL?
I've written a simple C++/CLI DLL that has 2 public static methods: namespace GetMscVerLib { public ref class CGetMscVer { static System::Int32 GetCompilerVersion (); static System::Int32 GetCompilerFullVersion (); }; } I'm trying to call these methods from a C# console app in the same solu...
This should work. Because the methods are private by default c# wont allow you to access them. namespace GetMscVerLib { public ref class CGetMscVer { public: static System::Int32 GetCompilerVersion (); static System::Int32 GetCompilerFullVersion (); }; }
65,131,384
65,131,431
how to use printf when printing a value from vector<string>?
I wanted to print the value of string type in a vector using printf but it crashes when i run the program. Please help. vector<string> vec{"zero","one","two","three","four","five","six","seven","eight","nine"}; printf("%s\n",vec[1]);
%s expects a char* pointer, not a std::string object. You can use the std::string::c_str() method to get a suitable pointer for %s to use: printf("%s\n", vec[1].c_str());
65,131,866
65,134,738
Get constexpr without running the program
I have a library (both as source and compiled) and I'm writing a program (not linked to this library) that needs to know if some type in the library is e.g. trivially copyable or not. I could make my program write the following into file.cpp: #include "mylibrary.hpp" int main() { std::cout << std::is_trivially_copy...
You are going to need to compile the code, at least to IR. This is because the triviality of a C++ class can depend on an arbitrarily complicated computation whose inputs may include platform attributes, available headers, preprocessor defines, compiler options etc., which can thus only be carried out by a C++ compiler...
65,132,697
65,135,120
Hi, I am struggling with a sorting problem
The body of the problem is as follows: Let n be a positive integer. Let v be an array with n positions counting from 1 to n and its elements being different numbers from 1 to n Consider n being a power of 2(n = 2^m, with m being a positive integer) and array v has the property that for any i from 1 to m and any j from ...
Think I got it, I think so ... basically a modification of Merge sort, without merging, but instead using the FLIP function that was required to be used. Took me a while, I had an off by one error in there and it took me a minute. #include <iostream> using namespace std; void FLIP(int v[], int n, int i, int j) { ...
65,132,698
65,133,996
What's wrong in my approach in a problem of game of death in a circle?
#include<bits/stdc++.h> #include<vector> #include<algorithm> using namespace std; void safe(int n,int k,int a[]) { vector<int>s(a+0,a+n); vector<int>b(a+0,a+n); while(s.size()>1) { int r; r=s.size(); int count=1; while(count<=r) { b[count%r]=0; ...
Here is a possible solution, hopefully the comments make it clear. There's no need to allocate an int[] and copy it into the vector, you can init the vector directly with iota. Likewise you can remove elements as you go, rather than zeroing and removing as a later step. #include <algorithm> #include <iostream> #include...
65,132,868
65,132,933
Preprocessors Directives in c++ : what is the output of the following code?
Student here. I have the following piece of code and i'm confused about it's output. When i run this code, it tells me the C will be 2 but i though it will be 0. Why is it 2? Ty! #include <iostream> using namespace std; #define A 0 #define B A+1 #define C 1-B int main() { cout<<C<<endl; return 0; }
The main point here is that you are expecting B to be evaluated befor A. This is true of ordinary C++ code, but the preprocessor simply replaces the directive with its contents. In this case, this happens as follows.. Take: cout<<C<<endl; Substitute C for 1-B: cout<<1-B<<endl; B -> A+1 cout<<1-A+1<<endl; A -> 0 cout...
65,132,941
65,143,467
Binary Search with nextafter()
I input an double n and am trying to find the root by binary search. the break-condition with epsilon are kind of long and i was thinking about using nextafter() to compute the result with high precision. double lower = 1, upper = n, mid, midSquared; while (nextafter(lower,upper) < upper) { mid = (l + u)/2.; mi...
Initializing lower to 0 and upper to a minimum of 1 will allow your code to find square roots for values < 1. I would do the error checking on the return value from nextafter if you aren't doing range validation on n. Check for NaN and HUGE_VAL. double lower = 0; double upper = (n < 1) ? 1 : n; double next = nextafter...
65,133,354
65,133,466
Why isn't my array values swapping in shared memory?
I'm working on a program that takes a given number of inputs and gives a sorted output(ascending/descending) using the shared memory in C++ using the fork() system call. I have created a shared memory segment, assigned a key and even put values in it. The values are taken as input in the child process and I can easily ...
In the inner loop you write for(j=0;j<n-i-1;i++) but you increment i instead of incrementing j. If you increment j like for(j=0;j<n-i-1;j++) that will fix it.
65,133,404
65,133,640
Altering and reading elements of a unordered_map from different threads without lock
I have an unordered_map in code, which has a fixed number of elements initialized at the startup of my program std::unorderd_map<int, bool> flags; //Initialize all needed values in the map // Start thread T1 // Start thread T2 all entries initialized to false in the beginning. There are two threads (T1 & T2). T1 can a...
Yes, this causes a problem. The wording from the standard (Β§ [intro.races]/21.2) is: The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers ...
65,133,776
65,134,092
Create your own functor,C++
I want to create a functor like std::plus<>() but also add std::clamp functionality to it. Let's say it is a function plus_clamp<>(T MIN = numeric_limits<T>::min(), T MAX = ...max()) I started to look what implementation does std::plus<>() have, and tried to repeat it. So I wrote something like this. struct plus_clamp ...
There are a number of issues in your code. There is no way to pass the clamp values into the operator (if using std::transform), you need to pass them as constructor parameters to plus_clamp. This then means that plus_clamp needs to be a template rather than the operator. Assuming nl is std::numeric_limits it is a tem...
65,134,030
65,140,276
elegant and fast operator function cpp
I am currently working on a program where my goal is to have a lot of operation between two objects (of one class) as fast as possible using the least amount of storage space possible. class number { public: number(int x) :x{x} {}; int x; // option 1 number operator+(number x) { return number(...
The "correct" way to worry about performance is to turn on compiler optimizations. Most of the time thats it. Write correct and readable code. Once you have that you can measure it. If you find that one piece of code is expensive you can look at the generated assembly to understand why it is expensive. To add two integ...
65,135,285
65,135,681
implementation of is_aggregate_initializable does not work with MinGW64
I need to use a traits function that deduces if a type can be aggregate initialized from given arguments. Typically it is like std::is_constructible, but uses aggregate initialization in decltype(). template<typename POD, typename Tuple, typename = void_t<>> struct is_aggregate_initializable_from_tuple : std::false_typ...
I've figured out. From C++11 to C++14 an aggregate requires to have no default member initializers. That is why I can't initialize abc. If it had no defaulted members, it would compile.
65,135,459
65,135,527
Dynamic Programming Fibonacci Number
I am trying to implement an approach using memoization for calculating the nth Fibonacci number. #include <iostream> #include <vector> using namespace std; int fib(int n, vector<int> v) { int result = 0; if (v[n] != 0) { return v[n]; } if (n == 1 || n == 2) { result = 1; } else...
You are copying the vector for each call, so you don't fill initial the vector by numbers. You have to use unsigned long long to calculate more numbers (actually 93 of them). intΒ can fit only 46 (1836311903). I would check the vector size inside of the function instead of creating it outside. Use unsigned long long f...
65,135,537
65,135,613
How does the C++ compiler evaluate recursive constexpr functions so quickly?
I've been learning about C++ constexpr functions, and I implemented a constexpr recursive function to find the nth fibonacci number. #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <vector> constexpr long long fibonacci(int num) { if (num <= 2) return 1; return fibonacci(n...
constexpr functions have no side-effects and can thus be memoized without worry. Given the disparity in runtime the simplest explanation is that the compiler memoizes constexpr functions during compile-time. This means that fibonacci(n) is only computed once for each n, and all other recursive calls get returned from a...
65,136,404
65,136,425
c++ how to store four 8 bit integers as a 32 bit unsigned integer?
I have four integers and I need to convert them into an unsigned 32 bit integer. I am converting an HDR image into LDR output image data.
You have four 8-bit integers, and you want to combine them into one 32-bit integer. The way to do that is to use bit-shifting, eg: uint8_t ui1, ui2, ui3, ui4; // set values to ui1..ui4 as neeed... uint32_t ui32 = (uint32_t(ui1) << 24) | (uint32_t(ui2) << 16) | (uint32_t(ui3) << 8) | uint32_t(ui4); // use ui32 as ne...
65,136,563
65,136,825
I want to find the week number of a date in C++
I'm trying to find out the week number of a date in C++. I'm taking my date from the console as a string and dividing it into the date, month, and year. This is my code. Please help me to find out the problem. #include <iostream> using namespace std; #include <string> #include <cstring> #include <ctime> int main(void)...
A struct tm uses a 0-based month number. When your user enters 04-11-2020, they (presumably) mean the fourth of November, 2020. To get that when you put the data into the struct tm, you'll need to subtract 1 from the month number. Years also start from 1900, so you'll need to subtract 1900 from your year number. Altern...
65,136,753
65,136,808
how to catch a child process as soon as it ends?
i wrote a copy function that uses fork in order to make the function run in the back ground , the child process should copy the file , and the parent process doesn't wait for the child until it finishes , my problem is that i want to print " copying was complete " massage when the child finishes copying the file , bu...
This is a fairly broad topic and this can be done in a variety of ways. When a process terminates its parent process receives a SIGCHLD signal. You can set up a signal handler for that using sigaction() (older C/C++ code also use the older signal() function for this). The main problem with that approach is that the ent...
65,137,336
65,137,398
Is there any difference between using floating point casts vs floating point suffixes in C and C++?
Is there a difference between this (using floating point literal suffixes): float MY_FLOAT = 3.14159265358979323846264338328f; // f suffix double MY_DOUBLE = 3.14159265358979323846264338328; // no suffix long double MY_LONG_DOUBLE = 3.14159265358979323846264338328L; // L suffix vs this (using floating point casts): f...
The default is double. Assuming IEEE754 floating point, double is a strict superset of float, and thus you will never lose precision by not specifying f. EDIT: this is only true when specifying values that can be represented by float. If rounding occurs this might not be strictly true due to having rounding twice, see ...
65,137,932
65,138,068
Can I count how many kinds enum_class could be?
enum class COLOR_ : char { RED, GREEN, BLUE, YELLOW }; int monsternum{ kinds_of_COLOR_*3 }; my enum class COLOR_ may change a lot, during this project. I want monsternum must be +3 for each kind of COLOR_ how can I know the number of enum_class's kinds?
Assuming your enum is indexed from 0 up to n-1 (where n is the number you want), the idiom I've seen used in the past is to include the count as an "extra" enum value. enum class COLOR_ : char { RED, GREEN, BLUE, YELLOW, COUNT }; Then you can get it and simply cast to an int explicitly. int monster...
65,138,010
65,138,079
how is the output going to get displayed?
i was writing a c++ code for performing binary search in an array,but am unable to wield the desired output. when execute the code, i ma getting a never ending output, what may be the reason behind this? #include <iostream> using namespace std; void Binary(int arr[], int n, int key) { int s = 0; int e = n - 1; ...
After you find your element, you generate output but never exit the loop or change either of the values that the loop condition checks. Simply break out of the loop (or return from the function) after showing your output: if (arr[mid] == key) { cout << "Element Found At Index No. " << mid; break; }
65,138,185
65,138,376
Can someone explain why this vector erase operation isn't working properly?
vector<int> nums{1,2,3,0,0,0}; for(int i = 0; i< nums.size(); i++){ if(nums[i] == 0){ nums.erase(nums.begin() + i); } } for(int i = 0; i< nums.size(); i++){ cout << nums[i] << " "; } //I keep getting [1, 2, 3, 0] I want to remove the zeros from the vecto...
Every time you erase from a vector the index of following elements decreases by 1. You need to account for this: for(int i = 0; i< nums.size(); i++){ if(nums[i] == 0){ nums.erase(nums.begin() + i); --i; // <-- HERE } } This is an O(n^2) operation. You can do this in O(n) lik...
65,138,410
65,138,710
How to use ampersands and asterisks when passing pointers by reference into functions
From EPI 19.4, the question asks to find any cycles in a directed graph. The strategy is to label nodes by the colors white, grey and black during DFS such that when two grey nodes are iterated in succession, a cycle is found. My issue here is not with understanding the strategy, it is with the implementation in which ...
I believe your confusion is centered around lines B and C, so let's break it down. Line B uses the parameter vector<GraphVertex>* G. This means that this vector owns all of these GraphVertices - it contains the actual vertex data and is in charge of allocating and deallocating them. The fact that this is passed by poin...
65,138,464
65,138,705
Template argument 2 and 1 is invalid - declaring vector
I have A txt file which contains data on numerous post-secondary graduates. The records are formatted as follows: year province graduation gender numEmployed numGrads. Here is a part of the file: 2000 AB Bachelor's All 6900 7500 2005 AB Bachelor's All 9300 10000 2015 PE Bachelor's All 440 500 2000 PE College All 728 80...
I have notice that "Property" is a template class, and "Record" is not. And you need to declare it completely in ReportGenerator.h using static std::vector<Property< TYPENAME >*> instead of using static vector<Property*> And the error compiler complain, i consider that is for std::vector template argument 1 for ele...
65,138,502
65,138,864
How can I get the strictly lower value than upper bound in a std::set?
Say I have a set s={1 5 10} Now if I run a loop for [0,2] and everytime check for the strictly lower than upper bound of the set than how can I handle lower value than s.begin() ?See the code for further clarification- set<int>s; s={1,5,10}; for(auto i:s) { cout<<i<<"\n\n"; for(int j=0...
You can return a std::optional if (it == s.begin()) and accordingly print some suitable default such as none. auto strictly_lower = [&] () -> std::optional<int> { if(it == s.begin()) { return std::nullopt; } it--; return std::optional{*...
65,138,696
65,138,835
Is this correct to overwrite operator++ in enum_class?
enum class COLOR_ { RED, GREEN, BLUE, YELLOW, count }; inline COLOR_& operator++(COLOR_& c) { c = static_cast<COLOR_>(static_cast<std::underlying_type<COLOR_>::type>(c) + 1); if (c == COLOR_::count) c = COLOR_::RED; return c; }; this code is in my header file. I include that header to u...
inline COLOR_& operator++(COLOR_& c) { ... } Defines the pre-increment operator (++someColor). You can define the post-increment operator like this: inline COLOR_ operator++(COLOR_ &c, int) { auto res = c; ++c; return res; }
65,139,687
65,230,225
IMFStreamSink::ProcessSample() not being called on a custom media sink
I am trying to implement a custom Windows Media Foundation media sink for use in a UWP application that will use it via MediaCapture::PrepareLowLagRecordToCustomSinkAsync(). However, I am currently running into an issue where the ProcessSample() function of my IMFStreamSink is never called, even though I queue the even...
I have found the solution to my problem: I re-implemented my stream sink without using winrt::implements, which seems to work as intended. What I assume (I'm still not 100% sure, though) is happening is that since IMFStreamSink derives from IMFMediaGenerator, the winrt::implemnets does not generate the QueryInterface p...
65,139,868
65,152,325
Passing Char Array With Unknown Encoding
Let's say I have char content[500] in C++, and it contains some characters in unknown encoding, and I would like to pass it to a python 3 code via ctypes callback. Here is a demo code I created: typedef int (*callback)(char *); extern "C" { void foo(callback cb); } void foo(callback cb) { char hello_world[] = {'h...
c_char_p has special handling to expect null-termination and convert to a Python str. Use POINTER(c_char) instead to suppress the automatic handling, but you need to know the size of the returned data if it isn't null-terminated. With POINTER(c_char), you can convert the returned ctypes.LP_c_char to a Python string u...
65,140,006
65,144,043
How can I store the same id number with different values in C++?
I have a function "link". It has 3 input parameters i, x, y. My problem is if the input i is the same number as i that already exists in the array ix, it replaces the value of existing x and y by the new input values of x and y for I. and when printing it out it shows the last input values. so what I want is to store i...
The array being used is the wrong kind of container for the data involved. A std::multimap is a better choice. Another alternative would be a vector that holds a std::pair<int, Data> (using the struct Data from below). In the code example, the struct Data could also be represented as a std::pair<int, int>. The exampl...
65,140,444
65,140,618
anything like pointers in c#?
I'm new to c# (& coding in general) and i can't find anything pointer equivalent. When i searched google i got something like safe/unsafe but that's not what i needed. Like in c++ if you had a pointer and it pointed towards some value, the change in the pointer would cause change in the original variable. Is there anyt...
If you don't want unsafe code, I can think of two options. Wrapper object You can create a class like this, that wraps an int: public class IntWrapper { public int Value { get; set; } } Then change a's type to be this class: static class Universal { public static IntWrapper a = new IntWrapper { Value = 10 }; } ...
65,140,502
65,145,103
Mock/Change value of external function pointer variable
I am trying to mock function pointers from an external library for unit-testing for now with FFF (Fake Function Framework) but other suggestions are also welcome. //lib.h ... typedef INT64 (__stdcall *fptr_lib_function) (LONG nItemID, LONG nInfoType, LPBOOL lpSuccess); ... extern fptr_lib_function lib_function; ...
In your specific case, lib_function in lib.cpp is a function pointer that gets initialized by RetrieveFunctionPointers. This means after calling RetrieveFunctionPointers() you can easily change the function pointer to point to a different function, i.e. to a fake/mock function. In this case the fake/mock function must ...
65,140,514
65,141,342
Accessing Linux environment variables without assigned value
I wrote small convenience functions for working with environment variables in C++ by wrapping std::getenv, setenv and environ. In addition to setting and getting the environment variables, I provided functionality to check if the current environment contains a certain variable. #include <cstdlib> #include <unistd.h> t...
Shell has a notion of internal and exported environment variables. A shell command like ABC=xyz sets an internal variable (which can be seen in Bash using set). To export an internal variable, there's the export command. export ABC=xyz will create an internal variable and export it (exported ones can be seen using env)...
65,141,621
65,142,452
C++ my copy constructor fails to move the memory to a new area
So I've recently started to work on getting my own vector class working and I'm a little bit stuck on my copy constructor. I'm obviously rather new to c++ and was hoping the good guys at stack overflow could help me out a bit. So I got this copy constructor which copies the actual ptr being used, the end index of the p...
There are multiple issues with your code. The first and foremost one is this: T* storage = new T[capacity]; That storage is not the same as the member variable storage. It is a local variable that just happens to have the same name. Once the copy constructor is complete, you haven't done anything except leak memory. ...
65,142,318
65,145,433
Why can't I input an integer from the istream? *Error on starred input operators*
istream& operator>>(istream& is, State& s){ uint16_t first; int second; char delim; is **>>** first >> delim >> second >> delim; //For player in Room. for(GameObject* i : GameObject::GameObjects){ is **>>** first >> delim >> second >> delim; s.containerObjects.insert(pair<int, int>(f...
I didn't include iostream... however I was still able to use istream and ostream with basic strings, so I guess that is a built in thing?
65,142,445
65,142,723
Remove zero Sum Consecutive Nodes from Linked List - How does this code works for test cases like this?
I have a linked list like this as my input (1) -> (2) -> (3) -> (-3) -> (4) -> NULL And I wish to remove the consecutive nodes which have sum equal to zero i.e., I want my output linked list to be like this: (1) -> (2) -> (4) -> NULL I have already solved this problem using approach of map and array, and then I came ...
(cur) iterates from the beginning of the list. for every (cur) start summing the elements after (cur). when the sum=0 update (cur)->next to point to the first element after this sum. So the first K elements after (cur) with sum=0 are skipped. This is done in loop until end of list. In every loop iteration the first K e...
65,142,538
65,142,633
Why is there a ".h" extension in <bits/stdc++.h>?
(As far as I know) C++ doesn't accept the ".h" extension on header files (as it's usually not present in other include statements) so how does the include <bits/stdc++.h> work in C++ and why does this have the ".h" extension?
C++ does not use the .h extension for standard library headers named in #include statements. But bits/stdc++.h is not a standard header, so the standard library naming conventions wouldn't apply to it. It should never be used anyway. There is no mandatory mapping, IIRC, from the name used in the include statement, to t...
65,142,604
65,143,560
Define class matrix of integers using vector
I have run the following code. Errors I got are: invalid types array subscripts Is there any mistake in using the constructor? While I run it normally without using any constructor, I got an error output. These are the errors I got, please check out what my mistake is: invalid types 'const int[int]' for array subscript...
As @Federico quickly spotted, class data v is initially defined just as a vector<int>, but then used throughout the member functions as vector< vector<int> >. No need to define b and loop indices i,j as class data. In addition, v in the assignment operator was redefined locally, so even after having correctly compiled,...
65,143,349
65,143,543
C++: The average output of my program doesn't show properly
I've already had searched around the internet for some answers, but I can't seem to find the answer. I guess this program would be easier if I use for loop but my professor ordered us to use the while loop statement. #include <iostream> using namespace std; int main() { float value[10]; float average; floa...
Move variables outside of the main function globally and there is no need to initialize them. Also, you can do calculations using only one loop. #include <iostream> using namespace std; float value[10], average, min, max, sum; int index; int main() { while (index < 10) { cout << "Enter a value : "; ...
65,143,418
65,147,377
Depth First Search Algorithm not working as expected when stimulating it with graphics.h C++ library
Thanks for looking into this, I was trying to make a visual simulation of Depth first search algorithm, using graphics.h in C++, Each of my graph nodes have 3 attributes, x_coordinate y_coordinate and a nodeId, also I have a separate Class for Graph Object which has the adjacentcy list graph, So As the following code w...
the (0-3) line never gets drawn because when you hit the condition if( not vis[nb->nodeId]){ node 3 was already visited through line (0-2-3-4)
65,143,423
65,143,526
C++ getting the sum of two array
i would like to get advised on how to get the sum of two array in C++. The sample problem is this.sample problem and sample output. I already got the first part however i can't get the sum. Please help thanks. #include <iostream> using namespace std; int A[10]; int B[10]; int sum[10]; int x,z; main() { cout<<"Enter el...
You need to use loop for (int i = 0; i < 10; i++) std::cout << A[i] + B[i] << "\n"; or if u want whole array you need to add both array into a variable using again loops if you are using c style arrays. After learning this try looking at c++ ways of doing this. this is c way of doing this.
65,143,647
65,143,871
deleted function, can't rewrite one record to another, objects
I'm new here so sorry if I do something wrong. I make a school project. In function I can't simply use tab[i] = tab[i + 1]; It shows error: an element of a function "Pilkarz::operator=(const Pilkarz&)" (is declared implicitly) cannot be referenced - this is a removed function This is my first class: class Player { pro...
The member fstream plik; is not copyable. It has a deleted copy constructor: https://en.cppreference.com/w/cpp/io/basic_fstream/basic_fstream Therefore the compiler can't generate the default copy assignment operator. You can either remove fstream plik; from your class or add a user-defined copy assignment operator: Pi...
65,143,753
65,159,278
write_imagef seems to not change any values
I'm trying to write texture data using opencl and displaying it with opengl. The goal is to compare the performance with and without interoperability. But right now I am failing to generate the texture itself. I first wanted to try to do it without the interoperability: cl Buffer initialization and kernel creation: thi...
First, your "fancy output" part is wrong. Your image has width * height * 4 float elements. You treat it as having width * height elements. auto pitch = this->width * 4; std::cout << "fancy output: " << std::endl; for(int y = 0; y < this->height; y++) { for(int x = 0; x < this->width; x++) { auto r = this->...
65,144,110
65,145,919
Printing LLVM IR with c++ API for debugging IR generation
I am currently working with the LLVM 12 C++ API to convert a custom design specific language to LLVM IR code. However I am running into some bugs in IR code generated. Could you point me in the right direction, to see how I can print out the generated IR code that is contained in my llvm::Module. I tried using this min...
(First, excuse my stupid comment. I was killing time in a queue and obviously my mind wasn't really engaged. Back at my desk now.) Your code creates a module, two constant numbers and an addition. However, an addition can either be a constant or an instruction. If the latter, then the instruction needs to be in a basic...
65,144,268
65,144,997
Why does ActivateObject function return E_POINTER?
i'm trying to work with windows media fundation, get hang of it. I was following steps from this tutorial, and at some point i got stuck. Let me describe my problem. I am calling ActivateObject function from object IMFActivate. This function call is presented in tutorial, I guess, in proper way, so I just copy-pasted ...
I am stupid :) I found mistake in my code. While setting m_globalContentInfo i forgot to set profile. In code it should be something like that: //... hr = m_globalStore->SetValue(MFPKEY_ASFMEDIASINK_AUTOADJUST_BITRATE, var); if (FAILED(hr)) { printError("Failed setting value for bitrat adjust", hr)...
65,144,576
65,144,736
C++ how to use std::function with overloaded operators of different return types
I'm trying to use the standard std::function with custom overloaded operators. However applying std::logical_and to my Test class with a string parameter is not working in this situation. class Test { public: std::string value; Test(std::string cvalue) : value(cvalue) {} std::string operator&& (const std:...
You need to use std::logical_and<> to allow deduction for both arguments and return type: std::string out = std::logical_and<>()(test, "hey"); Demo
65,144,612
65,144,862
How do you declare an abstract port on a MultiBodyPlant
I would like to do declare an AbstractOutputPort is so I can use calculations from the abstract port in my controller. Am I thinking of MultiBodyPlants wrong and should I define create my own LeafSystem void outputGeometryPose( const drake::systems::Context<double>& context, drake::geometry::FramePoseVector<do...
A LeafSystem (like MultibodyPlant) is responsible for creating its own input / output ports internally. You cannot add additional ports to the MultibodyPlant from outside it. But I would think that MultibodyPlant already offers output ports for any multibody-related quantities that you would need. If you tell us a li...
65,144,882
65,144,964
How to pass any number of arguments to C++ template function?
I have this simple C++ template function. I need to pass any number of arguments of any type to the Method, as shown below. How do I do this? template <typename T1, typename T2, auto Method> T1 * wrapObject() { T2 * obj = (*_asposeObj.*Method)(// I would like to pass arguments here); ... } This is a C++20 proj...
It may be that you are not using the parameter pack in the correct way. Correct usage: template <typename T1, typename T2, auto Method, class ...Args> T1 * wrapObject(Args &&... args) { T2 * obj = (*_asposeObj.*Method)(args...); ... } With perfect forwarding: template <typename T1, typename T2, auto Method, cl...
65,145,035
65,145,160
Why, in C++, is my class constructor described by Visual Studio as having "2+ Overloads"?
I have a TreeNode class with a constructor that sets the value of the node, and sets the left and right pointers to null. class TreeNode { public: int val = 0; TreeNode *left; TreeNode *right; TreeNode(int x) { this->val = x; left = right = nullptr; } }; When I hover my mouse over TreeNode(int x) I...
Your class TreeNode has implicit auto-generated copy/move constructors. Those should be the overload pointed by intellisense.
65,145,224
65,145,826
I am trying to change the order of english alphabets in a string such that for a it shall be z, for b it shall be y, etc.. and vice versa
I am trying to replace each occurrence of the letter 'a' by the letter 'z', each occurrence of 'b' by 'y', etc, and each occurrence of 'z' by 'a'....in a string. But the code is not giving desired output... int main() { string S; cin >> S; string alphabet = "abcdefghijklmnopqrstuvwxyz"; string reversed...
Here is my five cents.:) #include <iostream> #include <string> #include <cctype> #include <cstring> int main() { const char alphabet[] = "abcdefghijklmnopqrstuvwxyz"; const size_t N = sizeof( alphabet ) - 1; std::string s( alphabet ); // std::cin >> s; for (auto &c : s) { if (const char...
65,145,631
65,145,679
C++ private variable in struct being modified without using mutator func, not sure why? - OpenGL particle system
I am using OpenGL to write my first particle system and am stuck with an error I can't reason about. My particle struct's "active" property is private (while trying to debug this issue), and I have accessor/mutator funcs for active that print to console when used (again for debugging). I instantiate active=false in con...
Here: Rain() { drops = std::vector<RainDrop*>(); RainDrop drop; unsigned int i; for (i = 0; i < NUM_RAIN_DROPS; i++) { drop = RainDrop(); drops.push_back(&drop); } } You assign a RainDrop to the local variable drop and then store the adress of that local variable in the member vect...
65,145,810
65,145,842
How to pass NULL or nullptr to a function that receives a unique_ptr argument?
template<typename T> void foo(T&& p1) { p1.get(); } int main(int argc, char *argv[]) { auto a = std::unique_ptr<int>(); a = NULL; // this works because a is a unique ptr and it has a get method foo(a); // this does not work because NULL does not has this method. But can it work tho like ho...
You might write overload for std::nullptr_t: void foo(std::nullptr_t) {} And SFINAE the first form to discard it for wrong type as int (possible type of NULL): template<typename T> auto foo(T&& p1) -> decltype(p1.get(), void()) { p1.get(); } but use nullptr instead of NULL
65,146,256
65,146,373
make failed after successful CMake run
So, I am trying to follow this tutorial, I copied the code and CMakeLists.txt, which I later edited. Now when I run cmake everything is fine, but then when I run make it just fail with this error: main.cpp:1:10: fatal error: QApplication: No such file or directory 1 | #include <QApplication> | ^~~~~~~~~~~~~~...
The tutorial you followed has some problem, you should check the KF5 tutorial which has a correct CMake setup. You did the find_package thing, but you forgot to link the library to your executable! In CMake, linking to a library adds compile definitions, include directory and of course linking to the library. Here's wh...
65,146,310
65,146,704
Avoid stack corruption while writing to a pointer location
Let's assume that, we have a C API exposed by a C++ library where the C client queries a value by passing a void pointer and a key. bool GetValue(const char* key, void* val) { if(val != NULL) { // find the value using the key with some logic of library // lets assume found value is a int ...
Simply you have to design API in such way that type of the value is clear. So for example: bool GetIntValue(const char* key, int* val) { if(val != NULL && IsIntValue(key)) { // find the value using the key with some logic of library // lets assume found value is a int int foundValue = 34...
65,146,414
65,146,515
C++ lambda thread stoppable from outside
I'm trying to create a helper thread that waiting and works/finishes if the main thead says so. Something like this: std::atomic<bool> quit(false), doit(false); std::thread([quit, doit]() { while (!quit) { wait(); if (doit) std::cout << "done"; } } the compiler says: 1.cpp:26:15: error: call to im...
std::thread([quit, doit]() Setting aside the compilation error, for the moment: what this says is that this lambda captures this doit variable by value. So, even if the compilation error magically goes away, the end result will be something that's completely useless and will never work. All the lambda will be doing is...
65,146,697
65,152,258
CMake: Qt Project to CLion with MSVC 2017
I'm having a project in Qt Creator and I'm trying to port it into CLion but I found myself blocked into some problems. If any of you could help me to port this CMake project I would really appreciate it. Qt Creator So, here is my setup for the Qt Creator project first: Qt: 5.14.2 Compiler: MSVC 2017 64-bits Also, her...
It looks like QT Creator is using Ninja as a generator and CLion is using MSVC. Try -G Ninja in your CLion CMake Options text box. Make sure Ninja is in a path accessible by CMake.
65,146,769
65,146,912
C++::Access to more than one private members using templates trick
I am studying the following post access private member using template trick. I am wondering how the code should be modified in order to access more than one private varible I tried the following #pragma once template<typename Tag, typename Tag::type M> struct Rob { friend typename Tag::type get( typename Tag::type...
This is because typename Tag::type is both int A::*, so both instantiation define the same function. To fix this, you'll need to change the example a bit so it uses multiple tag types: #include <iostream> template<typename Tag, typename Tag::type M> struct Rob { // Here we receive tag directly friend typename...
65,147,168
65,147,551
Why does my control function do the opposite of what it's supposed to do?
int control(int n, data a[], string cod){ for(int i = 0 ; i<n ; i++){ if(cod == a[i].code) return i; } return -1; } Hello, everyone! this is my control function. it's used to check if a code that has been input by a user already exists in the struct. This is what happens in the "input" function: v...
Let's start by indenting your code so we can more easily understand what it does: int control(int n, data a[], string cod) { for (int i = 0; i < n; i++) { if (cod == a[i].code) return i; } return -1; } Ah, so it scans through an array, and returns a value greater than or equal to 0...
65,147,565
65,148,515
Linking to DLL via registry key ignored during debugging in Visual Studio
I'm working in VS 2019 on a C++ program in which I want to link into a bunch of 3rd party dlls, which are located in a folder separate from my executable. I don't want to copy all the dlls into the executable folder and have found the following solution. Just like in the solution, I create a registry entry to define th...
Following the suggestion by drescherjm I tried to prepend the DLL directory to the PATH variable in "Configuration Properties -> Debugging -> Environment" following this solution. However, this did not work for me. I also added the path directly in the system environment dialogue without success. What did work in the e...
65,147,635
65,147,685
Dereferencing C++ pointer to type if possible
class Foo { public: static const int BAR = 2; }; typedef Foo T1; typedef Foo* T2; int value1 = T1::BAR; // This works. int value2 = T2::BAR; // This doesn't work. Can the value of BAR be extracted from T2? I am using c++-11. I imagine this would be bad practice but am curious if it can be done.
Yes. You can strip the pointer using traits: int value2 = std::remove_pointer<T2>::type::BAR; Or alternatively (since C++14): int value2 = std::remove_pointer_t<T2>::BAR; (reference β€’ live demo) It's not even bad practice, unless there's some more expressive way to achieve your real goal.
65,147,701
65,147,849
Does a constant inside a object method live in the stack?
Consider this method of the class CameraTab void CameraTab::onFocusWheelTick(int delta) { const int lut[] = {0,1,3,6,8,16,32,62,90,120,240,500,700,900,1000}; const int lut_len = sizeof(lut)/sizeof(lut[0]); ... } Does all the instances of this class share the same lut[] array? Is it created and destroyed in...
To frame the answer in pedantic C++ terms: each C++ compiler is free to make any optimization that has no observable difference. What your question is: would this optimization have no observable difference? It seems at first glance that constructing the array and the variable in static scope, just once, would have no o...
65,147,739
65,148,922
Does "printf" prevent deallocation of array?
I was putting together an example for how new can cause memory leaks, and why you should include a corresponding delete, when I found that my output depended on whether I included a call to printf: #include <stdio.h> class Foo { public: double* array; Foo(void) { array = new double[16]; for ...
Calling printf there could make the compiler rearrange things so they aren't the same as when not calling it, and the value may rest in that memory address for some time, but you can't (and you shouldn't) count on that. As comments and @Joseph Larson says your construction is a bug.
65,148,070
65,148,213
C++: How can statvfs take a structure of its own type as an input?
I am using statvfs to check the filesystem, and I have difficulties understanding how the following snippet works: #include <sys/statvfs.h> struct statvfs aStructure; int output = statvfs(aPath, &aStructure); I include the header. This is the only line that's 100% clear to me here. I make aStructure of the type statv...
statvfs is a system call, it is not a constructor of any C++ class. struct statvfs is a C structure. C structures do not have constructors. In C++, struct statvfs becomes a POD. PODs, by definition, do not have constructors. Your confusion comes from the fact that the name of a structure is exactly the same as the name...
65,148,082
65,156,073
How virtual functions affect the way points are generated in OpenGL?
I have a project where I draw a triangle using points, it is called Sierpinski Gasket. To achieve that I am using a class Vx which holds x and y values. The problem is it throws different values if any method is virtual and I wonder why. How virtual functions affect the way the points are generated in the following Ope...
After some research, I found a more detailed answer to this question since it explains why virtual functions affect the way class members have different memory allocations throwing different results, in addition with some documentation from the c++ reference that explains about polymorphic objects and memory allocation...