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
73,022,014
73,022,139
Why can MyClass foo() access private default constructor?
The following code: #include <iostream> using namespace std; class Myclass { private: Myclass (); public: int num; }; int main() { Myclass foo(); return 0; } Compiles without any warnings or errors in Eclipse. However #include <iostream> using namespace std; class Myclass { private: Myclass ...
Why can MyClass foo() access private default constructor? It cannot (fancy hacks that allow you to call a private constructor aside). Is foo() being mistaken as a function Myclass foo(); is a function declaration. The mistake is to expect it to be something else. To call the constructor write: Myclass foo; // or M...
73,022,324
73,022,753
Heapsort with a selectable amount of children
Im trying to write some code that could sort an array using heapsort. The heap have two children right now but i want the user to be able to choose the amount of children in the heap(d in the function heapsort). Question: How do i make the function heapsort able to recieve a number (d) from the user and sort the array ...
Just because you made it so easy: template <typename T> void heapify(T arr[], int n, int d, int i) { int biggest = i; int childrenStart = d * i + 1; int childrenEnd = childrenStart + d; if (childrenEnd > n) { childrenEnd = n; } for (int child = childrenStart; child < childrenEnd; ++ch...
73,022,498
73,022,869
Error while opening png image with Gdk::Pixbuf::create_from_resource
I'm trying to read the png image with Gdk::Pixbuf::create_from_resource: #include <iostream> #include <gtkmm.h> int main(int argc, char *argv[]) { auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base"); Gtk::Window window; window.set_default_size(100, 100); try { Glib::Re...
If you want to load an image file directly into your program, instead of: Glib::RefPtr<Gdk::Pixbuf> image = Gdk::Pixbuf::create_from_resource("image.png"); you would use the following statement: Glib::RefPtr<Gdk::Pixbuf> image = Gdk::Pixbuf::create_from_file("image.png"); If you do want to use the ima...
73,022,556
73,026,329
QT C++ app crashing when send data with serial port
I am simply trying to send data via serial port, but I am getting segment fault error. When I click void productDetail::on_detailSaveBtn_clicked()) I got thıs error The inferior stopped because it received a signal from the operating system. Signal name : SIGSEGV Signal meaning : Segmentation fault Debug shows arron o...
If you run your code through cgdb, lldb, or any debugger in any IDEs, it will tell you where it is crashing. Based on your further clarification, it seems that you are trying to call a method on an instance of QSerialPort which has not been constructed yet. You need to create the serial port instance as per the example...
73,022,595
73,023,178
Impossible conditional statement
bool flag = ((idx == n) ? true : false); if (C[idx]->n < t) fill(idx); if (flag && idx > n) C[idx - 1]->deletion(k); The above code snippet is part of the BTree implementation, I searched everywhere but I can't find will the second if-statement will ever be executed? The flag will only be true when the idx =...
After implementing my version, I get to know that the in some conditions the fill function is calling another function named merge that is changing the value of n. When child-node can't borrow either from left-sibling or right-sibling they will merge with the parent, Which results in a change in the value of n void f...
73,022,841
73,025,381
Different colors of COLOR_WINDOW in Windows 10 and Windows XP
In Windows 10 color of window equal of background colors of GUI elements. However, in Windows XP color of window is white, that is not equal of background colors of elements. WNDCLASSEX configuration: WNDCLASSEX wincl; //... wincl.hbrBackground = (HBRUSH)COLOR_WINDOW; // Set background color //... i...
COLOR_3DFACE/COLOR_BTNFACE is the color constant you are looking for. COLOR_WINDOW is the color inside a text box. GetSysColor function Value Meaning COLOR_3DFACE15 Face color for three-dimensional display elements and for dialog box backgrounds. COLOR_BTNFACE15 Face color for three-dimensional display eleme...
73,023,102
73,023,493
Trivially copyable class - what has changed in C++20?
The standard says A trivially copyable class is a class: (1.1) that has at least one eligible copy constructor, move constructor, copy assignment operator, or move assignment operator ([special], [class.copy.ctor], [class.copy.assign]), (1.2) where each eligible copy constructor, move constructor, copy assignment oper...
What is the difference between pre c++20 and C++20 standard meaning? For pre-C++20 classes, none. For post-C++20 classes, the difference is constraints. The old wording talked about special member functions being "non-deleted". The new wording talks about them being "eligible." Eligible is defined in [special]/6: An...
73,023,510
73,024,065
Ignore the other string from input if certain string from array is detected
I need to create a program that print out the input value if on the first line of the input exists in an array #include <stdio.h> #include <iostream> #include <string> #include <algorithm> int main() { std::string avai_commands[] = {"PRINTAGE","CREATE"}; // Both must have the same functionality std::string i...
You need to parse your input. For example, you can split every line you enter and verify if it starts with the commands you want: #include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> int main() { std::string avai_commands[] = {"PRINTAGE","CREATE"}; // Both must have the s...
73,024,001
73,024,053
Overriding a pure virtual function with inline implementation
I've come across a piece of code which boils down to this: class Base { virtual void foo() = 0; }; class Derived : public Base { inline void foo() { /* Implementation */} }; I know the person who wrote this code is coming from a C background, so it may not be a correct practice. I understand that Derived::foo...
The method is already implicitly inline because it appears in the class definition. inline is not what you think it is. It is not to control whether calls to the function are inlined by the compiler. The compiler will decide this independent of the attribute inline. It merely says: The definition can be in a header, no...
73,024,149
73,024,328
Why can't the std::string constructor take just a char?
While using a function template, I was looking at how to convert a char into a length 1 string in C++, and I saw that std::string(1, c) converted the char into a string using the fill constructor, following the logic of "repeat char c 1 time to form a string." However, there is no constructor overload defined for std::...
In C and C++, char serves double-duty. It represents both a character and a number. It is considered an integral type, which means that it participates in implicit integer promotion to many other integral types, as well as implicit conversion from other integral types. Because char is overloaded, it is impossible at th...
73,024,572
73,053,969
Make a child class inherit specific attributes from two different parent classes?
I have a problem with a Diamond inheritance exercise. I have one base class A. Here is its constructor : A::A(std::string name) : _hp(10), _ep(10), _ad(0) { std::cout << "A object created !" << std::endl; return ; } Then, I have two parent classes B and C. Here are their constructors: B::B(std::string name) : ...
Okay, I got my program to work properly. Maybe I didn't explain well what I wanted to do, but I'm posting my solution here. There are 4 classes A, B, C and D. They all have _hp, _ep and _ad variables. D inherits from B AND C, which in turn inherit from A.          A        /     \       B     C        \      /        ...
73,024,981
73,025,026
C++ sort table by column while preserving row contents
Given a row-major table of type std::vector<std::vector<T>> (where T is a less-comparable type like int or std::string), I'd like to sort the table by a specific column while preserving the row contents (i.e. a row can only be moved as a whole, not the individual cells). For example, given this table: 2 8 1 4 3 7 6 7 3...
Use a comparator that compare the element to compare. std::vector<std::vector<T>> vec; // add elements to vec int idx = 2; std::sort(vec.begin(), vec.end(), [idx](const std::vector<T>& a, const std::vector<T>& b) { return a.at(idx) < b.at(idx); }); Full working example: #include <iostream> #include <vector> #inclu...
73,025,746
73,043,511
What does python do inside the gdb debugger?
I was debugging a C++ program in the gdb debugger and tried to access the 5th element of vector which only contains 4 element. After trying this error was on the screen: (gdb) list main 1 #include <memory> 2 #include <vector> 3 4 int main(int argc, char *argv[]){ 5 6 7 std::vector<int> v_num = {1, ...
Does gdb uses python internally? Yes, it uses Python a lot to extend itself in many ways, see https://sourceware.org/gdb/onlinedocs/gdb/Python.html#Python. What you discovered is called Python Xmethods, see https://sourceware.org/gdb/onlinedocs/gdb/Xmethods-In-Python.html. Xmethods are used as a replacement of inline...
73,025,780
73,026,534
Does calling a member variable of constexpr struct omits a whole constructor evaluation?
Let's say I have the following structure: struct MyData { int minSteps{1}; int maxSteps{64}; double volume{0.25/7}; }; constexpr MyData data() { return MyData(); } Does any of expressions below make an instance of the MyData structure constructed somewhere before the value is assigned? int steps = dat...
It's very unlikely an instance of MyData will actually be created if you compile your code with optimizations on. Any modern compiler should optimize it out. GCC will do so even at O0, MSVC will optimize it out at O1, so it's fair to say you likely don't need to worry about it if you don't intend to compile your code w...
73,025,998
73,248,280
How to access protected members
I have a MockAlgoController class which has protected inheritance of ControllerMockParams. How to access these protected fields outside, i.e. when asserting in tests? struct ControllerMockParams { int numCtx{0}; MockAlgo firstAlgo{Interface::first, numCtx}; MockAlgo secondAlgo{Interface::second, numCtx}; } ...
To access protected fields outside you must not use protected in the first place. So your code should be like: class MockAlgoController : public ControllerMockParams, public AlgoController { public: MockAlgoController() : AlgoController( ControllerMockParams::firstAlgo, Controlle...
73,026,053
73,026,238
#include in header and in main file (c++)
I have a project where there is a class item in a header item.h. I need to use the item class in both my main.cpp file and my player.h header. There are example files to explain my situation : main.cpp: #include "player.h" #include "item.h" #include <vector> std::vector<Item> items; int main(){ Item i; Player...
You need to do this in item.h: #ifndef SOME_WORD #define SOME_WORD // the same as above //item.h content #endif You can now import item.h in all the files that you want.
73,026,741
73,026,883
how can I allow a method parameter to be null
I'm new to c++, and coming from c#; in c# to achieve my intended goal I would simply do this public void MyMethod(int? value) { if(value is null) { // Do something } else { // Do something else } } how might I achieve this result, if possible in c++?
You can do this with std::optional. void MyMethod(const std::optional<int>& option) { if(option.has_value()) { // Do something with the int option.value() } else { // Do something else with no value. } } std::nullopt is what you pass when no value is desired. MyMethod(std::nullopt); Or if you want to be able t...
73,026,924
73,026,965
Using `static` keyword with Structured Binding
I'm trying to use C++17 structured binding to return a pair of values and I want those values to be both static and const so that they are computed the first time the function they're in is called and then they maintain their uneditable values for the lifetime of the program. However when I do this I get the error: a ...
The error is a bit confusing, but structured binding to static variables is just not supported with c++17. Either use a different solution, or c++2a. A different solution could just be an additional line: static std::pair pr = pairReturn(); auto &[a, b] = pr;
73,026,939
73,028,268
Spdlog: Only write to file if there is an error
At the moment I am combining a file sink with a console sink. (see bellow) std::vector<spdlog::sink_ptr> sinks; sinks.push_back(std::make_shared<spdlog::sinks::wincolor_stdout_sink_st>()); sinks.push_back(std::make_shared<spdlog::sinks::daily_file_sink_st>(path, 23, 59)); ...
You can call file_sink->set_level(spdlog::level::error) to make it log only on error and more severe levels.
73,029,184
73,032,691
Vertical order traversal of a binary tree: when nodes overlap
I am working on the LeetCode problem 987: Vertical Order Traversal of a Binary Tree: Given the root of a binary tree, calculate the vertical order traversal of the binary tree. For each node at position (row, col), its left and right children will be at positions (row + 1, col - 1) and (row + 1, col + 1) respectively....
In your final loop, you can just add a call to sort on the inner vector (that corresponds to a certain horizontal distance and certain level). It is in that vector you could get overlapping nodes. So: for(auto i: nodes){ for(auto j: i.second){ sort(j.second.begin(), j.second.end()); ...
73,029,309
73,029,519
Passing shared_ptr through 2 layers of methods?
What is the most efficient way to give a shared_ptr<void> to an object that passes it to another private method before being stored in it's final destination? It's difficult to describe... maybe asking with code will illustrate the question better: class Example{ public: void give(std::shared_ptr<void> data) { /...
An objective standard is needed for defining a "most efficient way". You clarified that you consider just one reference counting increment. I would suggest a slightly non-intuitive solution which does exactly this: #include <memory> class obj {}; class Example { public: void give(std::shared_ptr<obj> data) {...
73,029,621
73,029,739
Add a source directory to a Makefile
I have the following makefile: CPP_COMPILER = g++ CPP_COMPILER_FLAGS = -g -O0 -Wall -Wextra -Wpedantic -Wconversion -std=c++17 EXECUTABLE_NAME = mainDebug CPP_COMPILER_CALL = $(CPP_COMPILER) $(CPP_COMPILER_FLAGS) INCLUDE_DIR = include SOURCE_DIR = src1 BUILD_DIR = build CPP_SOURCES = $(wildcard $(SOURCE_DIR)/*.cpp) ...
Look at how you use SOURCE_DIR: SOURCE_DIR = src1 ... CPP_SOURCES = $(wildcard $(SOURCE_DIR)/*.cpp) CPP_OBJECTS = $(patsubst $(SOURCE_DIR)/%.cpp, $(BUILD_DIR)/%.o, $(CPP_SOURCES)) ... $(BUILD_DIR)/%.o: $(SOURCE_DIR)/%.cpp $(CPP_COMPILER_CALL) -I $(INCLUDE_DIR) -c $< -o $@ After you define it, you use it three time...
73,029,858
73,029,944
C++ - Does passing by reference utilize implicit conversion?
I am trying to get a better understanding of what "passing by reference" really does in c++. In the following code: #include <iostream> void func(int& refVar) { std::cout << refVar; } int main() { int val = 3; func(val); } How does func taking in a reference change the behavior of val when func is called...
Why don't you just try it? https://godbolt.org/z/8or3qfd5G Note that the compiler could do implicit conversion and pass a reference to the temporary. But the only (good) reason to request a reference is to either store the reference for later use or modify the value. The former would produce a dangling reference and th...
73,030,051
73,030,093
How to query multiple lines of DNS TXT data using WinAPI
I'm trying to get DNS TXT data: #include <Windows.h> #include <WinDNS.h> #include <winsock.h> #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "Dnsapi.lib") #include <iostream> #include <string> using namespace std; const std::string dnsAddress = "8.8.8.8"; int main() { IP4_ARRAY dnsServerIp; dnsServe...
DNSQuery can return multiple records, each with multiple strings. You need to enumerate the list of returned records as well as the strings within them. DNS_RECORD* pResult = dnsRecord; while (pResult != nullptr) { if (pResult->wType == DNS_TYPE_TEXT) { DNS_TXT_DATAW* pData = &pR...
73,030,292
73,038,110
How to Run File Explorer From C++ Program and Show Only Certain Files on Windows?
I'm sorry if this question sounds a bit vague. I am making a windows 11 application in C++, and I am making an editor where I want there to be an option to upload a file of a certain type. Let's say there is a button to upload a file type; I want the file explorer to open with only the files of the chosen type to be sh...
The classic open dialog allows you to filter by file extension(s): WCHAR buffer[MAX_PATH]; OPENFILENAME ofn = {}; ofn.lStructSize = sizeof(ofn); //ofn.hwndOwner = ...; ofn.lpstrFilter = TEXT("Only text and log files\0*.TXT;*.LOG\0"); ofn.lpstrFile = buffer, ofn.nMaxFile = MAX_PATH, *buffer = '\0'; ofn.Flags = OFN_EXPLO...
73,030,556
73,032,427
Determining size at which to switch from stack to heap allocation for multidimensional arrays
I am developing a C++ library focused on multidimensional arrays and relevant operations involving these objects. The data for my "Tensor<T,n>" class (which corresponds to an n-dimensional array whose elements are of some numeric type T) is stored in a std::vector object and the elements are accessed via indices by cal...
A std::vector has a constant size and allocates the actual data always on the heap. So no matter what matrix size you have the Matrix class will be constant size and always store data on the heap. If you want a heap-free version then you would have to implement a Matrix with std::array. You could use if constexpr to ch...
73,030,830
73,059,267
shark failing to compile: static assert failed _DISABLE_EXTENDED_ALIGNED_STORAGE
I followed the installation guide with Visual Studio 2022 as described here. I am able to clone from git and then use cmake to produce a VS2022 sln file. However, when I attempt to build that solution in VS2022, I get the following error: Severity Code Description Project File Line Suppression State Error C2...
Seems like Shark has left it to the person compiling the it to choose weather to define _ENABLE_EXTENDED_ALIGNED_STORAGE or _DISABLE_EXTENDED_ALIGNED_STORAGE. I chose the latter.
73,030,968
73,031,761
Can C++20 concept be used to avoid hiding template function from base class?
I want to use template specialization to query component of a derive object. The code below works fine. However, I am new to C++. I am not sure if such compiler behavior is reliable, and want some confirmation. #include <type_traits> class B{ public: template<class T> T* get() requires std::is_same_v< T, B>{ //... [...
This is specified in namespace.udecl#14, emphasis mine, When a using-declarator brings declarations from a base class into a derived class, member functions and member function templates in the derived class override and/or hide member functions and member function templates with the same name, parameter-type-list ([d...
73,031,061
73,031,296
How to get more kernel memory
I'm making a custom operating system, and I'm running into some memory issues. Recently I've had issues such as this: I've attributed characters not appearing on screen to there not being enough kernel memory, as this runs from kernel. I'm very new to asm, c++, and OS development as a whole so there could be a lot of ...
Your boot loader only loads 2 sectors (1024 bytes) of the kernel into memory. You could increase this a little (temporarily) by changing the mov dh, 2 to a larger value at line 15 of boot.asm. This has limits (e.g. limited to 255 sectors, and possibly limited by the number of sectors per track on the disk). To break th...
73,031,354
73,031,587
Why c++ static member was not initialized in this case?
registerT is not called and the function was not registered in the map. I have no clue. This is the code. //factory.h #include <iostream> #include <memory> #include <string> #include <unordered_map> #include <cstdlib> #include <cxxabi.h> template <typename BaseType, typename... Args> class Factory { public: static ...
First of all, the compilation command is wrong. The -L option expects a path to a directory containing libraries which are specified later. I am not sure what you are attempting by using it here, but as a result you are not linking the derive translation unit. .o files should simply be listed like source files, e.g. g+...
73,032,461
73,032,707
Connect C++ signal to QML slot
I'm trying to connect a C++ signal with a QML slot. The C++ signal is called userRegistered() and the QML slot is called userRegisteredQML(). In the C++ file, I have the following: QQuickView view(QUrl::fromLocalFile("interface.qml")); QObject *topLevel = view.rootContext(); connect(myClass, SIGNAL(userRegistered()),...
Expose your object to QML in C++: topLevel->setContextProperty("myClass", myClass); In QML, you can use Connections: Connections { target: myClass userRegistered: { // do something with it here } }
73,032,796
73,194,849
How can I wait for all data to be written before the serial port connection is terminated
I need to send data from my QT application via serial port. I am trying to send data in this way. void productDetail::on_detailSaveBtn_clicked() { if (!serial.isOpen()) { if (serial.begin(QString("COM3"), 9600, 8, 0, 1, 0, false)) { serial.send(ui->productDesp->text().toLatin1()); ...
Try to wait a few time so a portion of data can be written. Check if any left with while loop and repeat the process. serial.send(ui->productDesp->text().toLatin1()); while(serial.bytesToWrite()){ serial.waitForBytesWritten(20); } serial.end();
73,033,106
73,033,265
gcc linker: undefined reference to a symbol while target lib only contains a superclass method
I'm having repeatedly a linker error in Qt-Project containing a local Installation of Qt 5.14.2 and OpenCV 4.3 and a gcc 11 (fedora 35, x64) and in the last step bringing everything together there might be something off or not fit together: This is the last call out of the make system together with the error: g++ -Wl,-...
The QPushButton::hitButton override exists in the latest Qt 5 (which is 5.15 at the time of writing), but did not yet exist in Qt 5.14. It looks like your OpenCV build was compiled with a newer set of Qt headers than the version you're linking with. Presumably these came from your system, since Fedora 35 ships with Qt ...
73,033,362
73,033,548
Using multiple structs in a function c++
So i want to make a quiz program with structs. I have the question, options and the answer in a struct. But i have multiple questions(structs) so i wrote a function to nicely format the input and output. But seems like it doesn't work because i can't use variable struct in functions. Here's the code: #include <iostream...
You don't need to create a separate class-type for each question when you can create a single Question class with appropriate data members and then pass instances of that Question class to the function quiz as shown below: //class representing a single question struct Question{ std::string question; std::string...
73,033,460
73,034,060
Is it possible to generate multiple custom vertices using the Bundle Properties from Boost Graph Library?
I'm trying to generate an application that solves the bipartite assignment problem via the auction algorithm with the boost graph library. I found it possible to characterize vertices and edges with multiple properties using the boundle properties. But since the auction algorithm envolve two types of entities, persons ...
This question is overly broad, but let me try to provide some helpful pointers. But since the auction algorithm [i]nvolve two types of entities, persons and items, I was wondering if there was the possibility of generating more than one characterization of vertices in order to suppor[t] this distinction. It think "Bu...
73,033,734
73,505,351
Show QWidget as focused
I've got four QLineEdit placed inside of a QLineEdits, where I want the first the parent to look as if it is in focus when any of the containing ones is selected. Note: I don't want the focus to actually change, just the "focus frame" (the thin blue border) to appear on the parent LineEdit. I've tried to draw a rect, b...
Here's how to do it. Its a very basic class that draws the focus frame if any of the childs have focus. On focus change, we do an update (which can probably be optimized a bit to avoid unnecessary repaints). Screenshot: class IPEdit : public QWidget { public: IPEdit(QWidget *parent = nullptr) : QWidget(par...
73,034,238
73,034,562
Check if class is derived from templated class
I'm trying to check if a class that I'm templating is inheriting from another templated class, but I can't find the correct way to do it. Right now I have the following: #include <iostream> template <typename MemberType, typename InterfaceType> class Combination : public InterfaceType { public: Combination(); ...
This can easily be done with the C++20 concepts. Note that it requires a derived class to have exactly one public instantiated base class. template <typename, typename InterfaceType> class Combination : public InterfaceType {}; class MyInterface {}; class MyMember {}; class MyCombination : public Combination<MyMember...
73,034,411
73,034,644
Why a reference declaration influences my pointer?
Case 1 #include <iostream> using namespace std; int main() { int n = 1; // int & r = n; int * p; cout << &n << endl; cout << p << endl; return 0; } Output 1 0x7fffffffdc94 0 Case 2 #include <iostream> using namespace std; int main() { int n = 1; int & r = n; int * p; cout << &n...
Shouldn't an unintialized pointer point to some random places? No, an uninitialized pointer points nowhere. It has an indeterminate value. Trying to read and/or print this indeterminate pointer value as you are doing in cout << p << endl; has undefined behavior. That means there is no guarantee whatsoever what will ...
73,034,418
73,035,627
How can I print descending numbers on left side and ascending numbers on the bottom side of a box?
I have written codes to print a box with # outline but I am trying to print out a box which looks something exactly like that instead: # # # # # # # # # # # 8# # 7# # 6# # 5# # 4# # 3# # 2# ...
I am very sorry. But I have to do this . . . There are that many potential solutions and here is one of them: #include <iostream> #include <string_view> constexpr std::string_view box(R"( # # # # # # # # # # # 8# # 7# # 6# # 5# # 4# ...
73,034,442
73,034,528
how to work with deleted object on custom vector
I know that std vectors can work with objects that are not default constructible. However, when I try to implement a slightly modified one myself, I cant seem to make such vector. class A { public: A() = delete; A(const int &x) :x(x) {} private: int x; }; template <typename T...
The problem is here Array = new T[Capacity]; which default constructs T objects. std::vector uses placement new to construct objects when they are added to the vector. Array = (T*)operator new(sizeof(T)*Capacity); and (when you add the new item) new(Array + i) T(...); // placement new where ... are the arguments you...
73,034,718
73,034,955
Difference between using "struct S" or "S" as typename
In the C language the name of a structured type S ist struct S. In C++ one can also use struct S as typename instead of S as usual for struct S {}; struct S s1; // also ok in C++ S s2; // normal way in C++ So, the assumption is, that using struct S or S as typename in C++ is a matter of taste ;-) But in the following...
the assumption is, that using struct S or S as typename in C++ is a matter of taste ;-) The above assumption is wrong as there are exceptions to it(as also noted in your example) and the reason has more to do with C compatibility than a matter of taste. The point is that there are rules for when we can/cannot use str...
73,035,273
73,047,493
C++ Ignore string argument
I have built a program that create,insert a text into .txt file and now I need to add a small feature where I need to write a function that displays list of files in the directory. int main() { display_duration_start(); std::string VALID_COMMANDS[] = {"CREATE_FILE;","APPEND_TEXT;","DISPLAY_FILE;"}; i...
You can define a list of commands which don't need arguments and check it together with the presence of arguments. The code below should make the work int main() { //display_duration_start(); std::string VALID_COMMANDS[] = { "CREATE_FILE;","APPEND_TEXT;","DISPLAY_FILE;" }; std::string NO_ARGUMENT_COMMANDS...
73,035,275
73,246,993
undefined reference to `xlCreateBookW'
While using the libxl library in QT(c++) I got this error undefined reference to `xlCreateBookW' I have tried the setup in their website, https://www.libxl.com/setup.html I added : INCLUDEPATH = C:\libxl-4.0.4.0\include_cpp LIBS += C:\libxl-4.0.4.0\lib\libxl.lib to my project.pro and the file bin/libxl.dll to the ...
i solved the problem actually the customer support guy i emailed him, he told me to choose the bin which has the same version of my compiler (mine is 64bit) so you have to choose the bin and the lib also the same version and the path: for my case (Qt_6_2_3_MinGW_64_bit compiler ) INCLUDEPATH = C:/libxl-4.0.4.0/include_...
73,035,549
73,041,874
QT C++ Ask to user before close window
I have 2 pages, a homepage, a settings page. I open the settings page on mainwindow. when the user wants to close the settings page. I want to ask the user if you are sure you want to log out. How can I ask such a question to just close the settings page without the app closing? Mainwindow is my homepage
This is what I do in my preference dialog: PreferencesDialog::PreferencesDialog(QWidget *parent) : QDialog(parent, Qt::Tool) { ... QDialogButtonBox* buttonBox = new QDialogButtonBox(this); buttonBox->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::RestoreDefaults); butto...
73,035,602
73,065,655
How do you wait for `QtConcurrent::run` to finish without thread blocking?
Hey this should be a pretty straightforward question. Simply put: Want to run a function in another thread. Need to wait for the function to finish. Do not want to freeze the thread though while waiting. In other words, I'd like to use an eventloop. Here is the freezing example: extern void sneed() { QEventLoop w...
The solution comes from a simple class called QFutureWatcher: doc.qt.io/qt-5/qfuturewatcher.html Here is some sample code for running lambda's in a different thread, and receiving its value. template <class T> auto asynchronous( auto &&lambda ) { QEventLoop wait; QFutureWatcher<T> fw; fw.setFuture( QtConcur...
73,036,208
73,036,251
Is there any difference between empty derived class and using?
I'm writing a library whose functionalities are provided in a C-compatible header like the following: // File: bar.h typedef struct bar_context_t bar_context_t; #ifdef __cplusplus extern "C" { #endif bar_context_t* bar_create(); void bar_destroy(bar_context_t*); int bar_do_stuff(bar_context_t*); #ifdef __cpl...
Neither is necessary (and I don't even think your first variant works; using is just C++ syntax sugar, and does not introduce a type). You just declare bar_context_t to be a pointer to bar::Context; that's it. In C, you declare it to be a void*, since C has no type safety anyways.¹ ¹strictly speaking, C has type safet...
73,036,283
73,036,323
Sometimes the using namespace std; is inside main or other functions?
Usually when someone declares using namespace std; (I know that it is a bad habit), They should declare it like that: # include <iostream> using namespace std; int main() { // Some code here... return 0; } But it is a completely different story here. The using namespace std; is sometimes located in int main()...
The using for namespaces statement pulls in all symbols from the namespace into the current scope. If you do it in the global namespace scope then all symbols from the std namespace would be available in the global (::) namespace. But only for the current translation unit. If you do using inside the function, or even a...
73,036,402
73,036,628
Efficient way to XOR two unsigned char arrays?
I am implementing an encryption algorithm and was wondering if there was a more efficient way than O(n) for xoring two unsigned char arrays? I essentially want to know if it's possible to avoid doing something like this: unsigned char a1[64]; unsigned char a2[64]; unsigned char result[64]; for (int i=0;i<6...
As the comments note, the only way of doing this faster than O(n) is not doing it for all elements, In fact, don't do it for any elements! The reason is that you're writing a cryptographic algorithm. You'll use results[i] a few lines lower. That part will likely be numerically expensive, while this XOR is limited by me...
73,036,566
73,037,361
Understanding syntax of function parameter: vector<vector<int>> A[]
I'm solving a question where a function is defined as following: vector <int> func(int a, vector<vector<int>> B[]){ // Some stuff } I'm confused about why the second parameter is not simply vector<vector<int>> B. Why the extra [] part in the parameter? Can someone clarify the meaning of this? The vector, B, is pop...
Just as int foo(char str[]) is a function that takes a (c-style) array of characters, so int foo(vector<vector<int>> B[]) takes an array of vectors of vectors ... of integers. This means that it's three-dimensional data, requiring 3 indices to access the elements (fundamental data type; in this case, int), like B[i][j]...
73,037,605
73,621,458
A missing header from a repository which is linked to a shared library that is linked to my project, using cmake
I have a GitHub repository containing two cmake projects. Lets say the name of the repo is "Audio" and it contains a directory "AudioGui" and a directory "AudioLib". The "AudioLib" project is a shared library which includes and links a header from another GitHub repository. AudioLib can be built and its cmake contains:...
Since AudioFile is a third party library for the client programs, AudioFile.h must not be included in AudioLib's headers (a pointer and a forward declaration of AudioFile should be used instead in order to not having external dependencies). You can see the full CmakeLists files here: https://michae9.wordpress.com/2022/...
73,038,129
73,038,421
Change value of randomly generated number upon second compilation
I applied the random number generator to my code although the first number generated doesn't change when I run the code second or the third time. The other numbers change however and the issue is only on the first value. I'm using code blocks; Cygwin GCC compiler (c++ 17). Seeding using time. #include <iostream> #incl...
Per my comment, the std::mt19937 is the main PRNG you should consider. It's the best one provided in <random>. You should also seed it better. Here I use std::random_device. Some people will moan about how std::random_device falls back to a deterministic seed when a source of true random data can't be found, but that's...
73,038,464
73,039,069
Most efficient memory order to increment an integer
I have N threads, which operates 1 variable of std::atomic type. Like this: std::atomic<int> Num = 0; void thr_func() { Num.fetch_add(1); } Here, the default memory order is memory_order_seq_cst, which is not most efficient. Which memory order and why i should use to get the most effective code and also have a c...
std::atomics are not only about consistent state of themselves, but also about consistent state in the surrounding code. Say for example, that you use an atomic integer to store the number of items in an array. You will probably end up writing something like the following: std::atomic<int> len; ... array[len] = some_n...
73,038,670
73,038,811
Why are there duplicate C/C++ compilers (e.g g++, gcc)?
According to this answer, gcc and g++ have some functional differences. As confirmed by this script, the commands point to the exact same binary, effectively making them duplicates. Why is that so? $ uname Darwin $ md5 `which cc c++ gcc g++ clang clang++` fac4668657765c8dfe89d8995acfb5a2 /usr/bin/cc fac4668657765c8dfe...
The executable can determine the name it was called with by inspecting the first (or zeroth) command line argument passed to it. By convention it is the name of the executable and is passed by whatever program is invoking the compiler (typically e.g. a shell). Although it is the same executable, it can then take differ...
73,038,673
73,042,882
What will the order of slot execution if two signals are emitted at the same time in same thread?
I am trying to understand the code of HMI (QT based application). Typically in a embedded software, multiple ECUs send data at the same time to the UI. In which order 2 different slots (2 different UI classes) connected to 2 different signals, be executed if both the signals are triggered at same time within the same t...
UI classes should be typically handled in your main thread and only heavy computation that can block the UI in worker threads. So, by default, you would get them executed subsequently, and cannot certainly be in parallel in an ideal design. Yes, you are right, there is no parallelism with a single thread. Even with mul...
73,039,528
73,039,594
c++ array[] vs malloc(). are these 2 vriables the same?
Here we have arr1 and arr2... int arr1[3]{}; int *arr2 = (int *)std::malloc(size_t(int) * 3); and i think entities of arr2 should be stored in the heap compared to the arr1 that is stored in the stack memory. question: Is there any reason to use arr2 if its not going to get bigger or smaller during the code?
The memory held by arr1 is guaranteed to be allocated only in it's scope. The memory arr2 points to is yours till you free() it (or exit the program), thus you might pass it as a return value, store it, etc. Also, arr2's allocation likely takes more bytes in practice, as memory allocation usually maintains blocks of fr...
73,039,817
73,040,635
How to wrap a shared pointer of a template class function in Pybind11
I want to wrap a shared pointer of a template class function in Pybind11. My class is a template queue : MyQueue.hpp template<typename Data> class MyQueue { public: std::queue <Data> the_queue; static std::shared_ptr<MyQueue<Data>> make_data_q_ptr(); }; MyQueue.cpp template<typename Data> std::sha...
Move template<typename Data> std::shared_ptr<MyQueue<Data>> MyQueue<Data>::make_data_q_ptr(){ std::shared_ptr<MyQueue<Data>> data_q_ptr; data_q_ptr = std::make_shared<MyQueue<Data>>(); return data_q_ptr; } into your header file. It isn't visible at the point that needs to see it.
73,040,489
73,040,507
Why not use the root of the trie?
I'm trying to understand this program, why do they have to make Trie* pCrawl = root, why don't they just use the root of the tree and insert directly to it: void insert(struct TrieNode *root, string key) { struct TrieNode *pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i]...
I don't think pCrawl is needed. The argument root is a copy of what is passed and modifying that won't affect the caller, so it is free to modify the value of root in the function. It may be for clarity gained by using clear names for the argument (for input) and variable (for processing).
73,041,146
73,041,247
Linux gRPC & Conan Version incompatibility
I am trying to use gRPC to create a simple rpc mechanism for a project. I started by cloning gRPC from github and selecting the tag for version 1.47.1. I built and installed this on Ubuntu as per the instructions, by pulling from GitHub and selecting the tag for v1.47.1 I then created a simple file, e.g. // Latest prot...
You can either override the protobuf version in your conan recipe to 3.19.4 or probably better to update the git submodule in grpc/third_party/protobuf to 3.21.0: cd grpc/third_party/protobuf git checkout v3.21.0
73,042,171
73,042,767
why add_subdirectory() command did not work for my CMakeLists.txt?
I have a simple exercise on cmake with following file tree: proj01/ include/ functions.h src/ main.cpp functions.cpp CMakeLists.txt CMakeLists.txt README My project CMakeLists.txt is like this: cmake_minimum_required(VERSION 3.21) project (te...
add_subdirectory(src) results in cmake parsing src/CMakeLists.txt creating a new directory src in the build tree for building the part of the project in this cmake file. It doesn't result in you being able to use shorter paths in the CMakeLists.txt file containing the add_subdirectory command. If you move the target to...
73,042,277
73,042,393
How to use a char after the double colons of enum that resolves to one of the enum's values
I'm reading values from an input text file that I have no control over. The first line is an integer representing the number of the lines to follow. Each of those lines to follow contains one of 3 characters that can be found in the next enum: enum Size { S, M, L } The ifstream can't insert the value direc...
Enumerations have an underlying integral type with which the enumerators are represented. You can specify which integral value each enumerator should have explicitly. Since character literals are just integral values, you can specify them as well. Then you can simply cast from any integral type to the enumeration type ...
73,042,385
73,042,579
Project Euler #10 [C++] sum of primes below 2000000
Prompt: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. Code: #include <iostream> #include <list> /** * @brief Searches for numbers that in a that can be factored by b * * @param a list of numbers * @param b factorable number */ void search(std::list<long l...
In fact there is no need to define a list to calculate the sum of prime numbers. Nevertheless if to use your approach then within the function search after the statement a.erase(it); the iterator it becomes invalid. You should write while (it != a.end()) { if (*it % b == 0 && *it != b) { it = a.erase(it); ...
73,043,451
73,043,650
Upcasting through std::any
In C++ you can pass instances of Derived to functions accepting Base, if Base is a base class of Derived. This is very useful for satisfying APIs and a very common design pattern for APIs. Currently I am faced with a situation, where I want to upcast through an std::any. That is I have an std::any that stores an instan...
any is a type-safe void*. That means it obeys the rules of a void*. Namely, if you cast a T* to a void*, the only type you can cast it back to is T*. Not to a U* where U is a base class of T. It must be exactly and only T*. The same goes for any. any (like this use of void*) is for situations where code A needs to comm...
73,043,455
73,043,534
Function to check if a string is an ANSI escape sequence?
I need a C++ function (or object) able to tell me if a certain string is an ANSI escape sequence. So, if I have for example: std::string ansi = "\033[0m"; I would need something like this: is_escape_char( ansi ) which returns false or true if the string is an ANSI escape sequence. Is it possible?
If you know it's at the start of the string bool is_escape_char(std::string_view str) { return str.starts_with("\033"); } Otherwise look for it anywhere in the string bool is_escape_char(std::string_view str) { return std::string_view::npos != str.find("\033"); } Depending on what you need, you can capture the ...
73,044,313
73,048,238
How to avoid code copying in this class hierarchy?
I have the following class hierarchy, in which the instantiation of class B has to be static in both child classes: #include <iostream> class A { protected: virtual int get_num() const=0; }; class B { int num; public: int get_num() { return num=2; } }; class D1 : public A { public: static B b; int g...
If you have several classes that all have a B member and delegate some functionality to it, you should extract this bit into a common base class. If it is not a static member you would do just this: class Awith B : public A { public: int get_num() override { return b.get_num(); } private: ...
73,044,391
73,045,469
Overload macro as variable and function
First, there are a lot of posts on overloading macros: Can macros be overloaded by number of arguments? C++ Overloading Macros Macro overloading Overloading Macro on Number of Arguments etc. ... However, all of them ask the question about variadic macros. What I'd like to ask is if the following is possible: #define ...
It's not a macro, but looks like it struct SmartMacro { constexpr operator int() const noexcept { return 3; } constexpr int operator()(int a, int b) const noexcept { return a + b; } }; constexpr SmartMacro FOO; int main() { int a = FOO(0,1); int b = FOO; std::cout << a + b; return 0; }
73,044,484
73,045,387
MSVC won't perform a user-defined implicit conversion to std::nullptr_t when invoking operator==
Consider the following piece of code: struct X { operator std::nullptr_t() const { return nullptr; } }; X x; assert(x == nullptr); As far as I can tell, it should work because X is implicitly convertible to std::nullptr_t and hence operator== should perform that implicit conversion to the left argument. This seems to ...
MSVC is wrong in rejecting the code since the program is well formed as the implicit conversion via the conversion operator can be done for the check x == nullptr. A bug report for the same has been submitted here.
73,044,691
73,044,849
How boost format works in terms of c++?
I was looking at boost::format documents and just the first example made me wondering: cout << boost::format("writing %1%, x=%2% : %3%-th try") % "toto" % 40.23 % 50; What does it mean in terms of c++? I can understand call to boost::format itself, there's nothing strange there, but what's the meaning of the rest? %...
%, like many operators in C++, can be overloaded for arbitrary types. If we have the expression a % b where a is of type A and b is of type B, then C++ will look for functions compatible with the following signatures. R operator%(const A& a, const B& b); R A::operator%(const B& b) const; So, presumably, boost::format ...
73,044,955
73,045,022
How do I find out entry-point function in C++ dll project?
I built one project from GitHub. The project was built successfully, but I can't find the entry-point function in its code. The project settings are like this: How do I find out the entry-point function in a C++ DLL project?
Per /ENTRY (Entry-Point Symbol): By default, the starting address is a function name from the C run-time library. The linker selects it according to the attributes of the program... Unless specified differently, the entry point for a DLL in a MSVC++ project is _DllMainCRTStartup(), which calls DllMain() in the projec...
73,045,075
73,045,216
Why a portion of my Array output a value different from what i extracted(c++)?
data11.txt: Length(l) Time(t) Period(T) 200 10.55 0.527 300 22.72 1.136 400 26.16 1.308 500 28.59 1.429 600 31.16 1.558 ill be taking data from this file above in my code #include <iostream> #include <cmath> #include <fstream> #include <string> #include <iomanip> /*Using data11.txt as ...
What you have noticed is called 'buffer overrun'. float Length[n], Time[n], Period[n], acc_gravity; // since 'n' is 4, // so the valid range of subscript of Length/Time/Period are [0-3] // That means, if you try to write to Length[4], // that is invalid, often lead to ruin something else. ...
73,045,134
73,045,205
SetWindowText with a String and Integer
I'm running a threaded application and monitoring the duration with chrono. What I'm trying to do is then set the window title to say "Duration: " + the time taken. This is what I have so far but it just makes the window title blank. // Calculate Duration int duration = std::chrono::duration_cast<std::chrono::milliseco...
First, there's an issue where you're using pointer arithmetic and expecting string concatenation plus integer-to-string conversion. The value "Duration: " + duration is going to be a pointer that is offset from the start of the "Duration: " string literal by duration bytes. If that is any value outside the range [0,10]...
73,045,566
73,045,621
How to retrieve the new integer data after completion of a call to Document().Set(MapFieldValue{string_key, Increment()}) in Firestore C++
I'm attempting to atomically increment integer values in Firestore and read the value on the client side after the Set() operation is complete on the server side, with the guarantee that another Set() call won't overwrite the value on the server before the value is retrieved for the client. Without this guarantee it se...
The increment operator does nothing more than ensure the increment happens atomically on the server, and does not involve any transfer of values to/from the client. If you want full control over the order of the operations, including the read, you probably want to use a transaction to accomplish that.
73,045,735
73,047,277
Intuition on C++ situations where an an unknown number of objects of a custom class will be needed at runtime
Everything below has to do with situations where a developer makes a custom C++ class (I have in mind something like OnlyKnowDemandAtRuntime below)... and there can be no way of knowing how many instances/objects "the user" will need during runtime. Question 1: As a sanity check, is it fair to say that in Case One belo...
Not to your literal questions but you might find this useful. Smart pointers like std::unique_ptr are most basic RAII classes. Using RAII is the only reasonably sane way to ensure exception safety. In your particular example, I’d use std::unique_ptr<Node> specifically. With arbitrary graph that’d be more complicated o...
73,045,806
73,045,864
How to exit the loop :while(cin>>n) in C++
This is a program that counts how many letters and numbers a string has,but when I Press Enter to exit after entering,it has no response. #include <iostream> using namespace std; int main() { char c; int nums=0,chars=0; while(cin>>c){ if(c>='0'&&c<='9'){ nums++; }else if((c>='A'...
Pressing enter does not end input from std::cin and std::cin stops when encountering a whitespace. Better would be to use std::getline and std::isdigit as shown below: int main() { int nums=0,chars=0; std::string input; //take input from user std::getline(std::cin, input); for(const char&c: in...
73,046,198
73,046,678
How to Store Variadic Template Arguments Passed into Constructor and then Save them for Later Use?
I am curious how one would go about storing a parameter pack passed into a function and storing the values for later use. For instance: class Storage { public: template<typename... Args> Storage(Args... args) { //store args somehow } } Basically I am trying to make a class like tuple, but where you don'...
Since run will return void, I assume all the functions you need to wrap can be functions that return void too. In that case you can do it like this (and let lambda capture do the storing for you): #include <iostream> #include <functional> #include <string> #include <utility> class FnWrapper { public: template<type...
73,046,506
73,046,699
Standard library naming convention: Why is the counterpart of std::search called std::find_end?
I was looking at the different algorithms for finding/searching in the standard library and was wondering about the strange naming conventions used. In particular the distinction between the family of search and find algorithms. For example: std::search searches for the first occurrence of a subrange in the input range...
The reason: the algorithms are different. search moves forward by the interval and searches the first occurrence. find_end also moves forward by the interval and finds the last of all occurrences. It uses search and returns the last positive result. Literally, finding is the completion of searching.
73,046,900
73,046,955
C++ set slower than Java TreeSet?
I was working on leetcode problem 792. Number of Matching Subsequences, and one of the initial solutions I came up with was to create a list of ordered sets. Then we can determine if a word is a subsequence of string s by trying to find the ceiling of the next available character of string word using the current index ...
There is definitely some copying happening in the C++ version that isn't happening in the Java version. For instance st could be a reference set<int>& st = alpha[word[i++] - 'a'];
73,047,154
73,047,472
initializer_list constructor somehow excluded from std::variant constructor overload set
Help me solve this puzzle: In the following code I have an std::variant which forward declares a struct proxy which derives from this variant. This struct is only used because recursive using declarations are afaik not a thing in C++ (unfortunately). Anyway, I pull in all the base class constructors of the variant whi...
Your proxy class does not have a declared constructor that accepts a std::initializer_list<proxy>. What it has, is a constructor template that accepts any type, T. But for that template to be chosen, the compiler has to deduce the type of T. The braced-init-list {1,2,3,2.5,{1,2}} does not have any inherent type thou...
73,047,874
73,047,952
heap-use-after-free when using references with 2D vector in C++
I am solving this problem on leetcode: https://leetcode.com/problems/merge-intervals/ When I go to submit my solution, I get the error of AddressSanitizer: heap-use-after-free. More specifically, there is an error of Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) when I hit the line of code currentMergedInterval = merg...
References can't be reassigned. Assigning to a reference variable will not change the reference, it will change the object being referenced. Because of this, and because of adding elements to a vector might invalidate all references, pointers or iterators to elements, the two statements mergedIntervals.push_back(interv...
73,048,442
73,103,481
MyProject.dll is not a valid win32 application
I have copied a C++ solution folder written with visual studio 2013 to my Pc and tried to run it (I mean VS Debugging) with VS 2022. the solution Contains 5 projects but I just target one of them so unloaded the rest and set the one as Startup project and this error happened. Error Image Solution file is working well o...
Project properties the "Configuration Type" was mistakenly changed to .dll.
73,048,657
73,048,736
Can a base class access a derived class protected member in c++?
I'm trying to get my base class currency. To access and return the string from it's derived class pound. My instructor specifically said it's a non public type (so I'm assuming a protected member would be the best here) and to NOT declare it in the base class. I'm having trouble making a function string getCurtype()to ...
Your design is backwards. Base classes should not need to know about derived classes other than the interface defined in the base. Define the interface you want to use in the base: class currency{ public: virtual string getCurType() = 0; void print(){ cout << "You have " << getCurType() << en...
73,048,664
73,048,861
What is QT_TRANSLATE_NOOP_UTF8 for in Qt?
I cannot find any official documentation about QT_TRANSLATE_NOOP_UTF8 macro. How does it works and what is "scope" argument? Is it namespace? And if it is, how to specify nested namespaces?
I've found documentation for it (it is hard to find but it is documented): - Global Qt Declarations | Qt Core 6.3.2 QT_TR_NOOP(sourceText) Marks the UTF-8 encoded string literal sourceText for delayed translation in the current context (class). The macro tells lupdate to collect the string, and expands to sourceText ...
73,048,675
73,076,709
Automate memory search in dump
I have full dump and want to search across custom made doubly linked list of 6+ millions elements. To make is simple consider that element of list contains data that is type integer. Is that way to find (automate) if there is element with specific value. I'm using Visual Studio 2017 Professional, so action "Debug Manag...
I have used WinDbg Preview tool to sovlve this. It's free tool made by Microsoft. It can run JavaScript to analyze memory, and probably much more. Template JS code list iteration : "use strict"; function read_next(addr) { return host.memory.readMemoryValues(addr, 1, 8)[0]; } function read_data(addr) { return ...
73,048,832
73,049,415
Unable to locate package g++-arm-linux-androideabi
I have a JNI module and I'm trying to cross compile with GitHub action and the org.codehaus.mojo:native-maven-plugin maven plugin, so I wrote the following workflow that worked before I added the installation of the package arm-linux-androideabi-g++ that the docker image can't find: elaborate-native-module: name:...
Try with sudo apt-get -y install g++-aarch64-linux-gnu g++-arm-linux-gnueabi. The related compilation executable is arm-linux-gnueabi-g++
73,049,169
73,049,356
No Member Named Reverse While Using reverse()
class Solution { public: void print (vector<int> array) { for (int i=0;i<array.size();i++) { cout<<array[i]<<" "; } cout<<endl; } vector<int> nsr(vector<int> heights) { int n = heights.size(); vector<int> v(n); stack ...
There is no member function reverse in the class template std::vector. So this statement left.reverse(left.begin(),left.end()); is invalid. You should use the standard algorithm std::reverse declared in the header <algorithm> as for example reverse(left.begin(),left.end()); There are other problems with your code. Fo...
73,049,388
73,049,460
Problem with remove function while trying to remove a file from directory in C++
I need to remove a file from a directory based on the input of user and pass it into a function that perform the file remover process /* Class 3 veus 3:45PM*/ #include <string> #include <iostream> #include <stdio.h> #include <cstdio> void remove_file(std::string file); int main() { std::string file_name; std::cin...
use the function with c string instead: void remove_file(std::string file) { std::string x = "C:\\MAIN_LOC\\" + file + ".txt"; if(remove(x.c_str()) == 0) { .... }
73,050,100
73,050,165
Raw int pointer vs vector::iterator<int>
I was trying to understand difference between a raw pointer and an vector iterator. However, the following program trips me out. Does template function have priority over non-template function? Expected: hello! world! Actual: hello! hello! #include <bits/stdc++.h> using namespace std; template<typename It> void foo(It...
In general iterators of the class template std::vector are not pointers (though in some early versions of compilers they were implemented as pointers). For the both calls there will be called the template function. The call of the non-template function requires conversion to const (qualification conversion). The non-te...
73,050,202
73,050,339
Regex not able to show chars after space
I want to break this string into two parts {[data1]name=NAME1}{[data2]name=NAME2} 1) {[data1]name=NAME1} 2){[data2]name=NAME2} I am using Regex to attain this and this works fine with the above string , but if i add space to the name then the regex does not take characters after the space. {[data1]name=NAME 1}{[data2...
A good place to start is to use regex101.com and debug your regex before putting it into your c++ code. e.g. https://regex101.com/r/ID6OSj/1 (don't forget to escape your C++ string properly when copying the regex you made on that site). Example : #include <iostream> #include <string> #include <regex> int main() { ...
73,050,678
73,051,936
Implementing BlockingQueue using Semaphores only
I'm having a trouble with my code design and can't find a solution. I am implementing a BlockingQueue using Semaphores (TaggedSemaphores, to be precise) without loops, condvars, mutexes, and if-else statements. My current code looks like this: template <typename T> class BlockingQueue { using Token = typename Tagged...
This queue works fine. put_mutex_ and take_mutex_ are unnecessary, though, and should be removed. You say that simultaneous threads might be "working with the wrong data", but nobody ever gets the value of empty_ or taken_, so they are not working with this data at all. Code like this is difficult to write, and even ...
73,050,720
73,050,823
What namespace is CWnd in?
My biggest complaint about the MS docs is they don't say what actually contains what class you're looking at. OpenCV is like the gold standard of docs. Tells you the whole function, and what header file it's located in. For those of us that haven't been doing this for 20 years, I don't just know where this is at and it...
CWnd being a legacy MFC class, is not defined in any namespace, and therefore considered as belonging to the global namespace. In order to use it you need to #include <afxwin.h>, as you can see in the documentation.
73,050,958
73,051,979
Can I check the actual type of void*?
I have to use a legacy C library in my C++ code. One of the functions of that library looks like this: int legacyFunction(int (*userDefinedPredicateFunction)(void*), void* structure, otherArgs...); This legacyFunction() calls userDefinedPredicateFunction() inside itself passing structure as argument to it. I have mult...
I think you are on the right path with that wrapper function. You can save yourself some work by making it a template. This should work: using legacy_predicate = int (*)(void*); template<class T> void call_legacy(int (*predicate)(T*), T* obj, int otherargs) { using pair_type = std::pair<int(*)(T*), T*>; pair_t...
73,051,213
73,051,269
Getting out of bounds error at the runtime without any output
#include <iostream> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<int> v{1, 23, 4, 4, 5, 566, 67, 7, 87, 8, 8}; size_t s = v.size(); for (size_t i = 0; i < s; i++) { cout << v.at(i) << " "; v.pop_back(); } ...
Output is buffered. You can use std::endl or std::cout.flush() to force a flush of the stream: for (size_t i = 0; i < s; i++) { cout << v.at(i) << " "; cout.flush(); v.pop_back(); } PS: As mentioned in comments this code is bound to fail. You iterate till i < s but remove an element in each iteration. I su...
73,051,519
73,054,657
Typelist of nested types
I've got a typelist providing the following interface : template <typename... Ts> struct type_list { static constexpr size_t length = sizeof...(Ts); template <typename T> using push_front = type_list<T, Ts...>; template <typename T> using push_back = type_list<Ts..., ...
The question is seemingly looking for map, also called transform in C++. TL is one list of types, and the desire is to apply some type-level function (extract ::type1) and have another list of types. Writing transform is straightforward: template <template <typename> typename fn, typename TL> struct type_list_transform...
73,051,801
73,053,396
extern c template instantiation
I want to write a templated function and explicitly instantiate it inside extern "C" block to avoid code duplication. Here is example of what I mean: template<typename T> // my templated function T f(T val){ return val; } extern "C"{ int f_int(int val) = f<int>; // this does not compile, but this is what I want...
int f_int(int val) = f<int>; is not valid(legal) C++ syntax. The correct syntax to instantiate the function template and return the result of calling that instantiated function with val as argument would look something like: template<typename T> // my templated function T f(T val){ return val; } extern "C"{ in...
73,052,310
73,052,421
Structures with pointers
so I have a structure called Shield that has three pointers in it. I need to fill up with data one of this pointers before hand and I need to access this data inside of a constant loop. The problem that I'm having is that whenever I try and access what should be in my pointers my program crashes. This is my structure s...
This function accepts an object of the type Shield by value. void InitShield(Shield shield){ That is the function deals with a copy of the value of the passed argument. Changing the copy within the function does not influence on the original object. If you are using C++ then declare the function at least like void Ini...
73,052,522
73,052,868
Boolean bitwise and logical operators
I Have two booleans with OR operation between them. According to my understanding, I can use bitwise or logical operators and it will have the same effect: bitwise: bool first = true, second = false; first = first | second; logical: bool first = true, second = false; first = first || second; Is there any difference? ...
As noted in the comments, you should use logical operators when you're doing logic and bitwise operators when doing bitwise operations. One of the main differences among these is that C++ will short-circuit the logical operations; meaning that it will stop evaluating the operands as soon as it's clear what the result o...
73,053,381
73,054,405
Wording of array-to-pointer conversion and undefined behaviour
According to conv.array, array-to-pointer conversion is defined like this (bold emphasis mine): An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion ([conv.rval]) is applied. The result is a pointer to...
The paragraph is just in general imprecise, in my opinion. It doesn't say what "the array" refers to at all. No array has been introduced before, only array types. I guess it should probably state explicitly that it refers to the array object result of the glvalue, after temporary materialization if applicable. Then I ...
73,053,479
73,054,502
Python version mismatch even though CMake reports having found the correct version
I'm building some C++ Python extensions for Python 3.10 (using PyBind11) but I'm finding that when trying to import these extensions I get: ImportError: Python version mismatch: module was compiled for Python 3.8, but the interpreter version is incompatible: 3.10.5. I have find_package(Python3 3.10 REQUIRED) in my CMak...
There may have been other factors at play here (like including 3rd party CMake projects) so to fix my problem the first step was to remove those. Then I: changed my find_package(Python3 3.10 REQUIRED) to find_package(Python3 3.10 REQUIRED COMPONENTS Interpreter Development) (see here). User @Tsyvarev also somewhat all...
73,054,477
73,054,574
Using G++-12 but still c++20 is still not supported
I am using vs code where I run the task in the terminal with following option: g++-12 build active file compiler: /home/linuxbrew/.linuxbrew/bin/g++-12 I am using Ubuntu 20.04 so I installed the g++-12 version using brew and after some manual setup in vs code I make the g++-12 to run the task along with I change the c+...
According to https://gcc.gnu.org/onlinedocs/gcc-12.1.0/gcc.pdf g++ 12.1 is defaulting to -std=gnu++17. The default, if no C++ language dialect options are given, is ‘-std=gnu++17’. If you want C++20 you must specify -std=c++20 or -std=gnu++20 on the command line.
73,055,023
73,059,923
`glog` example is not showing output as expected
I am trying to understand glog and therefore trying to run the example code on their github page. I have installed glog (version - 0.6.0) and its dependency gflags (version - 2.2) on my mac OS (10.15.7) I compile the example below #include <glog/logging.h> int main(int argc, char* argv[]) { // Initialize Google’s ...
You have to parse the command line flags manually through gflags::ParseCommandLineFlags #include <glog/logging.h> #incldue <gflags/gflags.h> int main(int argc, char* argv[]) { // Initialize Google’s logging library. google::InitGoogleLogging(argv[0]); gflags::ParseCommandLineFlags(&argc, &argv, true); ...
73,055,463
73,056,807
Is it possible to make file accesible ONLY for certain processes?
So I'm attempting to make file accesible only for certain process, firstly by finding it via this function: bool GetProcessSid(PSID* pSID) { PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &en...
No, Windows' security is based around user/group access lists. It would be possible to set up a process so that it was running as some particular user and then restrict access to that user, but any program running as Administrator or Local System would be able to bypass that protection. The best you can do against such...