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
62,553,064
62,558,289
SWIG: read/write same variable from python and C++
I am not really sure if I'm taking the right path here. (See Edit below) I have a C++ library called myapp that compiles into libmyapp.so. This library contains a file called swigtest.h. The thing I want to do, is wrapping this file with SWIG to create an interface for python and using this interface to change or read ...
In Python it changes because it changes in C++. But it changes the C++ value inside the Python process. Each process run in a completely separated context. So when you launch the C++ process separately it runs in completely other context, having its own set of variables, memory, registries. No matter what you do in a p...
62,553,099
62,553,571
Efficient algorithms to check if a binary maze is solvable with restricted moves
I am given a problem to generate binary mazes of dimensions r x c (0/false for blocked cell and 1/true for free cell). Each maze is supposed to be solvable. One can move from (i, j) to either (i + 1, j)(down) or (i, j + 1)(right). The solver is expected to reach (r - 1, c - 1)(last cell) starting from (0, 0)(first cell...
If calling this function many times with low changes there's a data structure called Link-Cut tree which supports the following operations in O(log n) time: Link (Links 2 graph nodes) Cut (Cuts given edge from a graph) Is Connected? (checks if 2 nodes are connected by some edges) Given that a grid is an implicit grap...
62,553,386
62,553,542
manually stop a video in openCV
I have an OpenCV code that was given to me, and it displays a video using a linked list of pictures. I want to add to it the option of stoping the video in case of a loop, using a keyboard key. I did some searching and got to the 'WaitKey' feature, but I'm not sure where and how I'm supposed to use it in my code. cvNam...
cv::imshow("display", image); char ch = cv::waitKey(duration); if (ch == ' ') ch = cv::waitKey(0); // waits until user presses a key
62,553,681
62,553,879
Calling base method however only second level base method exists
Imagine a huge code base with many many inheritance. At some point a line comes in your way in the class you have to work with. inherited::Load(); This is do what it says. It loads the base object into memory. inherited is a typedef for the base class. However the actual parent class does not have a Load method. As a ...
What is actually going on here? Why there is no compilation issue? Is the Derived class copies all the method of the base, so it will have a Load method what is prints "Base ok"? Yes. A derived class inherits all methods from the base class. (yes really all of them, whether it can access them depends on the access sp...
62,553,744
62,557,112
Why does boost::lexical_cast throw an exception even though it converted the value?
I have a puzzling error on my hands. I am sure this code worked fine in an earlier version of boost, now (boost 1.72.0) it chucks an exception: string problemStr = "1.03964e-312"; double problemChild = boost::lexical_cast<double>(problemStr); Setting a breakpoint in boost's code: namespace boost { template <typen...
That's confusing. Couldn't repro it at first: https://wandbox.org/permlink/MWJ3Ys7iUhNIaBek - you can change compiler versions and boost version there However, changing the compiler to clang did the trick: https://wandbox.org/permlink/Ml8lQWESprfEplBi (even with boost 1.73) Things get weirder: on my box, clang++-9 is f...
62,553,819
62,554,775
the WM_CLOSE event is never sent/received?
I'm learning DX12 and, in the process, learning "good old Win32". i have trouble exiting the main loop and it seems related to the fact that i'm not receiving the WM_CLOSE message. In C++, Windows 10, Console application. #include <iostream> #include <d3d12.h> #include <dxgi1_4.h> #include <tchar.h> LRESULT WINAPI Wnd...
Thanks to Simon Mourier comment and link to a tutorial, the problem was solved. The message handling had to be done in WndProc, not in the "main loop". I'm reposting the modified, cleaned, working, code : #include <iostream> #include <d3d12.h> #include <dxgi1_4.h> #include <tchar.h> LRESULT WINAPI WndProc(HWND hWnd, U...
62,554,173
62,554,276
Why can using unsigned short be slower than using int?
On this webpage, the comments on unsigned short state: Used to reduce memory usage (although the resulting executable may be larger and probably slower as compared to using int Why is this?
I think the wording "probably slower" is too hard. A theoretical fact is: Calculations are done with at least int size, e.g. short a = 5; short b = 10; short c = a + b; This code snippet contains 3 implicit conversions. a and b are converted to int and added. The result is converted back from int to short. You can't a...
62,554,557
62,555,032
forward variable Argument list to mock std::thread
I want to mock my threads and wrote therefor an Adapter that just forward everything I need to std::thread. I am failing to do so for the constructor. I tried following: class ThreadAdapter { public: template< class Function, class... Args > explicit ThreadAdapter(Function&& f, Args&&... args) : thread_(f, args...
As Daniel says, you need to forward your arguments and expand your parameter pack, like this: template< class Function, class... Args > explicit ThreadAdapter(Function&& f, Args&&... args) : thread_(std::forward <Function> (f), std::forward <Args...> (args...)) { } Then it works.
62,555,368
62,555,531
Destructor of union member seems to be called automatically
I'm attempting to implement a tagged union. My understanding was that in a C++ union, the non-trivial (i.e. not empty) destructors of non-static members are never called, thus we have to call them ourselves. That's what I did: #include <iostream> class C { public: C() { std::cout << "C Ctor" << std::endl; } ...
In S(int type) : type(type) { if (type == 0) { u.c = C(); } else { u.b = B(); } } Since you are in the body of the constrcutor, u.c = C(); is not initialization but is instead assigment. That means you see the constructor called for C(), and then at the end of the expression the first des...
62,555,425
62,567,332
Arch Linux. AUR package mysql cannot be built with makepkg. ERROR: A failure occurred in build()
I tried to compile the package mysql from source. When I run makepkg -s inside the directory where PKGBUILD is located the building process fails and I have this output: [ 89%] Building CXX object sql/CMakeFiles/mysqld.dir/main.cc.o [ 90%] Linking CXX executable ../runtime_output_directory/mysqld /home/natalya/Downloa...
This worked for me. I created directory /tmp in my /home mkdir ~/tmp and then I set the TMPDIR environment to this directory: export TMPDIR=~/tmp
62,555,449
62,668,731
pcap_handler callback contains empty packets only when using npcap v0.9991
I have some code that is supposed to capture data from an ethernet adapter. I am using the following steps to get the data (after determining the name of the device in the format: "rpcap://\Device\NPF_{0C5[...]C89}"): deviceHandle = pcap_open(device_name, 65536, 1 /* promiscous */, 100, NULL, errbuf) Then running a lo...
This is probably Npcap issue #178, which is fixed in Npcap 0.9992, so it should also be fixed in the current release (0.9994 as of the time I'm writing this). Upgrade your Npcap installation.
62,555,676
62,555,746
Finding Min and Max numbers in a txt file
See the below photo for reference: I have a problem in finding the min and max number in .txt file. The number is stored in a file as one number per line. The Programm should go through these numbers and find the biggest and smallest number. Update: I solve this problem, but I face another issue due to the type of num...
This loop reads all numbers in the file: while (input>>number) { counter++; sum=sum+number; } After that loop, input is already at the end of the file and the next loop will not read any numbers. Read the numbers once and do all processing in a single loop. Alternatively, store the numbers in a std::vector and...
62,555,902
62,556,235
RE2 Not matching non-ascii characters
I cannot get RE2 to match bytes (that aren't ascii) using their hex/octal representation. Code snippet below explains the problem: char *test = "abc""\xe2""xyz"; std::string str(test); // "abc\342xyz" . \342 is octal for \xe2 // str.size() == 7 re2::StringPiece string_piece(str); // size is 7, as expected std::string...
Set the encoding to latin-1 - RE2 default is UTF-8 match = re2::RE2::PartialMatch(string_piece, re2::RE2("(\342)", re2::RE2::Latin1), &out);
62,556,091
62,556,111
Create class instance on stack
I am trying to play a little bit with memory in C++, I have defined myself a class and then I create an instance of that class inside of heap. #include <iostream> class mojeTrida { public: void TestPrint() { std::cout << "Ahoj 2\n"; } }; int main() { mojeTrida *testInstance = new mojeTrida(); te...
The way to create your object (i.e. class instance) on the stack is even simpler – local variables are stored on the stack. int main() { mojeTrida testInstance; // local variable is stored on the stack testInstance.TestPrint(); std::cout << "Hello World!\n"; } As you have noticed according to your comment...
62,556,200
62,556,499
Overloading an operator in a namespace and a sub-namespace in C++17 is ambiguous
I try to overload the operator<< in a namespace. Additionally, I want to include a debug namespace within the first namespace, where the operator<< does more. In the main function, I create an object of a class within the first namespace and give it out with std::cout. I expected to have to 'name' the operator before I...
I expected to have to 'name' the operator before I can do that, as in using test::operator<<, but I don't have to. This is because of Argument Dependent Lookup (ADL). If you pull the operator from the debug namespace into the current scope via the using, this does not "overwrite" the existing operator, they are both ...
62,556,339
62,556,377
Stack smashing detected : terminated Aborted (core dumped)
My array is of size 3x3 means i have values of index from 0 to 2 only. but when i traverse using for loop then why it is picking value of a[3][-3] on value of a[2][0] ??? and what is that error when i try a[3][3] it should give garbage value so why this error *** stack smashing detected ***: terminated #include <bits/s...
For an array like a[3][3], indexing into a with [3][3], or [3][-3] invokes undefined behavior. Anything can happen, including printing out garbage values. The program is not even guaranteed to print a value, it could simply crash. The only valid indexes for either bound is 0, 1, and 2. Note that even if you index into ...
62,556,571
62,556,740
Why do I need to repeat template arguments of my base class in member initalizer list?
I was porting some code from MSVC(without permissive-) to linux and I learned that if you call constructor of a template base class in initializer list of your class you must specify all the template parameters or you get an error. Seems kind of redundant, since if you make a mistake in retyping the template parameters...
You only need to do that when Derived is a template and the type of the base depends on its template parameters. This compiles, for example: template <typename T> class Derived : public Base<int, false> { public: Derived(const T& t) : Base(t) {} }; As far as I know, here (in member initializer list) Base is actual...
62,556,625
62,721,913
Basic Enter key functionality in C++Builder
I am currently porting an old Borland C++Builder 5 project to C++Builder 10.3. I have successfully ported all the project files, and it compiles and runs as intended, however there is an issue with the Enter key in some of the Forms. The old project would always execute the same functionality as double clicking an item...
Using C++Builder 10.4, I added a VCL ListView to a form with two items. I set up the ListView onKeyPress event handler. Then when I select one or the other items in the ListView and hit the enter key, I get the caption for the ListItem that was selected. void __fastcall TForm1::ListView1KeyPress(TObject *Sender, System...
62,556,691
62,560,683
Sample Application for WebView2 Older version
I am working on official released version of Edge - 83.0.478.50( assuming this is latest official version) and its compatible Webview2 SDK version V0.9.430. I could not find the sample application or Getting Started application. The official page is pointing to latest SDK API. https://learn.microsoft.com/en-us/microsof...
If you examine the history of the WebView2APISample.vcxproj file, you can see when it was updated to different WebView2 SDK versions and then checkout the corresponding change in your local repo. Looks like this change moved to build 430. If you have a local clone of the repo you should be able to do the following to g...
62,556,712
62,556,983
why am i getting this never ending loop while trying to print elements in singly linked list
I'm new to data structures and I was able to implement this singly linked list in c and it worked fine. While I was trying to implement the same in C++ I was pretty much done with it except the printList() part. This same function worked without any issues in C but when it was executed in C++ it is going into a never e...
Your bug is here: Node *head = new Node; one reason this is a bug is you are creating a head node with uninitialized data and uninitialized next pointer. You could fix that by adding a constructor for your Node class or using Node *head = new Node{}; or add a constructor for Node() if you have an old compiler. but w...
62,557,002
62,557,073
Insertion to std::list<std::vector<int>> failed when using initializer list as the value?
I have a C++ snippet that looks like this: std::list<std::vector<int>> lv; lv.push_back({}); std::cout << lv.size() << std::endl; // "1" lv.insert(lv.end(), {}); // Oops! // lv.insert(lv.end(), std::vector<int>()); // OK std::cout << lv.size() << std::endl; // Still got "1", but why? As you can see, whe...
Overload resolution for the lv.insert(lv.end(), {}); // Oops! call will resolve (formally, chosen as the best viable function as per [over.ics.rank]/3.1) to the following std::list<>::insert overload [extract from std::list<>::insert at cppreference, emphasis mine]: iterator insert( const_iterator pos, std::initia...
62,557,271
66,605,083
Why is there no WMI instance for Win32_Fan, when I do have a fan?
I am using WMI to monitor certain hardware metrics, and specifically, I am using WMIExplorer.exe to find WMI classes and their instances(link to WMIExplorer.exe download: https://www.bleepingcomputer.com/download/wmi-explorer/). When I try to retrieve instances of the Win32_Fan class within the Root\cimv2 namespace, I ...
Win32_Fan instances are provided by Windows\System32\wbem\cimwin32.dll. If you disassemble it you will see that it reads SMBIOS data (specifically entries with type 27) to get fan device information. So having no such instances means your system manufacturer did not write fan device info into SMBIOS, which is part of R...
62,557,280
62,557,849
c++ permutations of input
So I'm trying to take a user input of a couple of different numbers and have an output of every possible permutation of these numbers, in c++. Currently it works for up to three different numbers. I however can't figure out what stops it from taking on more numbers and was hoping to get some answers here. Furthermore, ...
I recommend to throw your code away and start over. You overcomplicated it and it's more difficult to fix it. Divide your main function into two parts: Read input Print permutations int main() { const auto input = readInput(); printPermutations(input); } You divide your problem into two smaller problems and ...
62,557,318
62,570,134
Qt and Android - How to launch camera by using Qandroidjniobject
I am new in Qt android app development. I want to open camera and take picture and get the path of image by using QtAndroid, and JNIObject. For example, Intent capture_image_intent = new Intent(); capture_image_intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(capture_image_intent, 101); I want...
I solved this above problem in Qt by using Qandroidjniobject. For launching camera by using intent code is given below, QAndroidJniObject ACTION_IMAGE_CAPTURE = QAndroidJniObject::getStaticObjectField("android/provider/MediaStore", "ACTION_IMAGE_CAPTURE", "Ljava/lang/String;"); QAndroidJniObject intent("android...
62,557,536
62,852,356
Linux Mount using Remount to allow read-write
I want to remount a read-only file system so that it becomes read-write, using the root account. Checking the Linux Manual pages, I noticed that there is no flag like MS_RDWRITE, so my question is, does anyone know of an example online that demonstrates using mount with remount flag that sets a read-only path to allow ...
I could not get the native API working. Per the manufacturer, they recommended using the remount command in a terminal window. This worked correctly for me. This will remount the entire root folder as read-write when called with root privileges. // Remount the root folder. char* cmd = "mount -...
62,557,684
62,557,840
How can I write generic code that will be inherited?
I'm trying to write some generic code in a parent class that gets inherited. However, I'm struggling with the type-ing of some of the variables. Take the code below: class A { protected: std::vector<void*> struct1; std::vector<void*> struct2; std::vector<void*> struct3; public: A::~A...
Did you mean that you wanted classes like B to inherit from A so that the destructor will destroy the contents of the vectors? template<typename T> class A { protected: std::vector<T*> struct1; std::vector<T*> struct2; std::vector<T*> struct3; public: A::~A() { for(auto i : struct1) { ...
62,557,753
62,558,034
Array index sequence expansion by pointer vs by array reference
I was looking at the to_array implementation from libstdc++ here and noticed that they use a clever trick to avoid writing an extra overload for the function by using a bool template argument to decide whether the function should move or copy the elements to the newly created array. I decided to play around with this t...
There's a lot template code covering a, in comparison, quite simple topic. In the following example, you are passing an array by reference: #include <iostream> void baz(int (&arr)[4]) { for (const auto e : arr) { std::cout << e << " "; } } int main() { int a1[] = {1, 2, 3, 4}; baz(a1); // 1 2 3 4 ...
62,557,861
62,558,115
Got runtime error while using BFS algorithm
There are n cities connected by m flights. Each flight starts from city u and arrives at v with a price w. Now given all the cities and flights, together with starting city src and the destination dst, your task is to find the cheapest price from src to dst with up to k stops. If there is no such route, output -1. Ex: ...
Look into this code: vector<vector<vector<int>>>g; for(auto f:flights) { int from=f[0]; int to=f[1]; int cost=f[2]; g[from].push_back({to,cost}); } Initially g is an empty vector. The first thing you are doing with it is accessing the non-...
62,558,559
62,558,715
No matching function for call to ‘std::vector::push_back(std::string&)’
I was given a C++ assignment for my class to make a program that reads student data records from a user, and the program will then sort the keyed in data records into sorted order in terms of students’ GPAs, or in terms of the alphabetical order of the students' last names, or doing both, depending on the user’s option...
Your vector has a type std::vector<student> But you are trying to push a string instead: string names; v.push_back(names); You probably meant v.push_back(student{names, 0}); This however opens another issue with pushing the GPA. Here you should just iterate over existing elements: for(int i=0; i < num; i++){ cout ...
62,558,640
62,558,775
i want to change variable value but all i want memory address will stay same, how can i do that
int x=5; int &time=x; int *ptr_x = &time; while(1) cout << (*ptr_x) << endl; (*ptr_x)++; i want to change "variable value" but all i want "address" will stay same, how can i do that –
Whats the difference between incrementing pointers value and the value of the pointer? Increment pointer's value It means you have a pointer pointing to a value. You increase the value. The fact that there is something pointing to it is "accidental". Increment the value of the pointer It means you have a pointer poi...
62,559,077
62,559,306
Can I instruct g++ to compile a c++ source file with a different extension than ".cpp" etc?
I am writing a library/framework that can be configured as a CPU-only implementation or a hybrid CPU-GPU implementation. As an example, say I the following files: LibraryMainCode.cpp LibraryMainCode.h Numerics.cpp Numerics.h For a CPU-only implementation, the build is straightforward: g++ -I. -c Numerics.cpp -o Numeri...
You can explicitly specify the language of a source file using the -x <lang> option: g++ -x c++ file.strange_extension
62,559,422
62,559,441
calling a static data member declared in hxx file
I have declared a static variable in a file say "example.hxx" and am calling this variable in the cxx file "example.cxx" in this way example.hxx file :- class example{ private: static int p; public: void func(); }; CXX file #include <example.hxx> class e...
You have only declared p. You need to define it as well, like this, outside the class: // .hpp file class example{ private: static int p; // declaration }; // .cpp file int example::p = 42; // definition Alternatively, you could do: class example{ private: inline static int p = 42; // inline defini...
62,559,634
62,559,688
Why are my LEGACY OPENGL colors inverted?
A few months ago i wrote a simple code for displaying 3 polygons. Everything worked fine. Then the colors suddenly started shifting... Im in VISUAL STUDIO 2019. I tried: Repairing the VS redistributables. Making a new project. Any clue? #include <GLFW/glfw3.h> int main(void) { GLFWwindow* window; /* Initial...
The color attribute has to be set (glColor) before the vertex coordinate is specified by glVertex2f: glBegin(GL_POLYGON); glColor3f(1.0f, 0.5f, 0.5f); glVertex2f(0.5f, 0.5f); glVertex2f(-0.5f, 0.5f); glVertex2f(-0.5f, -0.5f); glVertex2f(0.5f, -0.5f); glEnd(); glBegin(GL_POLYGON); glColor3f(1.0f, 1.0f, 1.0f); ...
62,559,811
62,560,660
convert s1 to palindrome with s2 as its substring
https://discuss.codechef.com/t/given-string-s1-and-s2-how-to-convert-given-string-s1-with-minimum-changes-to-palindrome-which-includes-s2-as-substring/69769 can some one help me understand this code please #include<bits/stdc++.h> using namespace std; int main(){ string s1,s2; cin>>s1>>s2; int l1=s1.length(),l2=s2.leng...
Palindrome... same backwards as forwards... The first part of your code overlays s2 on top of characters in s1 starting at some position: i. the string temp is the first i characters of s1, then all of s2, then whatever characters remain in s1 that werent covered up. The length of temp should be the length of s1. In t...
62,560,162
62,560,375
Free storage for pointers stored in a heap allocated vector
I have a unique_ptr pointing to a heap allocated vector, that itself stores pointers to dynamically allocated objects. The problem is I think the unique_ptr frees the dynamically allocated vector itself, but this vector's destructor doesn't free the dynamically allocated objects. So, how to solve this problem without ...
You have a misunderstanding about how types work in C++. Every type has a fixed size. You can get this size with sizeof. For example, on a typical platform, a vector<Test*> has a size of 24 bytes. When you allocate a vector on the stack, you are only allocating those 24 bytes on the stack. When you add objects to the v...
62,560,789
62,561,153
Is it possible to create a template instance with a non-default constructor in c++?
Is it possible to specify which constructor to use when inheriting from a template based class? It seems like a basic thing, but I can't seem to figure out how to accomplish this in C++... In the following code, I want to use a non-default constructor for the PlayerStats object when I create a PlayerActor (which inheri...
template <class ActorStatsClass> class BaseActor { public: BaseActor() { } private: ActorStatsClass m_stats; }; If this BaseActor class is going to have arbitrary members, it needs ways to construct those arbitrary members. So it needs a generic constructor. template <class ActorStatsClass> class BaseAc...
62,560,790
62,560,921
this_thread::sleep_for sleeps early
I am trying to do a very simply thing (yet spent hours without a result): Print one line, sleep a little, print a second line. I expect the below code to do that, however, it first sleeps then prints both lines simultaneously! Can anyone see what I'm missing here? This is the entire code: #include<thread> #include<chro...
printf doesnt necessarily flush the buffer, which is why you dont see it until the thread resumes from sleep (it does this because it notices the thread is inactive). To force a flush add fflush(stdout); before the call to thread sleep.
62,560,995
62,561,202
Run-Time Check Failure #2 Stack around the variable 'A' was corrupted
I've been getting this error for the code I'll post below. On going thru debugging and using breaks, it's breaking the program after the end of the program (ie. after the last } in main). I thought it was an overflow issue, but I am not seeing where there might be an array overflow. I've tried changing the numbers or f...
In SequentialSearch, on this line: A[n] = Key; you are invoking undefined behavior by accessing A out of bounds. In this case, A has only 500 elements, but n is 500. For an array of 500 elements, the only valid indexes are 0 to 499.
62,561,063
62,563,262
Error when I try to compile project using CMake with SFML library by mingw
When I want to compile project using CMake with SFML library by mingw (last verison), I catch a lot of strange errors (c++). CMake code: cmake_minimum_required(VERSION 3.0) project(MLproject) SET(CMAKE_SYSTEM_NAME Windows) SET(CMAKE_SYSTEM_VERSION 1) SET(CMAKE_C_COMPILER "i686-w64-mingw32-gcc") SET(CMAKE_CXX_C...
The error: CMakeFiles/UI.dir/src/UI/ScrollBar/ScrollBar.cpp.o:ScrollBar.cpp:(.text+0x6d): undefined reference to `_imp___ZN2sf14RectangleShapeC1ERKNS_7Vector2IfEE' indicates that the UI library uses some SFML components. However, you only link the SFML libraries to the main executable, so the library doesn't know wher...
62,561,090
62,563,062
default value in struct and the constructor order
I know we can have default value for struct members. For instance, I can set default value for those members: struct Foo { int a = 0; int b = 1; int c; } Suppose I have another constructor for member c: struct Foo { int a = 0; int b = 1; int c; foo(int input_c): c(input_c) {} } In this case, when I cons...
The order initialization happens in is quite rigid, it is always the order the members are declared in. First of all, all default in-class initializers are applied (in the order that members are declared) unless overruled by the initialization list. Then the constructors initialization list is used and any members list...
62,561,155
62,561,462
do I have to call get or wait on a std::async future
If I run it with launch::async then I know it will run anyway (I think thats what I read), but do I have to call get / wait in order to perform some sort of clean up. I dont need the result, I just want a nice fire and forget.
Put attention, that destructor of returned future object will perform blocking wait until your task action will finish (and the corresponded shared state will become ready). See last paragraph on the page: https://en.cppreference.com/w/cpp/thread/future/~future
62,561,380
62,561,769
Middle of a linked list bug
I write a function to print the middle of a singly linked list, but when the list length is odd, it is not printing it (does not print anything just blank space), and when the list length is even, it is printing the mid (sum of the node, which is correct). I have the following code: struct Node { int value; Nod...
Let's step through the logic for your example of an odd-sized list: Upon entry to mid_list(), head is the value=1 node, and temp1 and temp2 are set to head. Note that you are NOT checking head for NULL, so your code will fail if the list is empty, but that is not the case in this example. On the 1st loop iteration, ...
62,561,497
62,562,439
How to open a specific directory with QFileDialog in QT
I wanted to open QFileDialog for a specific path like //DC1/C$/Users/ but when QFileDialog opens it goes to a default path. When QFileDialog opens, I can change directory to the UNC path but I wanted to open this path as default. How can I do that? In the following code, g_absolutePath has been initialized with //DC1/C...
The Qt Documentation documents how to do this : void UploadFM::on_pushButtonDestination_clicked() { const QString defaultPath = "//DC1/blabla..."; QString fileName = QFileDialog::getExistingDirectory(this, "Choose Folder", g_absolutePath, defaultPath); ... }
62,561,717
62,561,750
How to call a function several times in the same line using an operator
This function adds a TElement to a vector<TElement>: friend void operator<<(ToDo& todu, const ElementT& D) { todu.add(D); return; } I want to call it like this: todo << elem1 << elem2 << elem3 << elem4...
If you want to chain operations like that, then you can simply return the ToDo parameter by reference, like this: friend ToDo& operator<<(ToDo& todu, const ElementT& D) { todu.add(D); return todu; } and now you should be able to use operator<< like this: todo << elem1 << elem2 << elem3 << elem4;
62,561,729
62,561,835
I am asking user to enter the size and array but when I am printing the vector it shows '0' only as output
I declared a vector and trying to put size and values and printing it #include<iostream> #include<vector> using namespace std; int main() { int s; cin>>s; //taking size of vector vector <int> arr(s); int input; while (cin >> input) {arr.push_back(input);} //ins...
This line: vector <int> arr(s); makes arr have the size s. It will have s elements that have been default-initialized to 0. Then you are doing push_back on this vector, which adds additional elements into the vector. When you print out the first s elements, you are not seeing the values that were read from cin, but th...
62,562,094
62,562,614
stl container of vectors of object c++
i have class with some vectors of objects, and also a lot of methods working on those vectors. So my pseudo-code looks like that: method1(std::vector1); method1(std::vector2); . . . method2(std::vector1); method2(std::vector2); . . . (etc.) Every time new vector of objects is being added to my class i have to remember...
The container you are looking for is std::vector. I was thinking about std::list because those vectors are changing theirs size, so there is a lot of reallocation. A std::vector does not change its size when you add elements. std::vector::size() returns the number of elements, but sizeof(some_vector) is constant. A e...
62,562,242
62,562,432
C++20 in g++10: generator not defined
This MCVE works fine in Visual Studio. #include <experimental/generator> #include <iostream> std::experimental::generator<int> f() { for (int i = 0; i < 10; ++i) co_yield i; } int main () { for (int i : f()) std::cout << i << ' '; return 0; } but in g++10, which is listed as having full support or C...
Nothing in GCC's status list alongside its coroutine support says it supports anything other than p0912r5, which does not provide std::generator, experimentally or otherwise. I recall that VS added <experimental/generator> a few years ago; I guess GCC never did. If it's currently proposed for inclusion in C++, and you ...
62,562,702
62,563,123
Cannot make function public. Getting: "LNK2005" error. How to debug linker errors
there is only one definition of MyFourierClass::forward_fft in my project. When I declare MyFourierClass::forward_fft as public, I get this error, otherwise there is no error. Error Message: 1>my_fourier.obj : error LNK2005: "public: void __cdecl MyFourierClass::forward_fft(int)" (?forward_fft@MyFourierClass@@QEAAXH@Z)...
As you included the module my_fourier.cpp in the module with main using the include directive #include "my_fourier.cpp" then this function void MyFourierClass::forward_fft(int bins) { bins = bins + 1; }; is defined at least twice. You should place the class definition in a header and this header include in the m...
62,563,480
62,563,757
How to force, value to be lvalue reference?
I want my function to take a lvalue reference and absolutely not a rvalue or temporary or whatever. This is my function: template<class T> void foo(T& value) {} // Imagine I have a class Foo struct Foo { int a; int b; }; When I call foo(Foo{1, 2}), first, it compiles even if I asked for a lvalue reference, and...
First of all, the given code will not compile by default in GCC and Clang, only in MSVC with non-standard extensions. If you want to make sure that foo() does not accept an rvalue, just delete that overload: template<class T> void foo(T&& value) = delete;
62,563,543
62,563,886
Efficiency: std::array vs. std::vector
I'm using std::vector here in this line: std::vector<bool> visited(length); to solve a LeetCode problem: Given an array of integers arr, you are initially positioned at the first index of the array. In one step you can jump from index i to index: i + 1 where: i + 1 < arr.length. i - 1 where: i - 1 >= 0. j where: arr...
a std::array is just a fancy c++ wrapper for an object that is the same as a normal C array. And just like a C array, the size needs to be known beforehand. If an array is allocated in a function it goes on the stack just like a C array. If it is allocated as part of a class the storage for the array is a simple offset...
62,563,764
62,795,230
Read Back Vertex Buffers from GPU in DirectX 11 (and get vertices)
Im trying to gain access to my applications Vertex Buffers (and there vertices) using the below method: //access vertex buffers UINT* Stride = new UINT[32]; UINT* veBufferOffset = new UINT[32]; ID3D11Buffer** veBuffer = new ID3D11Buffer * [32]; pContext->IAGetVertexBuffers(0, 32, veBuffer, Stride, veBufferOffset); std...
Here’s one way to do that. Get the ID3D11Buffer pointer like you’re doing. Ideally use something like std::vector<CComPtr<ID3D11Buffer>> instead of new/delete but that’s not too important, at least not for small projects. Call ID3D11Buffer::GetDesc to get size and other parameters of the buffer you wanna read. Adjus...
62,563,915
62,563,994
why cant I pass a reference as a function argument for std::async
I have this code. int TA11::AsyncRunP(Unit *unit,Function func) { return 0; } int TA11::AsyncRunR(Unit& unit, Function func) { return 0; } void TA11::RunFunc(Unit& unit, Function func) { assert(!unit.fut_.valid()); unit.fut_ = std::async(std::laun...
std::async passes the arguments to the callable by value (doesn't make perfect forwarding), hence you got the error because your callable only accepts reference. You can use std::ref() to pass your var by reference.
62,564,186
62,566,313
How do I retrieve text from QML's TextField from C++ code?
I'm trying to retrieve the user input text value typed in the TextField but QML can't find my object, when I type something, the following error paper on Qt Creator's application output ReferenceError: foo is not defined What am I missing? note: Any better way to do this is very welcome. I just started learning QML. ...
If you want to export a QObject then you should use setContextProperty(), not setProperty(). Also it is not necessary to use QVariant. engine.rootContext()->setContextProperty("foo", &nameUserInput); On the other hand it is not necessary to use Q_DECLARE_METATYPE, and it is good practice to put Q_PROPERTY in the privat...
62,564,308
62,565,259
How to know when MMsystem audio-recording have finished?
I’m using the "winmm.lib" c++ library to access audio via the microphone. I have a short int array with 8192 elements that I want to fill with the audio stream. It works fine when I record sound and sleep for the right period of time: const int lenBuffer = 8192; // 2**15 short int SOUND_BUFFER[lenBuffer]; ...
An async thread would work fine: // sampling input auto future = std::async(waveInStart, hWaveIn); //future is your async thread cout << "recording... " << std::endl; //maybe move this inside waveInStart // do stuff here type result = future.get(); // the program will wait to execut this line if the async threa...
62,564,334
62,564,437
why we use const char* func() instead of char func()
as I am new in programming, I just wanted to know in the following code why we wrote const char* what() instead of char what below in 6th line. second, why someone wrote MyException& e not just MyException e why we used reference over here in the Catch block. please enlighten me as I am a little confused over reference...
There are two reasons to do so here. A char represents a single character, like a or ,. A const char* can represent an entire string of characters, so you could have: char getChar() { return 'M'; } const char* getWord() { return "String"; } The second reason is because the class MyException is deriving from std::excep...
62,564,657
62,564,692
Is <initializer_list> included in <iostream>?
I know that the below code-block compiles #include<initializer_list> int main() { std::initializer_list<int> li = {1,2,3,4}; } I can't understand why this also compiles #include<iostream> int main() { std::initializer_list<int> li = {1,2,3,4}; } Is <initializer_list> included in <iostream>? According to this,...
Is <initializer_list> included in <iostream>? It is not specified nor guaranteed to be. But also, it is not guaranteed to not be included. Any standard header may include any other standard header, or system header. You should not rely on such transitive inclusion because another (version of the) standard library mig...
62,564,944
62,565,010
C++ variadic template product
I'm writing a testbench for a library that operates on different container types i.e. std::vector<int> std::vector<char> std::vector<bool> std::list<int> # etc I'd like to automate the generation of tests by basically doing the cross product of std::vector, std::list, std::forward_list with <bool, char, int> and also ...
How do you provide container types like std::vector as a template parameter without also providing a type? You cannot pass templates as a template type parameter because templates are not types. But you can pass them as template template1 parameters. Example: template<template<typename...> typename C> void foo(); fo...
62,565,274
62,566,379
fopen returning NULL in gdb
Im trying to solve a binary exploitation problem from picoCTF, but I'm having trouble with gdb. Here is the source code of the problem (I've commented some stuff to help me). #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <wchar.h> #include <locale.h> #de...
I don't want the solution, I just don't know if this is intended behaviour or a bug. I am not sure whether you'll consider it intended behavior, but it's definitely not a bug. Your ./vuln is a set-gid program. As such, it runs as group canary_3 when run outside of GDB, but as your group when run under GDB (for obviou...
62,565,354
62,565,606
Can a default function return auto?
Consider the following class: class example { public: auto & operator =(const example &) = default; auto & operator =(example &&) = default; }; Are those declarations considered legal?
auto & operator =(const example &) = default; auto & operator =(example &&) = default; Are those declarations considered legal? No. [dcl.spec.auto] ... If the declared return type of the function contains a placeholder type, the return type of the function is deduced from non-discarded return statements, if any, in...
62,565,674
62,565,907
Trying to put a function definition from a class in another file but a private member of my class is in the definition
I currently have the following in my header file: class Scene { private: const char* file; public: void sceneRender(); void setFile(const char* f) { file = f; } void printFile() { cout << file; } }; I want to define this function in another file apart from it but am having trouble with what to put insi...
The class definition is usually on a .h file so you'd have: myfile.h class Scene { private: const char* file; public: void sceneRender(); void setFile(const char* f) { file = f; } void printFile() { cout << file; } }; And in a separate file, which usually has the .cpp extension and the same name as the...
62,566,322
62,581,020
Using Magick++ library on windows
The title is pretty self-explanatory... how do I build the source for Magick++ for Windows? I've tried everything, and followed ImageMagick's directions extensively. However, all of these instructions are outdated. How do I get the static link libraries for Magick++, the include directories, and the dynamic link librar...
So basically it's super easy... Go to this link here, download whichever version fits your platform, go through the setup, and when a bunch of options comes up click the one that says install developer libraries. The include directories and libs will be in wherever you chose to install it.
62,566,438
62,566,478
In C++ are elements of an array of pointer type by default guaranteed to be initialized to nullptr?
If I have code like so class Node { public: Node *subnodes[10]; }; Node x = Node(); is it guaranteed after that code runs that x->subnodes[0] == nullptr? I'm no expert at C++, and I find C++ specs daunting. This works out in practice, but is it guaranteed by the spec that nullptr is put in each element of the arra...
Yes, it is guaranteed. Node() constructs a temporary object and performs value initialization. As the result, all the elements of the member array subnodes are zero-initialized as null pointer. x is copy-initialized from the temporary object and its members get the same initialization result too. (Because of copy elisi...
62,566,851
62,566,877
2-dimensional vector data member
I am getting an EXC BAD ACCESS error. Not sure what the problem is. I am trying to test the cells inside the 2d vector. I would like it to print a grid of 0's 20x20 struct Cell { int test; Cell(): test(0) {} }; class Board { public: Board() { for (int i = 0; i < 20; i++) { Cell temp; ...
In your code cellVec is default-initialized and contains no elements. Then trying to access element of it like cellVec[i] leads to UB. You can initialize cellVec as containing 20 elements in member initializer list, e.g. Board() : cellVec(20) { // initialize cellVec as containing 20 default-initialized std::vect...
62,567,248
62,567,750
Is it possible to create a thread that calls a function from a different class?
I am working on a C++11 multithreated GUI program. So I have the DevTools and MainWindow classes. I want to call a function that belongs to DevTools from a MainWindow clicked() event function. (All object definitions are created on the classes' definitions). Function on MainWindow calls Obtain_XY_Thread: void MainWindo...
This was simply fixed by adding std::thread: void MainWindow::on_obtain_xy_clicked() { std::thread obtain_xy(&DevTools::Obtain_XY, &DevTools); obtain_xy.detach(); }
62,567,718
62,575,891
Does operator function also cause function overhead
As per my understanding when we call a non-inlined function like foo() program control will shift to called function address then store the location of caller and return bank to the caller to another statement after previous function class. But when I implement the class with operator definition will the same process o...
An operator overload is just a function with a peculiar name. The compiler translates use of the operator into a function call. That is, a + b becomes a.operator+(b) or operator+(a, b), depending on how the overload is defined. (You can also write those out yourself, and it will behave exactly the same but miss the poi...
62,568,425
62,568,476
Specific Friend Function Specialization
Suppose I have a class like follows: namespace n { template<class integral> class ex { public: friend auto ::operator +(integral i, ex const & e) { return i + e.i; } int i; } } This code does not work because operator + is...
In the first example, because of Argument Dependent Lookup (ADL) it will work fine if you just drop the scope operator from the friend declaration: namespace n { template<class integral> class ex { public: // Note lack of scope operator in declaration friend auto operator +(integral i, ...
62,568,936
64,937,741
Cocos2d-x v4.0 crashing in iPhone Simulator with Xcode 12, Xcode 12.1, Xcode 12.2
Cocos2d-x v4.0 crashing in all iPhone Simulator. In device no crash glslopt_shader* glslShader = glslopt_optimize(ctx, shaderType, source.c_str(), 0); For above line everytime crashing. Not using any shader. Above line called by Sprite creation. auto background = Sprite::create(TEX_MM_BG); How to fix this crash for s...
With that little info we can't help much. But if I try to interpret the posted image corretly you receive a "EXC_BAD_ACCESS" Exception. This means more or less that you access a freed memory region or in general you try dereference a pointer pointing to an invalid memory address. The only argument which could cause suc...
62,569,003
62,569,303
Why can't assign const initialize while compile by pointer
I'm curious about why my research result is strange #include <iostream> int test() { return 0; } int main() { /*include either the next line or the one after*/ const int a = test(); //the result is 1:1 const int a = 0; //the result is 0:1 int* ra = (int*)((void*)&a); *ra = 1; std::cout <<...
The function isn't really that relevant here. In principle you could get same output (0:1) for this code: int main() { const int a = 0; int* ra = (int*)((void*)&a); *ra = 1; std::cout << a << ":" << *ra; } a is a const int not an int. You can do all sorts of senseless c-casts, but modifiying a const ob...
62,569,744
62,569,962
Send Variable values from QDialog to QMainwindow function
My UI MainWindow has a QListWidget and , upon clicking of its items ,a corresponding QDialog box must pop up , which prompts the user to enter some values in QDialog box, The values entered into line_edits of QDialog box must stored into a QString variable and this variable should be accessed/used in a function of Main...
you need to add in the WinApp dialog class the test getter, it should be something like: QString getFavouriteHotel() const { return ui.<favourite-hotel-label>.text() } In the MainWindow after the line winApp.exec(); I suggest adding an if to check if the user accepted or declined the dialog (docs). If the user acc...
62,569,944
62,588,901
C++ Writing to file with an unwanted null character inside the pathname
i fell on this singular issue: i have to write to a txt file on a path that is like "C:....\0-myfolder\subfolder\file.txt", where '0-myfolder' is the entire name of the folder writing it as a normal path with double backslashes doesn't work because of the unwanted null character that gets read in the sequence. I tried ...
Using raw string literals may be a good solution: #include <iostream> int main(void) { std::cout << R"(C:\0-myfolder\subfolder\file.txt)" << std::endl; return 0; } Handles escapes automatically producing the clean output C:\0-myfolder\subfolder\file.txt see https://en.cppreference.com/w/cpp/language/string_lite...
62,569,992
62,571,043
Adding a timestamp to filenames in C++
std::ofstream myFile ("report.csv"); So in my folder, I will get the file as "report.csv" How can I add a timestamp to the file name making it look like (date)_(time)_report.csv? I have included... #include <windows.h> #include <string> #include <time.h> using namespace std::chrono; I do not wish to add more librarie...
Since you didn't specify if the timestamp should be UTC (recommended) or just local date-time, here are both ways: #include <chrono> #include <iomanip> // put_time #include <fstream> #include <sstream> // stringstream int main() { auto now = std::chrono::system_clock::now(); auto UTC = std::chrono::duration_c...
62,570,253
62,570,476
Despite everything looks fine, values are not swapped
I wanted to write a function to swap two integers. Despite everything looks fine, values are not swapped. Here is my code: #include <iostream> using namespace std; void mySwap(int a, int b) { int temp; temp = a; a = b; b = temp; } int main() { int a = 5, b = 4; mySwap(a, b); cout << a << ' ' << b << en...
To manipulate with the values passed as arguments in main() directly, use a reference (followed by an ampersand sign &) as shown: #include <iostream> void mySwap(int& a, int& b) // using reference here { int temp; // remove for alternative option described at the bottom temp = a; // a = a + b; a = b; //...
62,570,435
62,570,871
How can I iterate through unknown object methods in C++?
Suppose I have the class class BaseClass { public: BaseClass(); ~BaseClass(); void runAllMethods(); }; and the sub class class SubClass : public BaseClass { public: SubClass(); ~SubClass(); // arbitrary methods void method1(); void method2(); ... }; Suppose I then create ...
How can I iterate through unknown object methods in C++? As far as I know, this is impossible. Check by reading n3337 (the C++11 standard). A possible approach is to generate the C++ code running all of them. You could use some meta-programming approach (like Qt does with its moc, which generates C++ code), or you co...
62,570,602
62,571,186
Binary search not converging for double
I have to find the nth root of a number , it is passing some of the test cases but failing for some when x=0.09 and n=3 I am getting ans as 0.09 but expected is 0.448140475. I am not able to figure out why bs is not working Please help! #include <iostream> #include <vector> #include<algorithm> #include<iomanip> #includ...
Firstly, I suppose that you are trying to utilize the bisection method, not binary search. Secondly, In mathematical perspective, in order to find the actual root, the initial bisection domain should contain the root from the beginning. However your bisection domain is too small to contain the actual root. (for 0<x<1, ...
62,570,882
62,571,241
what(): basic_string::_M_construct null not valid
I am making a program where I need to use a function which stores a tokens of a string in a vector. The function did not work properly so I tried the function on a smaller program. Of course, I used string tokenizer function. But it is not working as expected. First, here's the code: #include <vector> #include <string>...
In while(ptr) { ptr = strtok(NULL," "); v.push_back((string)ptr); } For the last token ptr will be null, constructing a std::string from a null pointer is undefined behaviour. Try: while(ptr = strtok(NULL," ")) { v.push_back(string(ptr)); } For a more c++ solution: #include <vector> #include <string> #inc...
62,570,987
62,571,091
Using next_permutation to get all combinations of length N C++
I am trying to do the classic all combinations of a list problem and I found this code here on the forum that works wonderful. However, I would like to limit the combinations to N elements. I know there are many similar threads but I am yet to find a simple solution to this issue. Are there any simple solutions to this...
The most simple is to use only the first two elements of any permutation and skip duplicates. To have uniques you can use a std::set: #include <vector> #include <iostream> #include <algorithm> #include <set> void next() { int n = 2; // Will only give me combinations of length 2 std::vector<std::string> arr = ...
62,571,674
62,571,758
Deduce type of Compare for std::set from constructor arguments
I wanna write simpler syntax when declaring std::set with custom compare: auto s = std::set({1,3,7,9,2,4},[](int a,int b){return a>b;}); but it does not work out of the box. CLang produces: /Users/kyb/devel/untitled3/main.cpp:13:14: error: ambiguous deduction for template arguments of 'set' auto s = set({1,3,7,9,2...
I believe there is a way to do that in more clean way. Your code snippet above should not be rejected by clang, as is governed by [associative.reqmts]/151 [emphasis mine]: A deduction guide for an associative container shall not participate in overload resolution if any of the following are true: (15.1) It has an I...
62,571,793
62,571,982
How can C++ remember inputs given in the past after being executed more than once?
I am working on creating a bank system with C++(see: Can anyone give me advice on this bank system project? for more details). What I would like to know is what I need to implement in my C++ code in order for it to be able to remember past inputs. In my project, this would mean that after executing the code for the fir...
To be able to recall past inputs, independent of program execution you will have to store that information. The most simple approach would be to store the necessary information in a text file. More complex approaches involve databases. View std::fstream for an example on how to use streams. If you want some more conve...
62,571,871
62,572,474
How to pass member function of class to thread?
What is the correct way of passing a member function to thread class foo{ public: int sum(int a ,int b) { std::cout<<a+b; } }; i need to pass this function to a thread in my main function.I have seen an example #include <thread> #include <iostream> class SayHello { public: void greeting(std::string const&...
why do we need to pass the reference to the object in this case? A member function, apart from the "normal" arguments, also takes a pointer to the object (this). This one is implicitly provided when you call with the normal syntax: x.apply_greeting("goodbye"); //secretly calls apply_greeting(&x,"goodbye"). (not valid...
62,572,152
62,572,350
list of prime numbers between 1 and 100
I want to find the list of prime numbers, I try this code but it doesn't show me anything: #include <iostream> using namespace std; int main() { int n, i; std::cout << "Liste des nombres premiers : " << std::endl; for (n = 1; n < 100; n++) { for (i = 2; i < n; i++) { if (n % i == ...
To correct program errors: Initialize the value of n as 2. And print when i is equal to n not when n % i is 0. It should be rather n % i == 0 then break. Change i < n to i <= n. Try the first approach (used sqrt()): #include <iostream> #include <cmath> int main(void) { for (int i = 2; i < 100; i++) { if...
62,572,364
62,572,398
c++ change array by index inside function
void changeArray(char* str1) { str1[0] = 'f'; } int main() { char* msg1 = "andrew"; changeArray(msg1); cout << msg1 << endl; return 0; } Hi guys,i dont understand why i'm getting segmentation fault. pointers cannot be accessed by index inside functions? (C++)
You're trying to modify string literal, which leads to undefined behavior. Attempting to modify a string literal results in undefined behavior: they may be stored in read-only storage (such as .rodata) or combined with other string literals: const char* pc = "Hello"; char* p = const_cast<char*>(pc); p[0] = 'M'; // und...
62,572,758
62,606,771
Difference between c++ and python solution of constructing bst from preorder traversal
Although this solution does it in O(n^2).What really fascinates me here is that the same solution in C++ gets accepted while the python version throws error.I am a novice in C++.Any help will be appreciated.The root passed in buildBST function always assumes it to be Null in python . C++ code TreeNode *buildBST(TreeNod...
root is a pointer ref in C++ TreeNode *buildBST(TreeNode* &root, int ele) { root is just a parameter in Python def buildBST(self,root,ele): When your code changes the value of root before return it has no effect in your Python code. Probably it should be: def buildBST(self, root, ele): if root is None: ro...
62,572,832
62,573,925
Is it always possible to rewrite a program written using recursion, to one that does not use recursion in C++ and what is the performance view point?
Just wanted some gyan on this question, at performance point of view and also please explain with respect to about how/Why Stack and Ackermann Function might be involved in this, is it okay to use it every time in C++ ? because it appears for me that each recursive program does indeed have a non-recursive implementatio...
Most of the problems which involve looping can be solved using recursion. So they are grouped into a special type namely Primitive Recursion. Then there are problems not belonging to this category. One such example is the famous Ackermann function. There are some problems where recursion maybe a better approach, for ex...
62,573,130
62,573,222
If const doesn't allocate memory, why I can get address of const?
C++ Primer said if the const can initialize while compile, it will swap the identifier to the value used when initialize, so why I can get the address of a const initialize while compile?
The key word in that statement is can. If the compiler can then it may replace your constant with a literal at compile time. If you take the address of the constant then the compiler must allocate memory for it so that there is something to point to. Even if you do this it may still use the literal instead of the memor...
62,573,347
62,632,685
How add wavefront file(.obj) to surface3d qml?
I wanna add a obj file(wavefront format) as a point(by a position) in surface3d in qml but i dont know how i do it! i found some solutions but they have some problems, for example i just want use qml , but they use c++ and QCustomItem . i tried to use it in sactter3d with new mesh (just training with that) but it could...
finally i added my CustomItem in qml. at first i created a Custom3DItem : Custom3DItem { id:c3i meshFile: qsTr(":/Items/oilrig.obj") position: Qt.vector3d(35,150,35) textureFile: qsTr(":/Items/redPng.png") visible: true scaling: Qt.vector3d( 0.25 , 0.25 , 0.25 ) } then i wanted add it to my Sur...
62,573,397
62,573,709
Returning char * instead of string
How may I correct the following code in C++11: const char *what() const noexcept override { return "Mtm matrix error: Dimension mismatch: (" + std::to_string(mat1_height) + "," + std::to_string(mat1_width) + ") (" + std::to_string(mat2_height) + "," + std::to_string(mat2_width)...
but won't that be converrted automatically? No. and how to fix that? Store the string as a member, and call c_str() in what. Example: struct descriptive_name : std::exception { std::string msg; descriptive_name( int mat1_width, int mat1_height, int mat2_width, int mat2_height) ...
62,573,407
62,574,807
Don't understand Template implementation of the JLospinoso books
In the JLospinoso (c++ Crash Course), chapter 10 about unit testing.Link to the book page There is this code (simplified) struct BrakeCommand { double time_to_collision_s; }; template<typename T> struct AutoBrake { AutoBrake(const T& publish) : publish{publish} {} ---snips--- private: const T& publish; }...
{}[] symbols which are confused you it's a part of the lambda definition passed by initializer_list to AutoBrake constructor. Let's go through the code line step by step AutoBrake auto_brake{[](const BrakeCommand&) {}}; 1 Lambda which takes BrakeCommand as an argument and does nothing [](const BrakeCommand&) {}; 2 T...
62,573,409
62,574,674
Why does bi-directional/forward operators don't support inequality relational operators?
I'm currently learning iterator types and there's something that I quite don't understand. First, from what I understood, iterator types are pointer-like types, meaning they can point to any element in a container and can also performs arithmetic operations (like pointers). It also appears that random access iterator t...
Why does bi-directional/forward operators don't support inequality relational operators? I mean the following operators <=, <, >, >= Because it would not be possible to efficiently1 implement such operators for all bi-directional/forward iterators. Consider for example how you would implement such operator for an i...
62,573,416
62,573,643
Why can I assign characters to string objects but not to vectors of string objects?
C++ Primer says that character and string literals may be converted to strings. I tried assigning a character to a string as: std::string s; s = 's'; And it gave me no error. But, when I tried to assign characters to a vector of strings object as: std::vector<std::string> svec; svec = {'a', 'b'}; It gave me an error....
C++ Primer says that character and string literals may be converted to strings. C-style string literals can convert to std::string implicitly, but chars can't. That's different from assignment. s = 's'; works because std::string has an overloaded operator= taking char. Replaces the contents with character ch as if...
62,573,601
62,574,164
Modifying tasks.json to compile multiple c++ files
I have 2 cpp files in /home/misha/proga/c++again folder: one with main function, and another with a function definition declared in the first one. I want to compile both of them. Here https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson it explains how to do that, but I'm stuck. First, I build C/C++...
As say in comments you try to compile /home/misha/proga/c++again*.cpp who not exists because the compiler try to compile all files in proga folder who begins with c++again and ends with .cpp Be sure to have the / character between your folder's name and your sources files names at the compilation time.
62,573,703
62,573,915
Why my map is only temporarily modfied in lambda function and value is not preserved?
I have local function, wherein am calling lambda function based on some conditions. Lambda function should check if key exists in map. If no, add key with default value = 0; if yes, just incerement value. When condition is satisfied lambda adds key to map, but only temporarily. Could you help me? using center_points_t...
As Jorge Bellon says in comments. You have to replace center_points_t map by center_points_t &map then it should work. Because you are taking a copy of your variable but the & character send the address of the original variable instead of a copy to your lambda function. So with &map your function will add a key to your...
62,574,701
62,578,259
SDL2 transparent background
I'm trying to create a .PNG image from a larger .PNG image. Basically clip a rect area of the original and save the result as another .PNG Sort of like a texture unpacker, if you will. My issue is that the portions that were transparent in the original image are colored in the clipped image. Initially I used hardware a...
There are two problems: Disable blending. Use SDL_SetTextureBlendMode(source, SDL_BLENDMODE_NONE); before RenderCopy, otherwise you'll get wrong colour (blended with default black - result would be darker than it shound be). Blending tied to texture so if you want to use this texture later you probably should reset bl...
62,575,131
62,590,542
CPP include directories setup in azure devops
I am trying to setup a build pipeline in azure devops. I have a cpp project. It needs a Framemaker FDKs to build. I have the FDK files on my local storage as well as on TFS. I want to link them in my pipeline so that they can be used while building and do not throw file not found errors.
Since Framemaker FDK is installed on local machines. You should create a self-hosted agent on the same machine where the FDK is installed. And then you need configure your pipeline to run on this self-hosted agent by targeting the pipeline agent pool to your local agent pool. So that your pipeline will be able to acces...
62,575,197
62,580,126
Compiling multiple C++ files. Calling a binary to run a code
I have 2 cpp files(with one main function) in /home/misha/proga/c++again folder. I built C/C++: g++ build active task and modified it to compile all files in the folder above. Now, I need to add one more task to call a binary. I think I should add one more entry in "tasks" to finally be able to run a code. Where can I ...
In Terminal, cd /home/misha/proga/c++again Let's suppose your two cpp files are mainFile.cpp and file2.cpp If g++ (so GCC) was not installed in your system, you can install it by running this command on the Terminal: sudo apt-get install gcc g++ and, to compile the program (read about invoking GCC, you want warnings ...
62,575,485
62,576,517
Translate text using google without API
I am trying to write a simple free translator (QT widget) using the online translation service. The idea is to send the standard get request to an online translator, and then parse the response. But the reply does not contain the translated text ! I guess this is because the service uses AJAX. In the example, I am usin...
looking at Google Translate it uses AJAX Request, to get the translation. You could try to change the URL to something like this (this is where the ajax request goes to): https://translate.google.de/translate_a/single?client=webapp&sl=auto&tl=en&hl=de&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=sos&dt=ss&dt=t&d...
62,575,522
62,578,754
Is there a way to create a menu inside an established for loop box (C++)
I am still very new to learning C++, and can't seen to figure out how to add a "for loop menu" inside another for loop box that I have created using ASCII. I am trying to create a menu with 7 options using an array inside the already constructed box. In my limited knowledge, I think I need to add another for loop with ...
Using the approach you've chosen, you need to add an array with your menu options and print them instead of spaces inside of the menu box. To save alignment in lines with menu options you can use setw() from <iomanip>. Resulting code can look like this: #include <iostream> #include <string> #include <cstdlib> #include ...
62,575,730
62,575,913
Armadillo library difference between square brackets [] and parenthesis ()
Armadillo library provides 3 ways for element access: via (); via []; via at(); I noticed that there is difference in perfomance when using each of them. I tested the code below: size_t n_row = 500, n_col = 500; { // () wall_clock timer; mat matrix(n_row, n_col, fill::zeros); timer.tic(); for (size_t...
The answer is mostly in the link you gave: ".at(n) or [n] As for (n), but without a bounds check. Not recommended for use unless your code has been thoroughly debugged." So the first part of the answer is that .at(n) and [n] are potentially slightly faster, but less safe, than (n), which is maybe why () access took ...
62,575,790
62,576,227
C++ class member scope when instatiated object in constructor
I have this code in class constructor: MqttSensorInterface::MqttSensorInterface(Client& client, String sensorTopic) { this->mqttClient = PubSubClient(client); this->sensorTopic = sensorTopic; this->askMeasureTopic = sensorTopic + "/askmeasure"; this->publishMeasureTopic = sensorTopic + "/measure"; } But just a...
When the body of the constructor MqttSensorInterface::MqttSensorInterface(String sensorTopic) { WiFiClient wiFiClient; this->mqttClient = PubSubClient(wifiClient); this->sensorTopic = sensorTopic; this->askMeasureTopic = sensorTopic + "/askmeasure"; this->publishMeasureTopic = sensorTopic + "/measure"; } get...
62,576,083
62,576,407
Perfect forwarding function parameters to function pointer: What about passing by value?
I have a data structure that provides access to its elements, and some loop logic for how to iterate over them. I need to call different functions inside the loop(s). These functions all take a data element as first parameter, but shall be allowed to have any number of additional parameters. So far, this sounds like a ...
Args will be deduced twice, once for the function signature, and once for the parameters. They do not necessarily need to be exactly the same: the argument is deduced as int&, since it is deduced from a local variable, but it does not correspond to the function signature (which is int). You can split them, like this: t...
62,576,089
62,576,164
operator << overloading in a template function
I can't tell which part of this code is wrong. Error message is given below. I want to overload the << operator so that I can write code like cout << tree. I looked up for information about templates, friend functions, operator overloading. But I still don't get why the error. template <typename Value> class Tree { ...
Before you can befriend specific template specialization, you have to declare the general template function first like this: template <typename Value> class Tree; template <typename Value> std::ostream& operator<<(std::ostream& os, Tree<Value> const& tree); template <typename Value> class Tree { protected: Nod...