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
66,443,398
66,448,783
Static member function and run time polymorphism
class Base { private: Base() = default; static Base *b; public: static Base* get(); }; class Derived: public Base { }; Base* Base::b=nullptr; Base* Base::get(){Base* b = new Derived();return b;} void main() { Base* b = Base::get(); } I get a compile time error: main.cpp: In static member fu...
By making the Base() constructor private, the Derived() default constructor becomes ill-formed (it tries to call the private Base()), so is implicitly deleted. You then try to use it to construct a Derived, which gives you the error you see. In order to make this work, there needs to be a Derived() constructor -- eith...
66,443,440
66,444,233
C++: Is it defined behavior to typedef nested type with same name?
the code: class Global { public: static const char *name() {return "Global";} }; typedef Global T_Outter; class Outter { public: typedef T_Outter O_Outter; // <= <1> typedef Outter T_Outter; // <= <2> static const char *name() {return "Outter";} static void test() {printf("self: %s, outter: %s\n", ...
It is not allowed to change meaning of a global name inside a class after it was used unqualified in the class definition. The program is ill-formed, NDR. See [basic.scope.class]/2: A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagn...
66,444,541
66,444,842
C++ example code of receiving data from Google Cloud Platform
I want to find a C++ example of receiving data via Google's "cloud" via Google's Pub/Sub. Here it seems that C++ isn't supported: https://github.com/googleapis/google-cloud-cpp/issues/777 and again here: https://stackoverflow.com/a/62573062/997112 But on the main Github page: https://github.com/googleapis/google-cloud-...
The Cloud Pub/Sub client library in C++ recently became available. Code samples in the Pub/Sub documentation should all have C++ examples, for example, publishing messages and receiving messages.
66,444,675
66,444,714
Disabling Ctrl-Z behaviour in `ifstream::getline`
I want to use ifstream::getline to read lines from a file, but the file contains the byte Ctrl-Z (0x1A), which makes getline think that it's reached the end of file (this is in Windows -- in *nix it would be Ctrl-D, if I'm not wrong). Can I disable this behaviour somehow, and tell getline to ignore Ctrl-Z? Just for inf...
This shouldn't happen when your ifstream object is using binary mode. Just create it like this: std::ifstream fin(<path>, std::ios::binary) This of course prevents you from using other features of the stream, but if your main goal is to be able to read all sort of values while ignoring special characters, this is prob...
66,444,724
66,444,827
How to modify an extracted node key from an std::map
In a previous question, I wanted to store some extracted nodes from an std::map into a std::vector<std::map<K, V>::node_type>, using a for loop. Now that I can do that, I'd like to modify the nodes keys before storing them in the vector, and I'm getting a compilation error (not copying the whole error message, it's ver...
Node handles are not copyable. Thus, you cannot create a copy in the vector. Node handles are movable though, which is why the other example works. Moving from a variable can be done using the standard function std::move: tmp.push_back(std::move(node))
66,445,019
66,460,849
What is the best way to load SVG as Cairo image surface?
I have a simple C++ program based on libCairo that is intended to draw some images (e.g. put one image onto another, write some text, and so on). I need to load some SVG files (to avoid scaling artifacts) and then draw them onto a surface that was loaded from PNG. I have a wrapper class that contains a cairo_t context,...
Cairo can write SVG files, but it cannot read them. You need something like librsvg to load SVG files. I just tried to get Google to give me a short librsvg example, but did not find one.
66,445,847
66,447,172
C++ yard.h header getting acreage programmatically
I am relatively new to C++ and it is essentially just a filler class for my college. I am stuck on this yard program. I need to create a header with the requirements below: following 5 public functions in the Yard class: getWidth(), setWidth(), getLength(), setLength(), and getAcres() Validate the width and length to e...
So, here's a yard.h that will answer the teacher's brief. class Yard { const double _dSqFtToAcre = 43560; double _length; double _width; public: Yard(const double& length = 0, const double& width = 0) :_length(length),_width(width) {} void setLength(const double& length) { ...
66,446,228
66,446,759
How to create a cmake header-only library that depends on external non-header-only target?
How to create a cmake header-only library that depends on external header files? is close but different. I have a single-header library, MyHeaderLib. In MyHeaderLib/MyHeader.h I have #include <QString>, so anyone doing #include "MyHeaderLib/MyHeader.h" had better have QString in their path (i.e., Qt5Core to CMake, I th...
Packages are responsible for defining targets. The Qt maintainers chose to name the package Qt5Core while deciding to define the Qt5::Core target. Usually the convention with CMake packages is that a package named package-name will define package-name::package-name with maybe other optional targets or subcomponents of ...
66,446,625
66,447,928
Global hook in DLL loaded in python renders firefox unresponsive, but only if the bitness doesn't match
I am writing a program to control a robotic sample changer, which uses a barcode scanner to check which sample was loaded. The scanner is read as a keyboard, and I want to be able to capture its input and prevent it from showing up as keystrokes in other programs. I used this solution, using ctypes to create the raw in...
Finally found the issue. I was not pumping messages in the python process that was calling the dll. Because of the way windows handles 32bit/64bit dlls and hooks, pumping messages caused an issue only when the bitness was mismatched between processes. In case anyone else runs into a similar problem, here's the old pyth...
66,447,229
66,447,408
How to limit the amount that an integer is increased? c++
In my game there is a troop quality increasing mechanic, however, I can't figure out how to limit the number of new knights, it just converts all of the militia into knights no matter if the training grounds are built of not, how do I cap it at 50 and 10? case 3: if(training){ ...
I changed the code so that when there are too many militia it just gets set to the number that I want so: case 3: case 3: if(training){ int newknights =militia; if(newknights>50){ newknights = 50; } ...
66,447,357
66,447,720
C++ - Google benchmark stop timing function
I'm trying to exclude the conversion of string into an object in a function. This is the involved function: std::vector<std::pair<value_type, size_t>> read_file(const std::string path, benchmark::State& state) { std::string kmer; std::vector<std::pair<value_type, size_t>> data; std::ifstream file(path); w...
There is nothing you can do here, this is expected. Starting and stopping a timer requires some form of synchronization with the OS, and the overhead of that in your case seems to be much higher than creating the temporary object. However, this shouldn't be an issue. If you're trying to compare several methods of filli...
66,447,376
66,447,486
Access violation reading location at cpp QT
I have problem with next constructor of QPixmap: QPixmap* map = new QPixmap(100, 100); There`s exception thrown, shown by visual studio. Access violation reading location 0x0000000000000000 I want to get empty field for drawing with current width and height, what should I do?
More specifically, you are trying to use QPixmap in a non-gui application. https://bugreports.qt.io/browse/QTBUG-64125 QPixmap is connected to the underlying GUI platform, and hence requires QGuiApplication/QApplication to be initialized. QImage can be used instead here.
66,447,462
66,447,573
Visual studio giving an out of range error codeblocks does not
I ran the following code #include <vector> #include <complex> #define N 8192 int main() { std::vector< std::complex<double> > input; input.reserve(N); for (size_t k = 0; k < N; k++) { input[k] = std::complex<double>(k, 0.0); } } in both codeBlocks and Visual Studios 2019. The latter gives th...
http://www.cplusplus.com/reference/vector/vector/reserve/ reserve only guarantees that the vector does not need to reallocate elements until it hits the reserved capacity. See the example in the provided link for more detail. Use the resize function to actually resize the container to contain the elements so you won't ...
66,447,647
66,448,082
Leaking memory with a map using the factory pattern, solution?
class Factory { public: Base* create() { return new Rand();} Base* create(double value) { return new Op(value); } Base* create(const std::string& comp, Base* x, Base* y) { /* std::map<std::string, Base*> map_CreateFuncs = { { "+"...
Unless there is a very specific reason to use raw pointers, consider always using std::unique_ptr by default. Using smart pointers allows to both avoid memory leaks and clearly document the ownership model. For example, when you create Add(x, y), should the ownership of x and y be transferred to the newly created obje...
66,447,830
66,448,066
Partial template specialization for: std::allocator_traits?
Is it possible to specialize the std::allocator_traits, template like this? namespace falloc_ { template<class Tp> class FAllocator ; } // partial spec for all falloc_::FAllocator<U>, std::allocator_traits template<typename Tp> struct std::allocator_traits<falloc_::FAllocator<Tp> > { using allocator_type = fal...
It is permitted to specialize the std::allocator_traits template. See [namespace.std]/2: Unless explicitly prohibited, a program may add a template specialization for any standard library class template to namespace std provided that (a) the added declaration depends on at least one program-defined type and (b) the sp...
66,448,668
66,448,717
Fill Method Question in C++ for a Class 'AList'?
I am new to programming and was wondering if someone may guide me in the following problem? Thank you, any advice will be helpful. Implement a fill method in AList class to fill all the elements in the list with a given value it. For example, let L=[1, 2, 3] . A call to L.fill(0) will make L=[0, 0, 0]. Below is a skel...
This should work: void fill(const ItemType & it){ for(int i=0; i<count;i++){ items[i]=it; } } The for loop just iterates through each index in items and replaces its value with it.
66,448,686
66,448,858
Can a std::map be efficiently split into two std::maps at an iterator?
Let's say I have a std::map<int, std::string> myMap containing the data 1. Red 2. Blue 3. Green 5. Fuchsia 6. Mauve 9. Gamboge 10. Vermillion and also an std::map<int, std::string>::iterator it pointing at the element 5. Fuchsia I would like to do something like (making this up) std::map<int, std::string> myHead = ej...
If we're speaking asymptotic complexity, you can do this in O(log n) time for most self-balancing tree types, using two operations colloquially known as split and join. There's an extensive Wikipedia article on this. You can not get this complexity using std::map, you'll need to roll your own or a third-party self-bala...
66,448,785
66,448,919
Problems Including GTK for C++ on Manjaro Linux
I've been struggling for hours to include the GTK library for manjaro in C++. I'm using VS Code, I have installed the GTK-4.0 package with the command sudo pacman -Syu gtk4 and I'm including the file /usr/include/gtk-4.0/gtk/gtk.h in my C++ program with the line #include <gtk-4.0/gtk/gtk.h>. It's throwing the error gtk...
You are missing an include path. Gtk requires* pkg-config to set the include path. see https://developer.gnome.org/gtk4/unstable/gtk-compiling.html So while you have included it with a complete path, the files inside the library still require the include path to be set. I don't know which build system you are using, bu...
66,448,813
66,448,971
Check all lines in the file that have both, one or none of the strings in the same line
I want to check if the chosen strings appear in the same line. Sadly I don't get the correct output. The file contains this text /* one two one two two one two one something else */ #include <iostream> #include <string> #include <fstream> using namespace std; void display(ifstream& MyFile, string a, string b) { ...
You are doing the if statement wrong. I changed the way to verify if a string contains another one, basically s.find(a) will return the start position of a in s if it exists in it, or will return -1 if it doesn't. This way, verifying like this s.find(a) != -1 or s.find(a) <s.length() would work the same way, bacause in...
66,448,987
66,458,455
How do I fix "Could not find the task C/C++: gcc build active file." error in VSCode?
I am working on a C program in VSCode, and I am on Windows running Ubuntu 20.04 via Windows Subsystem for Linux (WSL 1.0). Everything was working fine for the last few weeks until today when I encountered the error message in the title of this post. I will include both the tasks.json and launch.json below (both are in ...
It turns out downgrading the C/C++ extension was the answer. A recent update caused this issue to occur.
66,449,366
66,452,751
Win32 COM port data scrambled
I'm trying to have my Arduino Nano send data via USB over a COM port to my C++ script, but the data I get seems to be out of sink. I don't know what the issue is. Here is my Arduino code: void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: Seria...
The Arduino code is correct. The issues that I find with the C++ code are as follows: Continuously opening and closing the port is a bad idea (the while loop executes faster than the rate at which you get the data - this will just lead to you getting garbage data) Since you are trying to read a single byte of data, a...
66,449,441
66,449,474
In C++, why does auto not work with std::atomic?
General recommendation online seems to be to use auto where possible. But this doesn't work: auto cnt = std::atomic<int>{0}; While this works fine: std::atomic<int> cnt {0}; Is there a recommended way to use this with auto? Or should I just assume that auto is not possible with this?
std::atomic is immovable because it has a deleted copy constructor. Prior to C++17, auto cnt = std::atomic<int>{0}; tries to call the move constructor to move the temporary into cnt, so you can't use std::atomic with almost always auto. C++17 brought us mandatory copy elision, so auto cnt = std::atomic<int>{0}; works f...
66,449,680
66,449,716
Constructing shared_ptr from unique_ptr with and without move?
I see in the highly-upvoted answer here (https://stackoverflow.com/a/37885232/3754760) there are two ways to convert a unique_ptr to a shared_ptr, namely by creating the unique_ptr first and then move-ing it to the shared_ptr, as well as assigning the unique_ptr directly to the shared_ptr. Example: std::unique_ptr<std:...
Are the two above equivalent Yes could someone explain what this warning means and why it occurs in the 3rd example? Copy Elison only works when the result of a function call returning a temp object is directly assigned to a variable. The compiler can optimize away the temp object and let the function initialize t...
66,450,100
66,454,754
MSBuild deletes one lib file, breaking the build. Visual Studio works fine
I have project dependencies like this: Main -> A, Common A -> B, Common with the build order: Common B A Main The solution builds fine in Visual Studio 2019. But in MSBuild, it builds Common.lib, B.lib, A.lib ... then deletes Common.lib, before trying (and failing) to build Main.exe. I've tried changing the output d...
You should note the build has a order: Common-->B-->A-->Main If Main project has an error, it will not stop the A and B project's build because they has no error. Also, if the bottom project Common has an error, when it will break the whole rebuild process, delete A and Main project output files. Also, when you try tp ...
66,450,395
66,450,429
This function gives me the error "warning: control reaches end of non-void function [-Wreturn-type] }"
When I compile this code I get the error that was stated in the title, but I am not sure what is causing it. I have checked other similar questions and I still can't seem to figure out why it is happening. int dictionary::getRank(string Word) { int Rank = 0; string str; bool found = false; for (int...
Look really carefully at that code, and think what would happen if the 1st loop sets found to true, and then the 2nd loop reaches WORD_COUNT without finding a matching word. Logically, that can't actually happen at runtime, but the compiler doesn't know that. All it sees is a flow path that is missing a return statem...
66,450,472
66,450,571
What is the difference between virtual function and virtual destructor function?
class Base { public: virtual ~Base () { cout << "Base Dtor" << endl; } virtual void doSomething () { cout << "Base do something" << endl; } }; class Derive : public Base { public: ~Derive () { cout << "Derive Dtor" << endl; } void doSomething () { cout << "Derive do something" << endl; } }; wh...
Object destructors are special. Yes, they are functions, but they actually represent something particular. Namely, destroying an object. In your example Derive is an object. But through inheritance, Derive has a base class subobject called Base. That is, for every Derive, there is also a Base living within that Derive ...
66,451,365
66,455,534
How to modify a value with yaml-cpp?
I'm trying to make configuration file for my application, for which I'm using yaml-cpp library to generate a configuration and modify when user changes changes some setting or something in the application. I have a separate class set up for this, the constructor generates the yaml file which looks like this, Serializer...
You override the file, of course it only contains the items you gave to the emitter out. If you want to modify the loaded file, you should update the values in config and write all of it back out: fontSetting["Family"] = fontFace; fontSetting["Size"] = fontSize; out << config; std::ofstream ofout(filepath); ofout << ou...
66,451,575
66,453,159
How to search for files with CFtpFileFind::FileFind() method?
I created m_pFileFind using CFtpFileFind class. I tried to search all files with FindFile() by performing dynamic allocation, but 0 is returned and the search is not available. I tried debugging by referring to Microsoft docs, but I couldn't figure out the cause. Please give me detailed advice. void CMFC_FTPDlg::ShowLi...
Please check the documentation for CFtpFileFind::FindNextFile where it states: Return Value Nonzero if there are more files; zero if the file found is the last one in the directory or if an error occurred. To get extended error information, call the Win32 function GetLastError. If the file found is the last file in th...
66,451,662
66,463,787
How to serialize apache arrow c++ table, trans through socket,and deserialize it at python side
I'm new to apache arrow, My C++ project use apache::table to store data well. and now, I need to trans c++ table with socket to other python client. why try this,because python client needs to tans data to dataframe and I notice that arrow table in python can use 'to_pandas()' to do that. I tried to look up arrow cytho...
You could send an arrow table over a basic socket (example below) but you're probably better off using Flight. Flight uses grpc to send arrow data back and forth and it will remove some of the tedium of using sockets. Here is a great example. The complete socket example can be found in this gist. I will put the relev...
66,452,285
66,452,392
error: invalid types 'int[int]' for array subscript|
the code returns error: invalid types 'int[int]' for array subscript| and everything else seems to run fine. What can I do about it ? (line 10,22,23) #include <iostream> using namespace std; int n, x[50], y[50], z[50]; void citire(int &n, int v) { int i; cin >> n; for (int i = 1; i <= n; i++) { ...
You are using v as an array, but it isn't an array, it is int. You probably want to use int* v. void citire(int &n, int* v) { // ... cin>>v[i]; }
66,452,469
66,453,914
(C++) Input specific pattern accoring to user input
I have a line of code that when inputted 3, the result will print out a series of dashes and asterisks to form a diamond: Expected Input: 3 Expected Output: --*-- -***- ***** -***- --*-- what i have so far is the triangle but I can' seem to get rid of the middle line to make it a full diamond shape. Also "-" is not p...
For removing the double full star line use following code line for (int i = n-1; i >= 1; --i) { instead of for(int i = n; i >= 1; --i) { (side note: maybe you want to check as suggested by yaodav if you could not write the second part like the first part).
66,452,731
66,461,814
Regular expression to match String Exactly with opening Round Brackets or Parentheses
Simple regex question. I have a string on the following format: XYICD27A3 (MN PqrstUvw MFP E34540) What will be the regular expression to match this string. I have tried: (^([a-zA-Z0-9-_@&:.#$ s]+)$) this, but it's not matching the whole string
According to your comment, I corrected your regex like this: [a-zA-Z0-9\s]+\([a-zA-Z0-9_@&:.# -]+\)
66,452,781
66,452,811
Why const char* implicitly converted to bool rather than std::string?
#include <iostream> #include <string> struct mystruct{ mystruct(std::string s){ std::cout<<__FUNCTION__ <<" String "<<s; } explicit mystruct(bool s) { std::cout<<__FUNCTION__<<" Bool "<<s; } }; int main() { const char* c ="hello"; mystruct ob...
Because the implicit conversion from const char* to bool is qualified as standard conversion, while const char* to std::string is user-defined conversion. The former has higher ranking and wins in overload resolution. A standard conversion sequence is always better than a user-defined conversion sequence or an ellipsi...
66,452,878
66,456,694
Add threads jobs into Thread array
I attend to working RWLock with 5 thread ( 4 threads for reading and 1 thread for writing ), reference(&) operator and without using mutex library I want to make a thread array and insert the their jobs, and working. but when i had a breakpoint to funtion ReadLock, i got a value 5. It means threads are inserted last va...
In this line: th[threadNum] = std::thread([&](){ReadLock(try_w_lock, readFlag, threadNum, Val); }); you capture all lambda implicit parameters by reference. This includes threadNum. Thus, all your threads refer to the same location in memory that is being quickly changed in the for loop. By the time threadNum has bee...
66,452,879
66,453,032
How to iterate over a specific range of std::set/std::multiset?
For an std::set like std::set<std::string> set={ "aaa", "bbb", "ccc", "ddd", "eee", "fff" }; how to iterate over a specific range [a, b] of this set without tracking of extra indexes? Something like this: for(auto it = set.begin(); it!=set.begin()+b; ++it) std::cout << *it << " "; Or like this: for(auto it = set.b...
You cannot do set.begin()+a, but you can do std::advance(it, a): #include <iostream> #include <set> #include <string> int main() { std::set<std::string> set={ "aaa", "bbb", "ccc", "ddd", "eee", "fff" }; size_t a = 1, b = 4; auto it = set.begin(), it_end = set.begin(); std::advance(it, a); std::adv...
66,453,127
66,493,975
Xcode in release mode fails to compile <immintrin.h> - complains about __builtin_ia32_emms()
I'm very new to Xcode, and developing SIMD(SSE/AVX) codes for macOS with Xcode 12.4 (12D4e) on macOS Catalina 10.15.7. This very simple code can be compiled in Debug scheme: #include <immintrin.h> int main(int argc, const char * argv[]) { return 0; } But in Release Scheme, the header makes error: "Too few argumen...
If you have any Intel-specific code (such as Intel intrinsics) then you need to make sure that your Release build is set for x86-64 architecture only. In Xcode 12 the default is to build for both x86-64 and Apple Silicon in the Release build, which results in spurious error messages when Intel intrinsics are encountere...
66,453,186
66,453,343
How to in C++ substitute the dynamic polymorphism by the static one?
Let's say I have following code exploiting the dynamic polymorphism in C++ GraphicalObject.h class GraphicalObject { public: virtual void draw() = 0; }; Rectangle.h #include "GraphicalObject.h" class Rectangle : public GraphicalObject { void draw(); }; Rectangle.cpp #include "Rectangle.h" #include <iostream>...
The problem here is that objects pointed by GraphicalObject* picture[2]; got static type GraphicalObject and static polymorphism uses static type. But that doesn't mean static polymorphism isn't possible is similar situation. You would need a wrapper class which would know the actual type of stored object and would cas...
66,453,355
66,631,034
How to generate c++ grpc file after installing it by vcpkg and cmake?
I install grpc by vcpkg install grpc and add it to cmake file . Now I want to generate grpc c++ file , I run : protoc --cpp_out=grpc_file/ --grpc_out=grpc_file/ --proto_path=grpc_proto/ ./grpc_proto/side_information.proto It returns error : protoc-gen-grpc: program not found or is not executable --grpc_out: protoc-g...
Is your CMakeLists.txt like below? cmake_minimum_required(VERSION 3.1) if(DEFINED ENV{VCPKG_ROOT}) set(CMAKE_TOOLCHAIN_FILE $ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake) else() set(CMAKE_TOOLCHAIN_FILE "/path_to_vcpkg/scripts/buildsystems/vcpkg.cmake") endif() project(Foo) find_package(gRPC CONFIG REQUI...
66,454,003
66,457,459
Multiplying two matrix in a different way - can't figure it out how to do it
As a homework, I have a problem which sounds like this: We have a n*n square matrix. It is called 'subdiagonal' if all the elements above the main diagonal are null. a) Copy the useful elements (the ones which are not null, so basically all the elements from the main diagonal and below) to an array. (I've done that) ...
Matrix multiplication C = A*B is defined by C(i,j) = sum_k A(i,k)*B(k,j). The matrix A has structural nonzeros where i >= k, and B, where k >= j. Thus it suffices to iterate (outer loop) i from 0 to n-1 (middle) j from 0 to i (inner) k from j to i. The other piece is turning coordinates (i,j) into an offset with resp...
66,454,126
66,454,851
How to print a row of an array?
I am fairly new to C++ programming, and I am getting stuck at how to print values from a specific row. I mean: std::string musical_things [][][] = { { {"Scale"}, {"Minor Natural"}, {"1","2","b3","4","5","b6","b7"} }, { {"Scale"}, {"Major"}, {"1","2","3","4","5","6","7"} }, }; So, when ...
Note that your data doesn't fit a 3-D array model: the individual arrays are of different length, which will make the compiler "pad" them with zero-valued characters. This is a great amount of padding, and, what's worse, it's not easily predictable. For example, the longest string in your data has 13 characters, so all...
66,454,638
66,476,527
How does the OBEX protocol look like?
I'm trying to exchange data between a mobile phone and a computer using bluetooth. I'd like to use OBEX for it. I have read OBEX_documentation and Wikipedia and tried to send a following package from a device 1 (computer): const char package[] = /* Connect | 2B of length| OBEX Ver 1.0| Flag| Max Size */ ...
The PBAP is describe here (search for PBAP). The link was given by @Mike Petrichenko The other helpfull post can be found here.
66,454,810
66,455,013
In C++ threads, should I pass shared_ptr by value or reference?
This page on Thread Safety by Microsoft says shared_ptr should be used even if there are multiple copies sharing the same object. So does this mean that both of the following are acceptable? I've tried both and they appear to work fine. EDIT: The actual business objective is to get string updates from the long running ...
Typically, threads may outlive the scope where they are created. In such case, any local variable captured by reference may be destroyed while the thread is still running. If this is the case, then you should not capture by reference. Furthermore, modifying a shared pointer object in one thread and accessing in another...
66,455,184
66,455,590
No matching constructor error (Boost Beast, C++)
Here's my header file for a WebSocket client: namespace beast = boost::beast; namespace asio = boost::asio; class WebSocketClient { public: explicit WebSocketClient(asio::io_context &ioc); private: using stream_type = beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>; using ssl_context_type = asi...
The problem is that the boost::asio::ssl::stream class constructor (and by induction, beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>> constructor) requires an l-value of boost::asio::ssl::context as the second parameter, and WebSocketClient::get_ssl_context returns an r-value. In other words, WebSocketCl...
66,455,721
66,455,805
"Node" not declared in scope error even though "Node" is declared inside Tree class
I am not able to figure out why I get the compilation error 5 class Tree { 6 public: 7 Tree() : root(nullptr) { std::cout << "tree created" << std::endl; } 8 ~Tree() { std::cout << "tree destroyed" << std::endl; } 9 bool add(int val); 10 void inOrderTraversal() { inOrderTraversal(root); } 1...
Node is an inner class of Tree. Change your references outside of the class definition to Tree::Node so g++ looks in the right namespace for your definition. Like this: std::shared_ptr<Tree::Node> Tree::insert(int val, std::shared_ptr<Node> subTree) { ... } You'll also want to fix your return true in your insert fu...
66,455,994
66,456,251
Json data creation for nlohmann
I have some data like { "GLOBAL DATA": { "FIRST": [ {"BEGIN": "0", "END" : "100"} ], "SECOND":"SomeData", "THIRD":"SomeMoreData" } } I want to add more data to FIRST array. I tried creating the insertion data as follows json v2 = {"BEGIN": "200","END" : "300"}; But this...
You could wrap the JSON data in a raw string literal and use the _json user-defined literal to parse it: json v2 = R"({"BEGIN": "200", "END": "300"})"_json; Or you could make it directly (without parsing), but using valid C++ syntax: json v2 = {{"BEGIN", "200"}, {"END", "300"}};
66,456,027
66,457,397
How do I improve the following piece of code in constructor method?
auto MyName = "Luffy"; for (auto &student: students) { if (student.name == MyName) { m_student_info = &student; } } students is a struct with names and rollnumbers declared somewhere with values. How do I improve this piece of code inside a constructor? return cannot be used inside the constructor....
You can initialise the member with a function Student* find_student(std::string name, Students & students) { auto it = std::find_if(students.begin(), students.end(), [&name](auto & student){ return student.name == name; }); return (it != students.end()) ? &*it : nullptr; } Thing::Thing() : m_student_info(find_...
66,456,916
66,459,012
Implicitly capture const variable in a template lambda with no capture-default specified
Consider the following code: auto f() { const auto x = 1; return [] (auto) { return x; }; } GCC and MSVC compiles fine but Clang rejected it. Which compiler should I trust? Is that some compiler extension that Clang does not implement yet or Is it just a Clang bug?
This is a clang bug. The rule we have is [basic.def.odr]/9: A local entity is odr-usable in a scope if: either the local entity is not *this, or an enclosing class or non-lambda function parameter scope exists and, if the innermost such scope is a function parameter scope, it corresponds to a non-static member functi...
66,457,048
66,457,088
Vector as class member
class A { private: std::vector<int>myvec; public: const std::vector<int> & getVec() const {return myvec;} }; void main() { A a; bool flag = getFlagVal(); std::vector<int> myVec; if(flag) myVec = a.getVec(); func1(myVec); } In the line myVec= a.getVec(), there is a copy of vector...
func1(flag ? a.getVec() : std::vector<int>()); is one way. This will work if func1 takes the vector by const reference, since both anonymous temporaries can bind to it.
66,457,085
66,457,256
Reading file in C++ giving weird characters after the actual file content
I'm fairly new to C++ and I'm trying to read a JSON file into a char array/char *. But whenever I read a file, it give some weird character after the actual file content like so: {"Image": "myImg.jpg"}ts;C:\Ureßr Why is this happening? How do I fix it? This is my current code: char* read_file(const char *file) { ...
So-called "C-Style" character strings need to be nul-terminated in order to work with any of the standard functions, such as are used for displaying them. In order for your data buffer to conform to this, you need to increase the allocated buffer size to allow for this terminator character, and also make sure that the ...
66,457,355
66,457,413
Why do std::string variables accept only 1 character at a time in C++?
The problem I am facing is that whenever I try to read user input in my simple struct-based database application the programme accepts only 1 character at a time. When I give 2 characters or more as an input in the function fill_the_database() skips one section of this kind: std::cout << "What is the product's ...
You confused the place where [i] should be. Currently, you are accessing first product from the array and then you try to access i-th character in each string (which likely doesn't exist at that point). It should look like this (and similarly for all other reads): std::cin >> database[i].name; Also, there is a proble...
66,457,728
66,458,849
C++ SFINAE to determine the number of function arguments (C++17)
I created a metafunction using SFINAE to determine the number of arguments of a function at compile time. It works fine with gcc when used with with function objects, but not with lambda closures, I don't understand why. The metafunction is here below template < typename T > int val (T &&){return 0;}; template <int N,...
As pointed out in the comment by @rafix07, the issue here is that the lambda is returning void, so it's signature is not matched in the first definition of test, and falls back to the other overload. One fix is to apply a comma operator to the argument of val, i.e. changing static auto test(F, decltype(val(std::declval...
66,457,737
66,458,081
Rounding Floating Point Number To two Decimal Places in C++
After Rounding to two decimal places, i alwayse get the same value float TestT =round(t*100)/100; i would like to round it and fix it to two decimal places: 0.009999 -> 0.01
You can do this in 2 steps:- Step1:- transform your float value to string and use the inbuilt QString feature to perform the rounding for you Eg:- @QString::number( 99.48, 'f', 2); In your case:- QString TestS =QString::number( t, 'f', 2); Step2:- transform your rounded string value to float Eg:- in your case :- flo...
66,458,353
66,458,470
C++:How to make #define work with custom classes?
Is there a way to make #define work with custom objects?Here is an example to show what I mean: #include <iostream> #define i Complex z; z.Re=0; z.Im=1 //<-error using namespace std; class Complex{ public: double Re; double Im; void operator=(Complex z){ this->Im=z.Im;this->Im=z...
One way to solve this is by adding a constructor, then creating a const you can reference as necessary: #include <iostream> class Complex { public: double Re; double Im; // Add a simple constructor Complex(const double r, const double i) : Re(r), Im(i) { }; Complex& operator=(Complex z) { ...
66,458,416
66,458,532
How can I convert C++ class which contain constructor to C struct?
I want to draw rectangles in a window in C. I found the following C++ code I want to convert its classes to C struct to use it in my C project. I want to convert the following C++ class to C struct: class Rect{ public: int x1; int y1; int x2; int y2; Rect * next; Rect(){ x1 = y1 = x2 =...
You create a struct with the data and functions for the methods: struct Rect { int x1; int y1; int x2; int y2; struct Rect *next; }; struct Rect *Rect_init(struct Rect *r) { assert(r); r->x1 = 0; r->y1 = 0; r->x2 = 0; r->y2 = 0; r->next = 0; return r; } void Rect_draw(struct...
66,458,916
66,459,079
Back button in a console text game (c++)
based game there are multiple menus to access, and I would like to add a back button or choice to it. They are all in a switch statement, for example: cout<<"1. Open menu 1<<endl<< 2. Open menu 2"<<endl; int choice; cin>>choice; switch(choice){ case 1: //Opens menu 1 and shows more text for example: cout<<"1. Open sub...
I believe this is what you are looking for: main_menu: cout << "1. Open menu 1" << endl << "2. Open menu 2" << endl; int choice; cin >> choice; switch (choice) { case 1: //Opens menu 1 and shows more text cin >> choice; if (choice == 1) { goto main_menu; } break; case 2: //Ope...
66,459,023
66,459,164
Why can't we directly assign arr to pointer to array
I have an array of 5 integers. arr and &arr is same address. So why number 2 gives compilation error and and 3 works fine. int arr[5] = {1,2,3,4,5}; 1. int *p = arr; 2. int (*p1)[5] = arr //Compilation Error 3. int (*p1)[5] = &arr; //Works fine. arr = 0x61fdf0 and &arr= 0x61fdf0
The problem is that the initialized object and the initializer have different pointer types and there is no implicit conversion from one pointer type to another. In this declaration int (*p1)[5] = arr; the initialized object has the type int ( * )[5] while the initializer has the type int * due to the implicit convers...
66,459,137
66,459,741
Using std::copy with LPTSTR type argument
I'm using Win32 API and I need to copy arguments captured with argv, the problem is, the code has to be compliant with both ASCII and UNICODE and that's a problem with C/C++ in Windows. Beyond that I must use, when possible, C++ instead of C, so I'm using std::copy to copy arguments of type LPTSTR (or TCHAR*), I could ...
You should use std::basic_string: using tstring = std::basic_string<TCHAR>; It handles all the copying itself. Whenever you need to talk to some C API, use str.c_str() for a const pointer and str.data() (after C++17) or &str[0] (pre C++17) for a non-const pointer. #include <windows.h> #include <tchar.h> #include <core...
66,459,261
66,476,644
How to pass template parameter from class constructor
I have template class and some Policies to use it. It just execute lambdas with specific policy. template<template<class>class Policy, typename ReturnType> class execute :Policy<ReturnType> { public: ReturnType res; execute(ReturnType(*func)()) {res = Policy<ReturnType>().launch(func);} }; template<typenam...
The standard says: Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place. Therefore, you cannot achieve that this simple, although the functionality would make sense at first glance. A close solution via a f...
66,459,487
66,459,974
install CMake package on windows visual studio problem (find_package)
I made a simple program using glfw in Linux. and I want to build it in windows now. when I install glfw in Linux, I did the following steps. install CMake. download glfw source code. create a build folder in the source code folder. do "cmake ../" in the build folder do "make" do "make install" Then in CMakeLists.txt...
TL;DR answers: Because you did not specified an installation prefix. Add CMAKE_INSTALL_PREFIX to your GLFW CMake command, e.g. cmake -S <sourcedir> -B <builddir> -DCMAKE_INSTALL_PRFIX=<yourinstalldir> cmake --build <builddir> --target install --config Release If you do not specify an installation prefix to your cma...
66,459,705
66,459,975
What is the difference between const std::vector<T> and std::vector<T> const?
I thought the only way to declare a const<vector> is: const std::vector<T> v;
const applies to the thing to its left, except for when there is nothing on the left then it applies to the thing to its right. So, const int a=1; and int const a=1; are equal. const int *b and int const *b are equal (pointer to a constant int), but different to int * const b, which is a constant pointer to a non-const...
66,460,152
66,461,137
C++ - How to reserve some class objects to only be instantiated by a certain class
I'm defining a unique_id_generator class, which is kind of, sort of a singleton i.e there is just one instance for a given type_id. There can be many different type_ids, but for a specific type_id, there is just one instance. Now I want to make sure that type_id = 0 goes to a very specific class. Basically just that sp...
The only solution I could think of is to define 2 instantiation methods. One public and one private as follows: #define EXCLUSIVE_CNT 1 class UniqueID { public: friend class MySpecialClass; static UniqueID * GetInstance(int type_id) { assert(type_id >= EXCLUSIVE_CNT); return Instantiate(t...
66,460,463
66,460,928
Difference between typename parameter pack and auto parameter pack?
Suppose I have this 2 definitions. template<typename... Ts> struct S{}; template<auto... Ts> struct S{}; What's the difference between this 2 definitions? When we should opt for the one or another?
Templates have 3 kinds of parameters: Template type parameters Template non-type parameters Template template parameters template<typename... Ts> struct S{}; Here Ts is a pack of type parameters. It accepts data types like in S<int, long>. template<auto... Ts> struct S{}; Here Ts is a pack of non-type parameters wi...
66,460,464
66,460,568
Should I inline namespace scope lambdas? In either case, why?
Sometimes I have some capture-less lambda defined at the top of a header file, which is used in the following part of the header: //#include statements namespace detail { auto constexpr lambda = [](/* args */){ /* body */ }; } // in some function or whatever, use `lambda` Often I'm told in during code reviews that I s...
You should be using inline if the variable is defined in a header file. If it is not inline, then every translation unit that includes the header file will get that definition. That means you have multiple definitions for a single name which is an ODR (One Definition Rule) violation. Those do not require any diagnos...
66,460,961
66,461,087
What is meaning no declaration match error in my case?
I described class in different files: 3DObjectDescription.h #pragma once #include <SFML/Graphics.hpp> #include <NumCpp.hpp> #include "MoveMatrix.h" class Object3D { public: nc::NdArray<float> vertexes; nc::NdArray<float> faces; Object3D(); void translation(float tX, float tY, float tZ); void rot...
The declaration return type is void. void translation(float tX, float tY, float tZ);  ^^^^ But your definition does not have a type. void Object3D::translation(float tX, float tY, float tZ)  ^^^^ is missing When an explicit return type is missing, `int` is assumed by some compilers producing that error. e.g. VS2019 er...
66,461,499
66,461,801
Rcpp, Value Assignment Error, Meaning of SEXPREC*
I wrote the following code in Rcpp //#include <Rcpp.h> #include <RcppArmadilloExtensions/sample.h> #include <random> #include <iostream> using namespace Rcpp; // [[Rcpp::export]] arma::vec SimulBetaBin(int K, arma::vec N){ arma::vec D; Environment pkg = Environment::namespace_env("extraDistr"); Function...
You get a SEXP back from calling a Rcpp::Function() object, so you need to cast it. A modified version (also simplifying headers down to what you actually used and need) of your function follows, this one compiles for me. #include <RcppArmadillo.h> // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] arma::ve...
66,461,883
66,461,973
enum errors expected an identifier and other 2
I'm getting: expected an identifier and *a value of type "const char " cannot be used to initialize an entity of type "trivia" x2 This is my code, sorry, I'm new in programming so I'm testing stuff :) #pragma warning(disable:4996) #include <iostream> #include <string> using namespace std; enum trivia[1][2] { {"He...
The way you are using the enumeration is not correct. The enums are used to hold constants with meaningful names that are to be used during coding. This is done to increase the readability of the code. A sample enum example is as follows: enum Color { red, green, blue }; // 0 1 2 Color r = red; swit...
66,462,336
66,476,902
Can't see/load a .obj file with Qt3D, written in cpp
I'm having a lot of issues to have a simple working app that load a light mesh in Qt3D, nothing shows up on screen. Here's some code I put together to have a have striped down to show. You'll notice that it's a shorter version of this Qt example You won't see it in this example but in my actual project I already tried...
With the help from @eyllanesc and qDebug, I found how to write it in three ways: const QUrl url = QUrl( "qrc:/path/copied/from/qtcreator/su.obj"); const QUrl url = QUrl::fromLocalFile( "C:/path/to/folder/su.obj"); const QUrl url = QUrl::fromLocalFile( "su.obj"); qDebug() << QDir::currentPath(); // I used...
66,462,473
66,462,639
LNK2019 Unresolved external symbol OOP and polymorphism?
My project is to build a stack in C++, And I implemented it using array ,but I have 6 Errors: all of them LNK2019 Unresolved external symbol to some functions implementation in the .CPP file I know this is a linker errors , the problem occurred when I Divided My code into Header files .h and implementation files .cpp b...
Since you didn't post your code, I can only guess. If you are implementing your stack using a template (very common) then you may see this error if you define your template functions/methods in a separate .cpp file. Typically template functions & classes are defined inline or contain their definitions within the same h...
66,462,859
66,463,591
What's the difference between static_cast<type> and static_type<type *>?
So far I understand that static_cast is a compile time action that somehow analyzes the memory of the entity and tries to convert it to the specified object. I see static_cast used extensively as static_cast<T *>. What's the reason for this? Is it because the compiler needs a pointer to check the memory layout of the o...
It might be helpful to consider two different use cases for static_cast: one for converting non-pointer types to one another, and one for converting pointer types to one another. When converting non-pointer types to one another, static_cast has the meaning of "do the kind of conversion that you would do if you initiali...
66,463,447
66,571,385
Stack corruption with jsoncpp
I am getting stack corruption saying "Run-Time Check Failure #2 - Stack around the variable 'root' was corrupted." with following code: #include <json/json.h> #include <fstream> #include <iostream> #include <string> int main() { Json::Value root; Json::Reader reader; ifstream file("input.json"); if (!reader.pa...
Reader class in jsoncpp seems outdated. Refer to the latest example on https://github.com/open-source-parsers/jsoncpp/blob/master/example/readFromStream/readFromStream.cpp
66,463,954
66,464,721
How should i solve counting problem in my divisor program C++
hi guys i recently started learning C++ and today i got a problem with counting divisors in this program i want my program to count the number of divisors exactly but the output show weird numbers :/ #include <iostream> using namespace std; int main(void) { int Lowest; int Highest; int count = 0; cout ...
As noted by @cigien's comment, your count variable never gets reset to zero so it just keeps counting up. Reset it between each iteration of the outer loop. Better still, move the declaration to the closest place where it's used: #include <iostream> using std::cin; using std::cout; // only using what you need int mai...
66,464,181
66,465,445
Second thread is never triggered
I've been struggling with a multithreading issue for a bit. I've written some simple code to try and isolate the issue and I'm not finding it. What's happening is that the first thread is being woken up with data being sent to it, but second one never does. They each have their own condition_variable yet it doesn't see...
The 2nd thread is exiting because the keepRunning state flag is false. It's usually a good first step in debugging threads to log the start and exit of all threads. But you have a much less obvious problem. It does not appear that the appropriate mutex is held when the value of the condition variable's predicate is ch...
66,464,224
66,464,541
C++20 function taking sequence of ints?
Let's suppose we have an inline C++20 function f: inline void f(size_t i, int x) { /*...*/ } and we want to write another inline function g (or a multi-function overload set) that takes an ordered sequence of ints and for the ith one (zero-indexed) that has value x, calls f(i,x) One way to do this would be: void g(con...
This is what span is for: void g(std::span<int const> v) { for (size_t i = 0; i < v.size(); i++) { f(i, v[i]); } } This handles any kind of contiguous storage of integers, with no overload, and doesn't have to be a template. If you really want to support arbitrary literals as well, you can add an overl...
66,464,916
66,465,087
multiplication table of 1-4
i tried to write a code that shows the multiplication table of 1-4 but in the first attempt(below) it gave me: 1 2 3 4 2 4 6 8 3 6 9 12 4 0 but then sb told me to write it like this and it worked. 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 **Now my question is what was the problem with the 1st one????? 1st version: #include <i...
The difference is the starting index. Arrays begin at 0 position, so you must initialize your i and j from 0. Otherwise, you could declare your x matrix as [5][5], and you can use i and j starting from 1. Cheers!!
66,465,198
66,483,429
How to fix Java 15 JNI "UnsatisfiedLinkError: A dynamic link library (DLL) initialization routine failed"
I have found other posts of people having this exact error, but not one thus far has had a solution that worked for me. For reference, here are the things I have found: https://community.oracle.com/tech/developers/discussion/2233828/jni-link-error-a-dynamic-link-library-dll-initialization-routine-failed JNI Unsatisfied...
Well, @JornVernee effectively nailed the issue right on the head. It was a mismatch between the standard library I had for C++ and the one being loaded. I changed the version of GCC I was using to a more up-to-date version, recompiled the entire project, and the program works now.
66,465,330
66,704,290
List of subclass pointers that all derive from the same superclass (C++)
Take this example code: #include <QWidget> #include <QMainWindow> #include <QList> #include <QGridLayout> #include <QLabel> #include <QDialogButtonBox> #include <QApplication> class MainWindow; class BaseWidget : public QWidget { public: BaseWidget() = default; virtual ~BaseWidget() {}; virtual void disp...
As someoneinthebox commented, Qt doc about QMainWindow::setCentralWidget says: Note: QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time. So, second time you do this->setCentralWidget(widget);, the widget that was previously used as central widget gets automatically deleted by Qt ...
66,465,345
66,466,465
free(): double free detected in tcache 2 in PriorityQueue remove method
I am programming a priority queue, and I am getting an error: free(): double free detected in tcache 2 I know that problem is in the PriorityQueue::Remove(int value) method. The method tries to delete an element by value. This method returns TRUE when the element has been deleted and FALSE otherwise. Here is the code...
I do not see any double-delete in this code, so the problem has to be elsewhere. For instance, if PriorityQueue does not follow the Rule of 3/5/0 properly, and is shallow-copying pointers when it should be deep-copying them. There is not enough code shown to diagnose the root cause of the error. However, the code sho...
66,466,123
66,466,140
Updating class member values inside a range based for loop in C++
The code on top works. The code below it does not. Why? I am searching through a vector of class objects in C++ using the object's name member so as to increment it's watched member. The regular for loop and syntax successfully increments the member. However, my attempt to do the same using what I assumed was the corre...
Your loop makes a copy of the element into m every iteration. Your changes to m will be to that copy. Make m a reference to the element in the container instead: for(auto& m : mList)
66,466,615
66,466,685
Does C++20's 'requires' keyword slow your program?
Consider this class: class Person { std::string name; std::string last; int age; public: template<typename T1, typename T2> Person(T1&& name, T2&& last, int age) noexcept : name(std::forward<T1>(name)) , last(std::forward<T2>(last)) , age(age) {} Person(const Pe...
Does C++20's 'requires' keyword slow your program? No, it specifies a constant expression on template parameters that evaluate a requirement - or in a template declaration, specifies an associated constraint. Template parameters (and constraints) must be compile time constants by nature and won't affect the speed of ...
66,467,081
66,467,401
Can the C++ Array class be passed as a parameter with variable size?
I am aware that a regular, built-in array can be passed in to a function with variable sizes. However, is there a good technique to be able to write a single function that takes an array class object reference, but the size can be variable? Is there a template technique for doing this? Or do we just use vectors inste...
I am aware that a regular, built-in array can be passed in to a function with variable sizes. No, it can't. It can only be passed in by-pointer or by-reference. In the case of by-pointer, all size information is lost. In the case of by-reference, the size has to be stated explicitly in the parameter itself as part ...
66,467,140
66,467,260
How to solve Permutation of a phone number problem
The Problem: A company is distributing phone numbers to its employees to make things easier. the next digit cannot be equal to the last is the only rule for example 0223 is not allowed while 2023 is allowed. At least three digits will be excluded every time. Write a function that takes in a length of the phone number a...
A simple way to solve this problem could be using Recursion. Here's my commented C++ code: void solve(int depth, int size, vector <int> &curr_seq){ // If the recursion depth is equal to size, that means we've decided size // numbers, which means that curr_seq.size() == size. In other words, we've // decide...
66,467,141
66,467,248
ERROR: S2760: Unexpected token '<', expected ',' inside a ECS
Hello big brains of the internet :). I am making my way deeper into the depths of C++. I received this error and even tho it should be an easy one, I don't have the faintest idea where have I made mistake. Here is a declaration of the template etc.: using ComponentID = std::size_t; inline ComponentID getComponentTypeI...
I'm not sure what all Component, ComponentArray, and ComponentBitSet look like exactly, but perhaps these lines: ComponentArray[getComponentTypeID<T>()] = c; ComponentBitSet[getComponentTypeID<T>()] = true; should look like this: componentArray[getComponentTypeID<T>()] = c; componentBitSet[getComponent...
66,467,163
66,467,299
C++ need help fixing to get desired output
I am working on a programming challenge from "Starting Out With C++: Early Objects, 10th Edition". I have the code about halfway done, but the output isn't coming out how it is supposed to be, and I am wondering how to fix it. I have it attached here and the desired output. #include <iostream> using namespace std; int...
It appears as though your code does the correct calculations. Just format the output and it will look like the desired output. printf("%-10s%10s%10s\n", "day", "start", "end"); for(int i = 0; i < 30; i++) printf("="); printf("\n"); for (int i = 0; i < num_of_days_to_multiply; i++) { printf("%-10u%10.2lf", ...
66,467,531
66,467,939
XPath query is not working in IXMLDOMDocument2, but passes online XPath tester
In the below XML, I'm trying to use an XPath query to select the first <Event> node that has RenderingInfo/Task = StartRemoteSessionRdpClientBegin. <Events> <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Guid="{9e814aad-3204-11d2-9a82-006008a86939}" /> <Even...
Your XML involves namespaces, so you have to take that into account in your XPath query. This is documented on MSDN: Specify Namespace when you query the DOM with XPath For example: HRESULT SearchTraceFile(std::wstring fileName) { _bstr_t xPath = L"/Events/e:Event[e:RenderingInfo/e:Task=\"StartRemoteSessionRdpClien...
66,467,562
66,472,817
Variadic template inheritance order and syntax
I am trying to implement a signal/slot system via templates to get into some advanced usage of templates. I looked up existing implementations and found one at https://github.com/skypjack/eventpp. I have been trying to understand how it works and pretty much figured it out but there are still some things I can't wrap m...
Why is this template instantiated first? I would have expected it to be last (before Bus). constructor call and instantiation are different thing Bus<KeyPressedEvent, KeyReleasedEvent> inherits from BusBase<2, KeyPressedEvent, KeyReleasedEvent> which inherits from BusBase<2, KeyReleasedEvent> which inherits from BusB...
66,467,713
66,487,012
Composing complex regular expressions with "DEFINED" subexpressions in C++
I'm trying to write a regular expression in C++ to match a base64 encoded string. I'm quite familiar with writing complex regular expressions in Perl so I started with that: use strict; use warnings; my $base64_regex = qr{ (?(DEFINE) (?<B64>[A-Za-z0-9+/]) (?<B16>[AEIMQUYcgkosw048]) (?<B04>[AQgw]) ) ^( ...
I took a suggestion from the comments and checked out "boost" regex since it supports "Perl" regular expressions. I gave it a try and it worked great! #include <boost/regex.hpp> boost::regex base64_regex( "(?(DEFINE)" "(?<B64>[A-Za-z0-9+/])" "(?<B16>[AEIMQUYcgkosw048])" "(?<B04>[AQgw])" ...
66,467,762
66,467,862
Compare 2 char arrays C++
I am trying to compare 2 char arrays but in the end, I made my program useful and now nothing shows in the console, I am trying to use pointers, but I do not know how to use the pointers with arrays, and functions, I think that the major problem is on the pointers. #include <iostream> using namespace std; // return tr...
In the statement if (match(ptr1, ptr2)), ptr1 and ptr2 are uninitialized pointers. More importantly, inside of match(), you are comparing pointers, not the data the are pointing at. And your algorithm is returning the wrong result anyway. Try this instead: #include <iostream> using namespace std; // return true if tw...
66,468,051
66,469,446
Adding Multiple Windows to WinAPI Application
I am building an app with WinAPI that consists of basically two main parts: a panel on the left hand that is always shown and an area on the right that changes based on which screen is shown. Currently the left-hand, static area is just being drawn onto the main window; however, for I don't believe that I can simply dr...
As Remy said, you only need to re-register a new window and then create it as a subclass in the main window. You don't need to set the title and maximize and minimize buttons in setting the style, and you can also decide by yourself whether you need to deal with the WNDPROC function of the subclass. Here is a sample(In...
66,468,131
66,468,146
Universal reference seems not working, compiler take parameters as r-value
Here's an example: #include "type_traits" #include "string" template<typename T> class Wrapper { public: explicit Wrapper(T &&t) : t_(std::forward<T>(t)) {} T &Get() { return t_; } private: T t_; }; int main() { std::string s1; Wrapper<std::string> w1(std::move(s1)); std::string s2; Wra...
The constructor Wrapper::Wrapper is not template, the parameter is just not declared as forwarding reference. Given Wrapper<std::string>, Wrapper::Wrapper always takes parameter as rvalue-reference, i.e. std::string&&. function parameter of a function template declared as rvalue reference to cv-unqualified type templ...
66,468,237
66,468,307
C++ decimal placement
how would I make it so when i enter 2.785 for the input question the output will display the variable question as 2.79? I tried using setprecision but for some reason it is not working unless i am doing it wrong here is the user input question and what it should be: Enter positive daily growth % (.1 must be entered as ...
Floating point arithmetic The reason why it is challenging is that floating point cannot be represented accurately when you perform operations on them. See wikipedia article It is a very intesting topic, if you have a bit of time, take a look at explanations about floating point and how its representation inside the co...
66,468,370
66,468,432
istringstream split_string(line) how to update the split_string while changing line without using while loop?
line = "hello 2021" istringstream split_string(line); was a useful code to get the values from a string, i.e. split_string>>str>>temp_double; However, suppose that the value of line was changed, i.e. line="hello world" ,and one wanted to write the following code with the updated value of line. split_string>>str1>>st...
In the C++20 standard std::istringstream now has an str() method that allows replacing the contents of its internal buffer. This functionality is not available in C++17 or earlier. Before C++20 the closest alternative would be to use std::stringstream instead of std::istringstream and use << to put stuff into the strin...
66,468,760
66,471,044
Cast to negated unary expression fails in function templates
I use the following code to compare arithmetic types. The class template equal compares the given arguments for equality and stores the result in the member variable result. The class template also provides a cast operator to bool in order to be evaluated in conditional statements. I also provide a template deduction g...
I kinda think it is a bug in clang. I fiddled around with this for a while. I tried: return equal( t1, t2 ).operator !(); which clang didn't like, but the other compilers did. Clang said: <source>:69:27: error: member reference base type 'equal' is not a structure or union return equal( t1, t2 ).operator !(); an ...
66,469,136
66,472,250
How to store back the nested response data in protobuf?
I'm using GRPC to remote call the database and store the data in the response format given by the .proto file. My program is based on CPP programming: // similar .proto file message FinalResponse { repeated IntermediateResponse finals = 1; } message IntermediateResponse { string name = 1; InitialResponse f...
Looks like it was the server side issue probably, now with the same changes, it is able to store the response properly. Maybe server went down for some time and returned error.
66,469,437
66,469,749
c++ program that inputs a sentence from the user and counts the number of words and characters in the sentence
I am getting an error and also not getting the desired output what wrong could be here. [Error] Empty Character Constant #include <iostream> #include <conio.h> using namespace std; int main() { int countch=0; int countwd=1; cout<<"Enter a sentence: "<<endl; char ch='a'; while(ch!='\r') { ...
Try This #include <iostream> using namespace std; int main(){ int character_counter = 0, word_counter = 0; cout << "Enter a sentence: " << endl; char character, previous_character; while (character != '\n'){ scanf("%c", &character); if (character == 32){ if (character_co...
66,470,200
66,490,483
How to build Google tink library using bazel in C++?
I want to use Google tink library for my app. I bound my code using android ndk. However, I couldn't build Google tink library with bazel. I have tried their examples on github (https://github.com/google/tink). Moreover, I don't have any experience with bazel. Hence, if anyone knows how to build Google tink library in ...
When the README.md was written, the entire project was in a single Bazel workspace. Nowadays the examples subdirectory is it's own separate workspace, so you need to cd into it before executing bazel. Correct instructions: # Build the code. git clone https://github.com/google/tink cd tink/examples/cc bazel build ... #...
66,470,294
66,470,464
How member functions are implemented in C++?
I read somewhere that member functions are just like normal function in C++ but with an additional implicit this argument. So I thought this program would be unable to distinguish between two func. But the program ran successfully. So was the statement stated above is wrong? #include <iostream> class MyCls { publi...
Looking at this site, just to pick a tutorial among others if you google the exact same question, you'll find this Member functions are the functions, which have their declaration inside the class definition and works on the data members of the class. The definition of member functions can be inside or outside the def...
66,471,107
66,471,642
How to retrieve the first element of each vector of a matrix in C++?
Given that the matrix is defined as: using matrix = std::vector<std::vector<double>>; I'm trying to print the first element of each vector in this matrix. std::vector<double> print_first_val(const matrix& all_val) { std::vector<double> first_vals; long unsigned int size_of = all_val.size(); for (unsigne...
You are trying to save as int: int num = all_val[i][0]; What is supposed to be a double: using matrix = std::vector<std::vector<double>>; So change the type specifier of num to either double or auto: auto num = all_val[i][0]; Below, a reproducible example: #include <iostream> #include <vector> using matrix = std::v...
66,471,350
66,595,194
Expose C# service to C++ COM client
I have lot of function calls and back events in an .NET dll. which I want to expose above as service. This new service will be consumed by new .Net application and an old COM C++ application.(two way communication since events with data will be fired from service to clients and client will make function call on service...
Even tough SignalR-Client-Cpp suits our need. After trying out it, we found that its not actively supported and not easy to use on windows. So ended up into GRPC.
66,471,452
66,472,227
What's the difference between ( this ) and ( std::ref(*this) )
I used to create a thread in this way std::thread(&A::Func, this); But I find there's another way std::thread(&A::Func, std::ref(*this)); What's the difference between them?
In the context of launching a thread running a member function of a class A, those calls are equivalent. The first is like void compiler_created_on_new_thread(A * a) { a->Func(); } The second is like void compiler_created_on_new_thread(A & a) { a.Func(); } If instead A were a namespace, they would be distinguishable ...
66,471,556
66,472,030
C++ thread can't abort after being joined
So I have 2 threads running in my program and I eventually want them to terminate when this function is called: void AutoClicker::TerminateThreads() { programrunning = false; clicker.join(); hotkeyLoop.join(); terminateThread = true; } And after that is called the threads are supposed to run this code:...
Two things to start off with: Do not call std::terminate(). It is not a nice way to tear down your program, and may leave open files and other OS resources hanging. Also, it applies to your entire program, not just the thread you call it in. If you want a std::thread to terminate, then just return from it or allow it ...