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
64,104,291
64,104,776
Should I use Qprocess on the stack
is there any draw back of creating QProcess on the stack, for something trivial like this void Utils::changeFont() { QString command("book"); QStringList arguments({"opensans", "10"}); QProcess fontProcess; fontProcess.start(command,arguments); fontProcess.waitForFinished(); } i have 10 Utils obj...
The issue here is not related to creating QProcess "on the stack". In fact, stack is a misnomer: what you're really asking is "can I create QProcess as a local variable". Yes, you can, of course! But such a QProcess is useless, because you're not supposed to use the waitFor methods - not ever. They are a horrible API. ...
64,105,054
64,106,680
Concatenate const char at compile time when one of them is a function parameter
I'm trying to add a filename prefix to each log string in spdlog. The Spdlog formatting string looks as this: Test log {} Logs are written as this: spdlog::error("Test log {}", value) I'm trying to wrap this call and concatenate additional {} before formatting string, so I can pass the prefix of the file there. static ...
Parameter value cannot be used for constexpr. You might turn: template<typename... Args> constexpr void critical(const char fmt[], Args&&... args) into template <char... cs, typename... Args> void critical(std::integer_sequence<char, cs...>, Args&&... args) { constexpr char fullFmt[] = {'{', '}', ' ', cs... , '\0'...
64,105,084
64,105,191
Why can I pass iterators of two different containers into sort?
I was taking part in an online programming contest earlier today. There was a problem where I had to deal with three input vectors and one of them required sorting. My code, in a simple example, looked as follows: vector <int> a; vector <int> b; . . . sort(begin(a), end(b)); Notice how I mistakenly(/stupidly) made a t...
Why do C++ algorithms allow this and why hasn't the C++ committee done something about it? Because it's not something that can be fixed. Lets say you have an array like int arr[500]; and you wan to sort it. You would pass arr and arr + 500 as the arguments to sort but those are just int*'s. They hold no other info...
64,105,219
69,092,707
Will C++20 modules change the anatomy of static and shared libraries?
Traditionally, C++ libraries are made of a header file + the implementation compiled in a binary file (.a, .so, .dylib, .dll, ...). The header file is #included in the source code and the binary part is linked to the final executable. Will modules from C++20 change such layout? If so, will operating systems have to upg...
Absolutely. Modules are a very different type of representing library code to users than conventional header/libraries. The main advantage of a module is to have it parsed to the level of the abstract syntax tree (AST) by the compiler. This only happens once per module -- in contrary to every time you include a particu...
64,105,232
64,107,654
Infix to Postfix short trick
Does anybody know a shortcut or short trick for infix to postfix conversion for multiple-choice questions exam? I know the method using stack but is there any fast technique for it? for example a+b*(c^d-e)^(f+gh)-i to abcd^e-fgh+^*+i-
Write the expression as a tree (leaves are values, internal nodes are operators), preserving the left-to-right order of values, and then write down its post-order traversal.
64,105,905
64,106,185
Qt Qml How to set the value of the QSG_INFO parameter to 1
I got stuck with the problem that my application on some PCs loads the processor very heavily, and does not load the video card at all. When I went to figure it out, I came across this article: https://www.qt.io/blog/2017/01/18/opengl-implementation-qt-quick-app-using-today It describes the method of debugging, and say...
To set an environment variable you can use qputenv(): #include <QtGlobal> int main(int argc, char *argv[]) { qputenv("QSG_INFO", "1"); QGuiApplication a(argv, argc); // ... or you can set when launching the executable: QSG_INFO=1 ./your_executable
64,106,147
64,106,464
C++ returning pointer using parameter - comparison between distinct pointer types lack a cast
I'm trying to create a function called void find(int id, Student** s) that searches the array for the student with the id specified in parameter id, and returns that student pointer using parameter s. The task says I must use the parameter to return this data and to not use the return value. I'm a little confused by wh...
The second argument in the function says "A pointer to a pointer to Student" To return it, you'll need to set it to a pointer of Student. Taking a pointer of one of the student array is done like this: &student[i]. Once you have the pointer, you need to store somewhere, and you'll store it inside the given pointer-to-p...
64,106,998
64,107,444
The way to check that class has operator() with specific template
I'm trying to use SFINAE technique to check - does class/struct have operator() with specific template declaration, for example (little bit simplified): struct Simplified { // 1st operator - I need to detect its presence template<typename T, int I> void operator()(T& val1, double val2) { std::cout << std::...
Well... not sure to understand what you exactly want but... I propose the following class template<typename Fn, int I, typename T> class TemplatedOperatorCheck { template<typename U, void(U::*)(T&, double)> struct SFINAESimple { }; template<typename U> static std::true_type Test(SFINAESimple<U, &U::op...
64,107,007
64,107,856
Checking membership in large ordered list?
I have a piece of code in C that generates a lot of numbers sequentially, and I want to check if these numbers are in a sorted list. The list was created using numpy, and has ~109 elements, which, as mentioned, are ordered from least to greatest. What is the absolute fastest way for my C code to check if its result is ...
Your array is sorted. Just use the C standard library bsearch function with an array. If you've produced them with Numpy, then write these to file as a binary, in order, i.e. import numpy as np array = np.arange(1, 3000000, 3, dtype='int32') array.tofile('array.bin') and use mmap if in Unix/Linux to map it into memor...
64,107,248
64,117,767
What is the problem with this code? It never ends (Top View of a Binary Tree)
Problem Statement : Print the Top view of the binary tree My approach : I maintain a queue which has a pair inside it each for root->data and horizontal distance(hd). I push the root with the hd in the queue and add it to the map which contains the hd and the root->data. Then I pop from the queue. Now, if there are an...
There are two issues in your code. One is that you're only storing the node values in the queue instead of the node pointers. So your traversal condition if(root->left) is only checking for the children of the root node. This leads to an infinite loop because we are not traversing past the root node. The second issue ...
64,107,759
64,108,104
Linux API read/write and c++ bitset
How to use C++ bitset container with Linux API read/write functions? Something like this: #include <vector> #include <bitset> #include <fcntl.h> // Linux API open #include <unistd.h> // Linux API read,write,close using namespace std; int main() { // Some 8-bit register of some device // Using vector...
What you can do is, to convert to a std::bitset before you write the data. Something like std::bitset<8> controlRegister = 0b00101100; // Use some consts and combine them // with bitwise or (|) to make this more // human readabl...
64,107,912
64,108,199
is there a way that my program can make subsets of any given size?
I am facing an issue. #include <iostream> using namespace std; bool Check(int arr[], int size, int con) { for (int i = 0; i < size; i++) { if (arr[i] == con) { return true; } for (int j = i+1; j < size;j++) { if (arr[i]+arr[j] == con) ...
Here's a simple example of a recursive implementation of your function: bool Check(int *arr, int size, int con, int curr_sum = 0) { for (int i = 0; i < size; i++) { int new_sum = curr_sum + arr[i]; if (new_sum == con || Check(arr + i, size - i, con, new_sum)) { ...
64,108,134
64,109,793
How to get address of user-defined function?
I am trying to hook a user-defined function. (via DLL injection and inline function hooking) To do that, I need to get the address of the function to hook in process memory. I tried various methods to find the address, and finally came up with the equation below. (offset) = (Address of function in EXE file) - (Image b...
Module relocation occurs as a whole. Individual sections are never moved with respect to the image base. The offsets (RVA) of each section are hardcoded in the module header. For example: # Name VirtSize RVA PhysSize Offset 1 .text 000C44C1 00001000 000C4600 00000800 2 .data 00000FEC 000C6000 00000E00 000C4...
64,108,151
64,208,212
How to resolve parsing error in ANTLR CPP14 Grammar
I am using the below ANTLR grammar for parsing my code. https://github.com/antlr/grammars-v4/tree/master/cpp But I am getting a parsing error while using the below code: TEST_F(TestClass, false_positive__N) { static constexpr char text[] = R"~~~(; ModuleID = 'a.cpp' source_filename = "a.cpp" defin...
Below changes in Lexer that helped me to resolve the raw string parsing issue Stringliteral : Encodingprefix? '"' Schar* '"' | Encodingprefix? '"' Schar* '" GST_TIME_FORMAT' | Encodingprefix? 'R' Rawstring ; fragment Rawstring : '"' // Match Opening Double Quote ( /* Handle Empty D_CHAR_SEQ...
64,108,775
64,108,928
mutex on boost::asio::write not works
I'm trying to make an async tcp client(it's gonna not waits for result of a request before sending another request). A request method looks like: std::future<void> AsyncClient::SomeRequestMethod(sometype& parameter) { return std::async( std::launch::async, [&]() { // Gonna send a...
You did put the lock guard around writing to the asio. There is, as you can see, no guarantee the other end will have them processed with the same guard. You should rather put the guard where you need it, on writing the json, out of the asio: void AsyncClient::write(const std::string& strToWrite, boost::system::error_c...
64,108,839
64,112,438
How can I alter an array from inside a function in C++
I am trying to write a c++ rk4 algorithm and I seem to be running into the same error no matter what I try. I can compile the program but I keep getting a zsh: segmentation fault (core dumped) ./main. I believe that the problem is within the rk4 function here: void funcs::rk4(double *p_vec, double h) { double *k0...
A problem that still remains even with the latest version of funcs::rk4() is that all your pointers (k0 ... k3) point to the same static buffer inside funcs::force(). Therefore, when you are computing p_vec[ inst ] += ( ( k0[ inst ] ) + 2*( k1[ inst ] ) + 2* ( k2[ inst ] ) + ( k3[ inst ] ) )*( h/6 ); all of k0 ... k3 ...
64,109,210
64,135,919
Is this the correct use of OpenMP firstprivate?
I need to parallelize the following: for(i=0; i<n/2; i++) a[i] = a[i+1] + a[2*i] In parallel, the output will be different than in sequential, because the "to read" values will be "rewritten". In order to get the sequential output, but then parallelized I want to make use of firstprivate(a). Because firstprivate gi...
As you noted, using firstprivate to copy the data for each thread does not really help you getting the data back. The easiest solution is in fact to separate input and output and have both be shared (the default). In order to avoid a copy it would be good to just use the new variable instead of b from thereon in the co...
64,109,550
64,109,614
Am I suppose to use virtual destructor=default to properly handle classes with virtual functions?
I forgotten my C++. From memory if I have virtual functions I should have a virtual destructor. So I wrote the below. However I get a linker error about B destructor (but not A). Is the correct solution virtual ~A()=default? It seems to work but I feel like I'm missing something $ clang++ a.cpp /usr/bin/ld: /tmp/a-a25a...
Although a pure virtual destructor virtual ~A() = 0; is legal standard C++, you'd need to write a function body for this as destructors are not overridden. (If you don't then the linker will fail as you observe.) Since C++11 the simplest way of making your class polymorphic is to make the default destructor virtual, w...
64,109,842
64,169,982
ReOpenFile Windows API fails with "error invalid name" when reopening a file in C:\windows\system32
I would like to know whether anyone can explain a reason for ReOpenFile failing with "error-invalid-name", when CreateFile has successfully opened the file. Here are the details: I open a file C:\Windows\system32\unit_test.txt using CreateFile, and it opens fine. When I later attempt to change permissions using ReOpen...
As soon as I recompiled my "minimal example" as 32-bit rather than 64-bit, it started to exhibit the problem of ReOpenFile failing. This lead me to an article that explains the situation: Accessing files from System32 directory using 32 bit application on 64 bit machine Quote from the article: " As you seen, on a compu...
64,110,079
64,110,109
How to define the value type for iterator which points to an element in another container in c++
The purpose I want to achieve is that: I have an unordered_map<int, list<int>::iterator> mp and a list<int> lst. How can I store the iterator of an element in lst. And later, by using the iterators in map, I can manipulate (e.g.,erase) the element in the list. (Assume free of iterator invalidation problem) The followin...
You are putting the wrong kind of iterator into the unordered_map: unordered_map<int, list<int>::const_iterator> mp; // ... mp[1] = lst.crbegin(); // error, const reverse iterator mp[1] = lst.cbegin(); // ok If you want the value type of the unordered_map to contain reverse iterators, you need to specify that: unor...
64,110,303
64,110,343
How to handle null value in sqlite prepared statement
Consider a database, which models a directory tree and each file or folder is a record: CREATE TABLE "tree" ( "id" integer, "parent_id" integer, "name" varchar(255), UNIQUE("parent_id","name"), PRIMARY KEY("id"), FOREIGN KEY("parent_id") REFERENCES "tree"("id") on delete cascade ); The node at root has parent_id s...
You want null-safe equality. In SQLite, you can use is: select * from tree where name = ? and parent_id is ? How this works is explained in the documentation: The IS and IS NOT operators work like = and != except when one or both of the operands are NULL. In this case, if both operands are NULL, then the IS operato...
64,111,055
64,111,388
C++ arrays, expression must have a constant value
Ok, so I am new to coding and am trying to learn c++. I am making a program to verify a password has uppercase, lowercase, and a number. I feel that the solution will be a simple one but I cannot for the life of me work it out. using namespace std; string password =""; cin >> password; I can validate this...
Ah I finally got it. Thanks to user4581301 for telling me that a string already is an array of characters. This hint gave me ideas of how to solve the problem. I actually managed to get rid of the new array entirely and instead search through the string. instead of char passwordHolder[password.length()]; I could get ri...
64,111,066
64,111,103
Starting a std::functional object in a thread, inside a class
I have a member function pointer and I'm trying to invoke the function in one of the member function. The function pointer is set using a lambda. class CFoo { std::function<void(int a, int b)> m_fFunc; public: CFoo() {} void Init() { m_fFunc = [](int a, int b) { printf...
Your issue is that an std::function is not a member function,so you don't need to pass this or use the pointer-to-member syntax. void Call(int a, int b) { std::thread th(m_fFunc, a, b); th.join(); } If you wanted to call a member function directly, then you could do something like this: ...
64,111,153
64,111,154
How can I disable a C/C++ `-Werror` build error in Bazel? (AKA: how to turn OFF specific warnings already turned on by `-Wall -Werror`)
I'm getting the following error when building: ...has undefined behavior [-Werror,-Wundefined-reinterpret-cast] The Bazel build completely stops since this clang (llvm compiler) -Wundefined-reinterpret-cast warning is converted into a build error by -Werror. How can I force the build to continue and produce a binary...
The answer is to use the -Wno-error=<name> build flag, as described by gcc here (note that clang's options are modeled after gcc): -Werror= Make the specified warning into an error. The specifier for a warning is appended; for example -Werror=switch turns the warnings controlled by -Wswitch into errors. This switch ta...
64,111,575
64,111,613
Adding elements to a 2D vector (Vector of vectors) C++
So lets say i have the: vector<vector<int> > temp; so it'd just be an empty 2d vector and pretend it's filled with 0s so it'd look like: 0 0 0 0 0 0 0 0 and let's say I want to add something to that vector, like if I had: int x = 3, y = 4; I want to push these onto the vector so that it looks something like: 0 ...
Since temp has inside a vector<int>, the correct syntax would be: temp.push_back({x,y}); Using the brace-initializer list, this creates another vector consisting of two elements, x and y, and pushes that back onto temp.
64,112,146
64,112,198
Program doesnt find relative file when run from withing Visual Studio
I am using visual studio 2019. I was doing this process to try to read the data from files but on the visual studio I am unable to. It just shows blank screen, no error or such. Then I used an online ide but the program was able to read the file online. I can't figure out the issue. It's the same code that is used on b...
When you run your projects from within Visual Studio, your current working directory becomes where your main.cpp resides (see the note at the end), not the executable directory. Therefore your program can't find the names.txt and hence what you see. So you can verify that by going into your Release/Debug directory (dep...
64,112,683
64,112,798
How to access a variable from .cpp file in a .h file
Consider this scenario: File1.cpp: double dir = M_PI/2; hFile1.h: void printdir () { cout << dir; } Main.cpp: #include "hFile1.h" int main () { printdir(); } This obviously will not work because hFile1.h will throw an error: "use of undeclared identifier 'dir'". In this example, I want to be able to access and use t...
You need to use keyword "extern" in hFile1.h as below. I tested, it worked. extern double dir; void printdir () { cout << dir; }
64,112,723
64,115,247
Drawing a colored mesh in CGAL
In CGAL have a Surface_mesh<Point_3> with Surface_mesh::Property_map<Surface_mesh::Face_index, CGAL::Color>. I use CGAL::draw() method to draw this mesh, however the different colors of faces don't reflect. What am I missing?
The current version of basic viewer of Surface mesh does not take into account the color of faces. However, it is easy to change the code. Have a look to the file draw_surface_mesh.h. Add a functor MyColorFunctorSM (inspired by the existing DefaultColorFunctorSM) that returns the color of a face given its index Replac...
64,113,243
64,113,319
C++ - String capacity pattern
I noticed that the string capacities in C++ follow this pattern: initial string size is 15 for any string that is larger than a particular size 'block', the capacity is doubled. Here are the string capacities for strings up to length 500: 15 30 60 120 240 480 960 Capacities were found with the following C++ program:...
Doubling is a well known method. It amortizes the cost of reallocation making push_back a constant time operation (as it is required to be). The 'obvious' alternative of adding a fixed size would make push_back a linear time operation. Other patterns are possible though, any multiplicative increase would work theoretic...
64,113,465
64,114,196
Reading from a file and into a dynamically allocated array of type Student in C++
I thought I had a decent understanding of fstreams and struct's, but for some reason I can't figure out what's wrong with my code. The file I'm reading from starts with an integer 'n' that represents the amount of students in the file, it's then used as the size of the dynamically allocated array of Students. I go on t...
The problem is not with your reading code. That is actually reading the file data just fine. The real problem is in the display code. You are calling display() on the 1st entry in the array each time, and display() is ignoring the Student that is passed to it, instead displaying the data of the Student it is called on...
64,113,579
64,114,012
c++ split a file into records when blank space is found?
I have a file like this 2.7388 0 2.4670 3.6384 1 24.5927 8.7844 0 10.6871 11.2892 0 2.6507 19.6054 1 16.8974 25.8811 0 8.0084 For example i'll take the first row 2.7388 0 2.4670 . Im trying to accomplish something like the following 2.7388 = double x 0 = int y 2.4670 = double z My attempt struct fileReader{ ...
(Recommended) More direct way to do this : #include <fstream> #include <iostream> #include <vector> struct Data { double x; int y; double z; }; std::vector<Data> fileReader(std::string fileName) { std::vector<Data> result; std::ifstream file(fileName); Data data; while (file >> data.x >> data.y >> da...
64,114,161
64,114,291
Is there a way to control Cursor Point in std::fstream?
I'm reading big datas from .txt file(s) like 1000-5000 persons data. and they saved in a file with alegorithm that i can easily read datas back. but to do it more easy, I'm seeking the way to control File cursor point. for example in console app you can use VT100 Escape sequences like \033[3A (3 line up) \033[2D (2 Let...
std::fstream can be seen as a linear stream of single bytes. As this, there is no way to use something like "cursor up" which as std::fstream has no knowledge of lines in the file. What you can do is asking for the current position you are currently reading tellgor writing with tellp. After keeping such positions, you ...
64,114,238
64,115,133
How to pass a cstring as a function parameter/argument
I have a small program that prints out the capital form of each letter of a word, but I get the error signed/unsigned mismatch when I compile it because I'm passing a cstring as a normal string in this program. How do I pass it correctly so that I can still use text.length()? Here is the error that I get "Tester.cpp(22...
The simplest way to handle passing sentence as a string is to enclose it in a braced set, to provide direct initialization to the parameter std::string text eg.. for ( ; ; ) { std::cin.getline(sentence, 100); if (*sentence) capitalizeFirstLetter({sentence}); } This allows the ch...
64,114,701
64,114,940
Why does this code compile without errors in C++17?
I have deleted all the constructors, even then following code is working perfectly. How and why ? class Ax { public: Ax() = delete; Ax(Ax const&)=delete; Ax(Ax&&)=delete; void operator=(Ax const&)=delete; void operator=(Ax&&)=delete; void print() { cout << "Hello \n"; ...
(For a thorough walk-through of this topic, see the blog article The fickle aggregate) Aggregate initialization Class Ax is an aggregate in C++11, C++14 and C++17, as it has no user-provided constructors, which means that Ax{} is aggregate initialization, bypassing any user-declared constructors, even deleted ones. st...
64,115,197
64,115,386
Classes and code throwing errors and strange unexpected behavior
I am working on a tiny project. And I am running into some issues, I've been trying to figure this out for weeks now. But, I finally decided to come to SO, and post this here. I am trying to get two of my functions to work properly: Remove(...) and SearchWithName(...), I am using the C++ Range-based for loops. But, the...
What's the compiler error You did not define Employee(std::string name, std::string address). You only declared that. std::__cxx11::basic_string<char, std::char_traits, std::allocator> may look bogus, you may just treat it another name of std::string. What would happen to your code if it compiles Your EmployeeArray::em...
64,115,224
64,115,967
C++ Comparison operators for std::unordered_set
This post raised a question of the absence of >, < .. comparison operators for unordered containers in C++. From the reply it looks meaningless to have those. However, I checked Python and see that set type supports subset and superset operations. Python set is a hash table. We can easily do: {'1', '6', 't', 'j'} > {...
Python's sets have a partial order, not a total order, based on the subset relation. E.g. neither { 1, 2, 3 } < { 2, 3, 4 } nor { 1, 2, 3 } > { 2, 3, 4 } are true, but { 1, 2, 3 } == { 2, 3, 4 } is false. You can write a < that behaves like that, but as noted in the comments, you can't put it in namespace std, so it wo...
64,115,301
64,116,787
How to efficiently bind C-style function (for Mono) to C++ style class methods
I'm using Mono to bind C# code to C++. After setting up Mono domain etc. you bind functions accordingly: C++ side: mono_add_internal_call("Camera::SetPerspectiveVerticalFOV", Camera_SetPerspectiveVerticalFOV); float Camera_SetPerspectiveVerticalFOV(Camera *camera, float verticalFov) { camera->SetPerspectiveVertica...
As Botje suggested, std::invoke is what I was looking for.
64,116,463
64,116,581
C++ Square Bracket Syntax
On the cppreference article about SFINAE, I came across this syntax which I do not understand: template <int I> void div(char(*)[I % 2 == 0] = 0) { // this overload is selected when I is even } template <int I> void div(char(*)[I % 2 == 1] = 0) { // this overload is selected when I is odd } I get that ...
Arrays of size 0 are illegal in C++ so a particular overload is chosen based on the value of I: when I is 5, char(*)[I % 2 == 0] would be a pointer to an array of size false, i.e. zero, while the other array pointer is perfectly legal. = 0 is just a default ignored argument value to save you from typing (0) every time ...
64,116,578
64,134,504
Getting handles to the credentials of a domain user from a process launched by a local user on Windows 10
Background: Computer mycomputer is running Windows 10 and is joined to domain mydomain.com. A user is logged with local account mycomputer\localuser on mycomputer. The user also knows the password of domain account mydomain\domainuser. The service principal name myprotocol/domainuser is registered in Active Directory ...
To obtain credentials other than those associated with the current logon session, populate a SEC_WINNT_AUTH_IDENTITY structure with information for the alternate security principal. Pass the structure to the AcquireCredentialsHandle function using the pAuthData parameter. And this micrsoft example demonstrates a client...
64,116,632
64,117,122
Getting compile errors when compiling gnu cgi for web project
On my raspberry pi I am using c++ to write a web project. I am following C++ CGI. I installed gnu's cgi library using apt-get installed libcgicc3. When I compile the form g++ -o cform.cgi cform.cpp i am getting the following error. Fatal error cgicc/CgiDefs.h no such file. How do I find the cgi library. I have seen ...
You're almost there. You need to install the libcgicc-dev package instead, that containers header files and the library to link to. To link with the library (called libcgicc.so): g++ -o file.cgi file.cpp -lcgicc
64,116,637
64,116,731
std::make_pair automatic type deduction?
Consider this function: std::pair<int, double> getPair() { return std::make_pair(0, 0); } Why does this compile? Shouldn't make_pair return a std::pair<int, int> which is incompatible with std::pair<int, double>? Where is the conversion from int to double taking place? Link to example code: https://ideone.com/Zq6o...
std::make_pair(0, 0); indeed creates a std::pair<int,int> object. But, you are incorrect about incompatibility of pairs. They are compatible if their arguments are. See cppreference: // #4 template< class U1, class U2 > constexpr std::pair<T1,T2>( const pair<U1, U2>& p ); // #5 template< class U1, class U2 > constexpr ...
64,116,744
64,116,807
How to check the type of the parameter sent in a template?
I'm trying to create a simple logger which logs different messages to disk. The logger is a simple class of which I've overridden the << operator and, in order to save the messages, I send an enum value signaling to save what has come so far. basically flush everything to the disk. This is how I intend on using this lo...
You have it almost correct, if constexpr(std::is_same<T, Logging::Mode>::value) is what you want in C++17. Without constexpr the body of the if statement is compiled no matter the condition, this did generate the error about comparing arrays with enums even though the branch is never taken in such case. 'operator==' (o...
64,116,916
64,118,141
C++ Cannot call function with stack template
Please tell me what could be the problem. I have 2 of my own stack classes (stackm and stackl), and stack sort function: template <class TStack> void quick_sort_stack(TStack &s, TStack L, TStack G, TStack E) { // Sort stack } To sort my arrays I call the functions: template <typename T> void quick_sort_stack(stackm<T>...
I had a structure like this: template <typename T> void quick_sort_stack(stackm<T> &s) { quick_sort_stack(s, stackm<T>(s.size()), stackm<T>(s.size()), stackm<T>(s.size())); } template <typename T> void quick_sort_stack(stackl<T> &s) { quick_sort_stack(s, stackl<T>(), stackl<T>(), stackl<T>()); } template <typ...
64,116,931
64,117,065
C++ C-style array size limit
I am trying to create a 2 dimensional int array of size 800. This is my code: #include <iostream> int main() { int array[800][800]; std::cout << 1; } My problem is that it never prints 1. I am using g++ as my compiler so it might have something to do with it's inner workings. Furthermore, I couldn't find anywh...
Does anyone have an idea where this limit comes It comes fromn the language implementation. The space available for automatic storage is typically limited to one or few megabytes (potentially less on embedded systems) and that space is shared with all automatic variables on the same thread of execution. Since this ar...
64,117,602
64,117,683
Why is this c++ program to reverse a word not working
I am extremely new to c++ and wrote this program to reverse a word. What I tried was to basically loop through an array and swap first letter with the last, second with the second last etc. However the result is some wired characters ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠Ω ⌠7p≈╗. I don't want a work-around since there are plenty of example...
Problem is what sizeof(word - i) actually does. Short answer: it returns pointer size (4 or 8). More detailed answer: word has type char[10] and size 10 when you do word + 1, the compiler will decay array to pointer to char to be able do this operation. So result type is char * now sizeof(char *) is 4 or 8 depending o...
64,117,940
64,224,599
Pass numpy's include dir to Cmake from Setuptools
I have a C++ library which I have successfully exposed to python using Pybind11. In the CmakeLists.txt file, I have added the numpy include like this: include_directories("C:\\Python37\\Lib\\site-packages\\numpy\\core\\include") This works, but is undesirable. I would like to pass the numpy include directory from my se...
Is your cmake build using the wrong numpy path or not finding numpy at all? If it's the wrong path, you could try prepending instead of appending numpy.get_include(): ext.include_dirs.insert(0,numpy.get_include())
64,118,000
64,122,115
Using passed argument list in a function
I'm trying to build a Thread Manager system in C++, which I give commands to, and if there is a thread available, it starts working. I made a template, because i don't assume how a function should look like that gets passed to the system, and because I want it to work on functions in general. The whole concepts is theo...
As you use C++, avoid C-ellipsis and use variadic template: That would fix your compilation issue: template <typename Func, typename ... Args> void ThreadManager::Run(Func func, Args... args) { using namespace std::literals::chrono_literals; while (!is_free_thread_available()) std::this_thread::sleep_for(1ms);...
64,118,359
64,118,575
I'm working on heterogenous list that uses std::variant. Is there a way to initialize it every time with a custom set of types for std::variant?
...or to quickly change types inside std::variant in source code. Below is the code inside header files for the list itself and its container-element. // HVector.hh class HVector: public std::vector<HVElem> { public: HVector(); void push(std::variant<Party, Loot> newData); void show(); }; //HVElem.hh class...
Is this just a bad idea of using std::variant in this case? There is too little context, so I have to assume that you are using std::variant because std::variant is what you need. If yes, should I use templates or std::any? std::any is for something very different. std::variant is for a limited set of types, st...
64,118,696
65,765,729
Enable DPI Awareness setting has no effect (VisualStudio 2017)
I want my program to be DPI aware but I don'T want to set the default awareness programmatically because this is not recommended according to the microsoft docs(https://learn.microsoft.com/en-us/windows/win32/hidpi/setting-the-default-dpi-awareness-for-a-process). The Enable DPI Awareness in the project configuration h...
This appears to be a bug in VS2017. If you can upgrade to VS2019 you should upgrade. This solved the problem for me. If you can't upgrade you can right click on the .exe and enable the dpi aware flag in the accessibility settings.
64,118,868
64,121,685
Base case specialization for recursive variadic template
My target is to define a Recursive class, templated on an int N and one or more types T, ...Ts, which should behave like a std::pair with a std::array of N items of type T as the first, and, as second, an optional std::vector of Recursive instances templated on the same N and on the remaining template arguments Ts.......
You have several issues: Your specialization doesn't match your primary template template <int N, typename T1, typename T2, typename ...Ts> struct Recursive; requires at least 3 parameters. I think it should be a specialization and primary template should be: template <int N, typename T1, typename ...Ts> struct Recurs...
64,118,926
64,119,151
How to append c-style string or string literals to std::vector<char*>?
I am trying to append string literals to std::vector<char*> but whatever I try i can not append them. std::vector<char*> vector1; vector1.push_back("examplestring"); // gives warning C++11 does not allow conversion form string literal.. const char* anotherstring = "examplestring"; vector1.push_back(anotherstring); ...
You can use const_cast to cast away const-ness for the sake of passing a const object where a non-const object is expected by an interface. Note, however, that this is just for bridging the interface; the function to which you pass the (casted) const-value (or any other part accessing the passed object) must not alter ...
64,119,481
64,120,812
Cannot initialise a parameter of type QMainWindow: ui->setupUi(this) error
I am new to Qt. I have from the link https://www.bogotobogo.com/Qt/Qt5_QNetworkRequest_Http_File_Download.php the code because I want to learn about QNewtorkRequest class. But when I execute the code I get the error below: here is a part of the source code: #include "httpdownload.h" #include "ui_httpdownload.h" HttpD...
There's your problem. The ui file expects a QMainWindow but your C++ code defines a QDialog. Choose one and fix the other.
64,120,069
64,120,265
Getting stackoverflow error while doing DFS on a graph
I am implementing a depth-first search on a graph to find the minimum sum of all connected components. But I'm getting a stack overflow error. I tried to debug it, but failed to do so. Can anyone please help? Here is the code: #include <bits/stdc++.h> using namespace std; void DFS(int x, vector<vector<int>> graph, ve...
Surely DFS(x, graph, cost, visited, c); should be DFS(graph[x][n], graph, cost, visited, c); You really should have noticed that in the debugger.
64,120,122
64,120,219
Using std::function to store methods of inherited classes c++
Is it possible to do something like this?: // some_header.hpp #ifndef SOME_HEADER_HPP #define SOME_HEADER_HPP class baseclass { public: baseclass(){}; std::map<std::string, std::function<void()>> methods_map; void call_method(const std::string &name){ auto it = methods_map.find(name); if(it...
You're close: &temp->new_meth isn't valid, you can capture temp into a void() functor through one of these ways: objects[0]->methods_map["new"] = std::bind_front(&inherited::new_meth, temp); objects[0]->methods_map["new"] = [&] { return temp->new_meth(); } Notes: objects[0] is an invalid index since you never insert...
64,120,279
64,150,206
C++ alsa api bad recorded quality
I'm trying to record microphone with alsa api on linux, but result is strange sounds like freezed glitchy robot. Recorded pcm data sended by UDP protocol to pcm player endpoint. char* device = "default"; unsigned int rate = 44100; unsigned int channels = 2; snd_pcm_uframes_t frames{}; ...
So the problem is because i'm not specifying period time, period size. And after period manipulation i need retrieve actual values. I have mistake in buffer size formula. Fixed code: ... frames = periodSize; if (snd_pcm_hw_params_set_period_size_near(captureHandle, hwParams, &frames, 0) < 0) throw ...
64,120,648
64,139,780
How to treat output arguments like char** array in python?
I am trying to call C methods from Python script but I am facing an issue while calling the method which outputs char** array as an argument. the method in C layer as follows. helper.c file: //This method takes filename as input and oNames as output extern C int GetNames(char* iFilename, char** oNames) { int oNum...
I've simplified the function to focus on the char** parameter. As your sample function was written it assumes memory was pre-allocated, but there is no interface to indicate the size of the array used for output or the individual strings in the array. In this example, the memory is pre-allocated for a 3-element array...
64,121,152
64,141,028
How to compare floating point in catch2
I am using Catch v2.13.1 What is the correct way to compare float values. I thought the below would fail, but both pass. REQUIRE(1147332687.7189338 == Approx(1147332688.4281545).margin(0.0001)); REQUIRE(1147332687.7189338 == Approx(1147332688.4281545)); However this fails as expected REQUIRE(abs(1147332687.7189338 - 1...
There are a couple of things to consider in the posted example. REQUIRE(1147332687.7189338 == Approx(1147332688.4281545)); This will pass, "unexpectedly". The reason can be found in the documentation (assertions - floating point comparisons). Approx is constructed with defaults that should cover most simple cases. Fo...
64,121,357
64,121,398
How does one correctly format a string on output with variables in C++ 17?
I'm wondering what is the efficient and smart way to output a string to console with variables. I know in C++20 there is std::format which makes this easy, but I'm unsure about C++17. For example, as it could be done in C++20: #include <iostream> #include <string> #inclide <format> int main(){ int a = 13; int...
std::cout << "The respondents of the survey were " << a << "-" << b << " years old\n"; If you find that verbose and/or annoying, use fmtlib as a placeholder for std::format. Or go old-school with #include <cstdio> std::printf("The respondents of the survey were %d-%d years old.\n", a, b); That is not type-safe, b...
64,121,390
64,121,740
!= auto generated from == in C++20?
Is this standard behavior in C++20? I couldn't find anything about it in cppreference. I've just tried both on Clang and on Visual Studio and it works and it doesn't give me any sort of error or warning. I also checked with the debugger to see if operator== was being called and it was! Does C++20 now allows for the aut...
!= auto generated from == in C++20? Is this standard behavior in C++20? Yes. operator!= is auto generated from operator== in C++20. Furthermore, all four relational operators are generated if you define operator<=>, and all of the comparison operators are generated if you define operator<=> as defaulted. What you w...
64,121,490
64,172,155
How to set text for dropdownlist Combobox MFC?
when I change the combobox format from dropdown to dropdownlist, the SetWindowTextW method no longer seems to work? How can I assign text to it in OnInitDialog event? CComboBox m_dropdownlist; whether there is a method as: m_dropdownlist.setindex[0] my dropdown image my desire result
As mentioned in the comments to your question, you can use CComboBox::SetCurSel. It might be worth just taking a moment to think about when you map a combo to a variable. You basically have three ways: You can map to a control variable (a CComboBox). You can map to a value variable of type CString (when the combo is a...
64,121,556
64,124,187
Issue with C++ Serial Communication on Windows
I'm trying to communicate with an Arduino using C++ on windows. The Arduino is waiting for a number and will light up an amount of LEDs specified by the received number. I can successfully open a port and send data to the Arduino, however there is some strange behavior. When I use the built-in serial console in the Ard...
As Julian mentioned in the comments, enabling DTR did the trick. ... dcb.fDtrControl = DTR_CONTROL_HANDSHAKE; ...
64,121,623
64,121,889
C++: Just allow numbers as an input
I want to block all the letters for input in the following code, can you help me with that? #include <iostream> using namespace std; int main() { cout<<"To close this program you need to type in -1 for the first input"<<endl; int m, n; do{ int counter1 = 0; int counter2 = 0; cout<<"Now you need to input two sepera...
When you declare a type of a variable, the variable can't contain anything else than what you have declared. So: You can’t use an int m to input a float. You could however use cin.ignore() (more details here) to accept a user input of "4.1" as "4". Here you go: #include <iostream> #include <limits> using namespace std...
64,121,922
64,122,614
How to get class type from member pointer template type
For sorting user defined typed objects in a flexible way (i.e. by naming a member variable) I wrote a template to generate lambdas to do the comparison. Additionally to chain comparisons of different member variables in case of equality I wrote a second template. It works so far but I want bpth templates to be complete...
You can easily extract the class and type of the pointer-to-member in your first template with some small modifications. template<class Class, class Type> auto order_by(Type Class::* f) { return [f](const Class& smaller, const Class& bigger) { return smaller.*f < bigger.*f; }; }
64,122,365
64,131,973
Is there a "simple" way to have ld output demangled funtion names?
I find very frustrating to have to fix C++ errors happening at linkage time (especially undefined reference errors) due to the fact that all the function names are mangled. An example of mangled name: _ZNK5boost7archive6detail11oserializerINS0_13text_oarchiveEN9galandria8UniverseEE16save_object_dataERNS1_14basic_oarchi...
ld (The GNU Linker) is able to demangle C++ function names. ld documentation on demangling from it's man page: (available here online) --demangle[=style] --no-demangle These options control whether to demangle symbol names in error messages and other output. When the linker is told ...
64,122,915
64,150,846
How to resolve the error: ‘yield’ was not declared in this scope from DallasTemperature library (Arduino)
I'm trying to gather temperature from my temperature sensor and i'm facing this error : /home/myuser/sketchbook/libraries/DallasTemperature/DallasTemperature.cpp: In member function ‘void DallasTemperature::blockTillConversionComplete(uint8_t)’: /home/myuser/sketchbook/libraries/DallasTemperature/DallasTemperature.cpp...
DallasTemperature-3.9.0 came out on 2020-09-02, my project was a little older, I first created it before and I couldn't finish it since. I was using 3.8.0 version, I re-installed it and it worked again.
64,123,221
64,123,308
I have difficulty initialising enum in constructor in C++
I am using enum to initialise the different genders. So my problem is that a do not know what exactly to put in this constructor. class CPerson { private: char* Name; enum class Gender { Male = 0, Female = 1 }; Gender sex; public: CPerson(const char* szName, Gender s) :Name{ nullptr } { ...
Since your enum is part of the class, you need to reference the class name to get access. And since you've made Gender a class instead of a simple enum, you'll have to reference it too. CPerson("Simon", CPerson::Gender::Male); Plus as noted in the comments, you need to make the enum public.
64,123,392
64,123,733
How am i missing last element of an array
I am facing a problem with #include<iostream> using namespace std; bool check(int input) { int count = 0; int temp; int val[] = { 2,0,2,1 }; temp = input; while (temp != 0) { count++; temp /= 10; } int *arr = new int[count]; for (int i = count; i >= 0; i--) { ...
You got the loop counter wrong: for (int i = count; i >= 0; i--) { arr[i] = input % 10; input /= 10; } In the first iteration i == count and arr[count] is out-of-bounds. Last iteration i == 1 (because when (i >= 0) == false you stop the loop) and you never assign to arr[0]. You can call such mistakes history w...
64,123,556
64,123,582
How do I use the parameters of the object that I am calling a function on?
//Function to find the distance between 2 points TLength CPoint::Distance(const CPoint& point) const { TLength horiz = abs(point.X() - OBJECT.X()); TLength vert = abs(point.Y() - OBJECT.Y()); TLength dist = sqrt(pow(horiz,2) + pow(vert,2)); return dist; }; int main() { const CPoint a = CPoint(4,5); const C...
this is the pointer on self object, so TLength CPoint::Distance(const CPoint& point) const { TLength horiz = abs(point.X() - this->X()); TLength vert = abs(point.Y() - this->Y()); TLength dist = sqrt(pow(horiz, 2) + pow(vert,2)); return dist; } And it is even "implicit" (unless required (dependent nam...
64,123,933
64,124,086
How to build std::map to functions overloaded for derived class
I want to build an std::map to a set of functions taking a Base object, while also being overloaded for a particular Derived class. In case the function were not overloaded, the setup would be the following: #include <functional> bool func_1( const Base& ); bool func_2( const Base& ); std::map< std::string, std::fun...
You will have to cast the function pointer to the type you need and the compiler will select the correct overload for the type you are casting to: {"a", (bool(*)(const Base&))func_1 }, This isn't so clean, and function pointer syntax can be confusing, but it is what's needed to make that code work I didn't realize tha...
64,124,428
64,163,405
Optimizing a Q3DBars graph
I am developing a Qt application that requires visualizations of very large data sets. I was hoping to use Qt's 3D graphing functionality (Q3DBars) to make the data more easily understood. However, I am having difficulty getting a reasonable framerate. I have done the below in hopes that the framerate would improv...
After playing with the other 3D graph classes, I have discovered that Q3DSurface runs smoothly with the same data set. I am unsure what the specific difference is but I suspect the surface is rendered in a vastly different way. Initially, the image looked unclear. However, after disabling the wireframe the image be...
64,124,667
64,137,417
Is MPI_Bcast supposed to work with MPI_IBcast?
As far as I know, you can freely mix blocking and non-blocking MPI operations on both ends of the communication, meaning that an MPI_Send(...) can be received by an MPI_Ircv(...). That said, I could not use an MPI_Bcast(...) with an MPI_Ibcast(...), as in the example below: #include <mpi.h> #include <stdio.h> #include ...
Simple answer to your question: No, the code is not supposed to work. Long answer: we cannot match blocking and nonblocking collective calls because, the collective operations does not have tag argument. The use of tags for collective operations can prevent certain hardware optimizations. So message matching cannot be...
64,124,725
64,130,413
Undefined reference to `main` error when embedding Python in C++
I'm trying to embed Python in C++. This is my Python file (with the name EmbedTest.py): from __future__ import division class model: def init(self,a,b): self.a = a self.b = b def test_method(a,b): m = model(a,b) m.add(1) print("a: ",a,"b: ",b) return (a+b,a-...
You are not linking the .o file, you are outputing to it. Change gcc -o EmbedTest.o -L/home/MyFolder/anaconda3/lib/python3.6/config-3.6m-x86_64-linux-gnu -L/home/MyFolder/anaconda3/lib -lpython3.6m -lpthread -ldl -lutil -lrt -lm -Xlinker -export-dynamic to gcc -o EmbedTest EmbedTest.o -L/home/MyFolder/anaconda3/lib/...
64,124,842
64,125,695
C++20 #import ""-statement: Will it be possible to use multiple preprocessed header files
In C++20 it is possible to instead of include headers with #include "header.h" use #import "header.h" // Edit: this is not standard see comments (this is for old code that cannot fully be converted to modules and use the normal import keyword without #) My question is about preprocessing. For a long time it as only b...
Yes, it is possible to import any number of header units into a translation unit. Because the rules for modules prevent any interaction between them (in particular, they cannot share macros), they can all be “precompiled” independently. That said, some implementations may copy certain components from the resulting co...
64,124,946
64,127,357
Sublime text gives error on creating a build system for c++ 14
I created a new build system in my Sublime Text 3 for C++ 14 and pasted the below code and saved it as c++ 14. { "cmd":["bash", "-c", "g++ -std=c++14 -Wall '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'"], "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_dir": "${fi...
Here is a new build system to try: { "shell_cmd": "bash -c \"g++ -std=c++14 -Wall '${file}' -o '${file_path}/${file_base_name}.exe' && '${file_path}/${file_base_name}'\"", "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_dir": "${file_path}", "selector": "source.c, source.c++", "vari...
64,125,388
64,132,285
How to build a version of Boost with _GLIBCXX_DEBUG?
When debugging my code, I like to build it with -g -D_GLIBCXX_DEBUG GCC flags (and no -O3 -DNDEBUG). Unfortunately, using these flags prevents it from linking with "normal" Boost. Is there a simple recipe for building Boost with custom GCC flags like this? (Another SO question about this doesn't seem to cover -D_GLIBCX...
You can build the boost libraries as described here: https://www.boost.org/doc/libs/1_74_0/more/getting_started/unix-variants.html You can specify the macros for the boost libraries on the b2 command line by adding: define=MACRO_NAME=MACRO_VALUE for each macro.
64,125,593
64,126,052
Is it possible to get the address of the first string in memory of a process in c++?
Is it possible to get the address of the first string in memory of a process in c++? Like i dont have to iterate through the whole memory of the process to find strings but i can start iterating from the address of the first string? I'm talking about finding the first of any type of variable not just string, though i u...
Std strings allocate their internal storage using the same heap as all other objects allocated using operator new. There is no way to distinguish the various pieces of content. That said, from a purely intellectual excercise, it is possible to declare your own implementation of basic_string with a custom allocator, whe...
64,126,190
64,126,446
Constructing const_iterator from iterator
I am implementing a simple iterator for some custom container (based on a list): template <class T, class Link> class single_iterator { public: using iterator_category = std::forward_iterator_tag; //A value is not T but T*, because the list is a contaner of elements of type T *. using value_type = T *; ...
You can simply provide an implicit conversion operator which converts the non-const version of your iterator to the const version. A short example : template<class T> class my_iter { public: // Non-const iterator can be implicitly converted to const operator my_iter<const T>() const { // Replace this wi...
64,126,197
64,126,328
Is there a possible lifetime issue with the derived class pointer here?
#include <memory> #include <iostream> #include <thread> class IA { public: virtual ~IA() = default; virtual void foo(void) = 0; }; class A : public IA { private: int x; public: A(int _x) : x(_x) {} void foo(void) { std::cout << "Hello\n"; } }; int main(void) {...
First, A::foo() should be marked as override: class A : public IA { ... public: ... void foo(void) override { ... } }; That said, in this situation, making the std::thread directly call A::foo() using a type-casted IA*-to-A* pointer would defeat the purpose of using IA at all. You may as ...
64,126,464
64,126,521
Why with dot operator value is not changed in c++?
I am from Javascript background and was experimenting with c++ where i wanted to mutate a struct member in an array in the caller function as below. #include<iostream> #include<vector> using namespace std; typedef struct Node{ int value; Node(int val){ this->value = val; } }; void changeValueByDot...
On this line: Node n = *(p + idx); the variable n is a copy of the node on the right hand side. Modifying n.value won't change the node referred to on the right hand side. If you want n to refer to the dereferenced node, then use a reference: Node & n = *(p + idx); // ^ Now changes to n will be reflected in change...
64,126,774
64,128,285
How to create a `std::integer_sequence` out of `__func__`?
I'm trying to create a function foobar() that can be used as... int main() { auto x = foobar(__func__); // decltype(x) = std::integer_sequence<char, 'm', 'a', 'i', 'n'> } Any hints? The code does not need to work on MSVC.
Here is the approach that works with GCC and Clang without need for C++20 using the statement expression language extension: template<std::size_t n> struct helper { const char(& s)[n]; constexpr helper(const char(& str)[n]) : s(str) {} template<class Fn, std::size_t... is> static constexpr...
64,127,498
64,127,971
Automatic conversion from derived class to base class' member variable's type
Long story short: I'd like to understand why the D::operator B() const conversion operator is not used in the last line in the code below, which thus fails when compiling with g++ -std=c++17 source.cpp (compiling with g++ -std=c++2a deleteme.cpp is successful, though). The error is: $ g++ -std=c++17 deleteme.cpp && ./a...
When compiler sees d == B{2}, it first creates a list of operator== overloads that it's able to find, and then performs overload resolution on them. As the link explains, the overload list contains: Member operator==s of the first operand, if any. Non-member operators==s found by unqualified lookup, if any. Built-in o...
64,127,599
64,127,649
Error during the usage of of size() function in vectors
So I've started learning vectors for the first time and wrote a simple program which goes like this: #include <iostream> #include <vector> using namespace std; int main() { vector<int> g1; int n; cout<<"enter values"<<endl; do { cin>>n; g1.push_back(n); } while (n); cou...
That is the bad side of using auto. If you have no idea what the result of auto is, you get no idea why it is something totally different you expect! std::vector::begin delivers a std::vector::iterator and you can't compare it against an size_type value which is a result of std::vector::size. This type is typically std...
64,127,820
64,128,061
Overloading a member function to receive an assigned value?
I want to create two methods of a class that access and modify some data in that instance. For example: int val = image.at(row, col); image.at(row, col) = 255; Is there a way to overload the function so it allows assignment when calling image.at(row,col)?
You don't necessarily need to write 2 methods for this. So long as at returns a value that can be assigned to (i.e. an l-value), the same function will work to both access and modify the data: struct Image { int& at(int, int); // ^^^^ }; However, you should provide an overload for the case when the object whose d...
64,128,201
64,128,346
C++ regex capture is dropping last char in email validator
C++ Shell Online Execution Link: http://cpp.sh/5z2uq I am writing a regex to validate an email ID which can have multiple dots and plus characters in its local name and can only have one dot in the domain name. The problem I'm facing now is in capture group. My domain name capture, i.e. group #2 is working as expected,...
You can use this expression: "([\\w.]+)(?:\\+[\\w]+)*\\@([\\w]+\\.[\\w]+)$" The first part ([\\w.]+) matches the Local part (i.e. any word character or dot) The second part (?:\\+[\\w]+)* denotes a non-capturing group repeated 0 or more times (matching a plus sign folowed by one or more word characters). The third par...
64,128,444
64,128,637
storing fixed known data in classes (c++)
I have this class to store fixed known data. Each object should have its own unique id in such way that, when the user calls Belt belt(1), an object with the correct values of name, perimeter, nOfPoints is created. Is there any better way to define these other parameters without a switch-case? Should I design this in a...
Is there any better way to define these other parameters without a switch-case? You could use a private static map to hold your prototypes: class Belt { private: static const std:map<int,Belt> prototypes; int _id; std::string _name; int _perimeter; int _nOfPoints; Belt(int id, const std::stri...
64,128,630
64,130,205
c++ function to reverse string doesn't work
Just learning c++. The following function is my attempt to reverse a string (doesn't work and I don't know why). Thank you for spotting my stupidity. #include <iostream> using namespace std; string r(string s) { int len = s.length(); for (int i = 0; i < len; i++) { char temp = s[i]; s[i] = ...
Firstly, string.length() returns length with '\0' which mean end of string, so you need to delete 1. Secondly, you don't travel whole string, you should stop at the middle, i/2 will just do this whatever the length is. finally : string r(string s) { int len = s.length() - 1; for (int i = 0; i < len/2; i++) ...
64,129,560
64,129,616
what is the best way to return a string in C++ where size of string already known?
When I am using str[] I get compilation error of mismatch type.When I use str+push_back instead of str[] everything works fine. class Solution { public: string bits(int n){ string str[32];//size already known thats why used str[32] for(long long int i=31;i>=0;i--) { if(n & 1<<i)...
string str[32]; is declaring an array of 32 std::string objects. But the bits() method is declared as returning a single std::string, which is why return str; does not work. You don't want an array of 32 strings. You want a single string of 32 characters in length, eg: std::string bits(int n) { std::string str(32...
64,129,758
64,190,566
OpenGL subimages using pixel coordinates
I've worked through a couple of tutorials in the breakout series on learnopengl.com, so I have a very simple 2D renderer. I want to add a subimage feature to it, though, where I can specify a vec4 for a kind of "source rectangle", so if the vec4 was (10, 10, 32, 32), it would only render a rectangle at 10, 10 with a wi...
I ended up doing this in the vertex shader. I passed in the vec4 as a uniform to the vertex shader, as well as the size of the image, and used the below calculation: // convert pixel coordinates to vertex coordinates float widthPixel = 1.0f / u_imageSize.x; float heightPixel = 1.0f / u_imageSize.y; float startX = u_so...
64,129,807
64,129,840
Bool will never be NULL [-Waddress]
I'm starting in C++ and got this warning: ../src/loop.cpp:23:6: warning: the address of ‘bool almostComparison(double, double)’ will never be NULL [-Waddress] Any can explain to me why this? If the intention is just a comparison for returning true or false? I've been researching other questions, but the answers are too...
if(almostComparison) { This tests the address of the function, which will always be non-NULL. You want to actually call the function like so: if(almostComparison(number1, number2)) {
64,131,389
64,131,607
C++ invalid conversion from 'const char*' to char*
I am new to C++. I have an exercise about constructor with const char* parameter. class Book { private: char* title; } public: Book (const char* title) { this->title = title; } When I code the constructor like that, I receive error cannot convert const char to char*. I tried using strcpy(this->tit...
You are doing an exercise, did the course you are following not explain what you are supposed to do? I would guess that this is an exercise in dynamic memory allocation and what you are expected to do is use strcpy after you have allocated some memory so that you have somewhere to copy the string to. Like this this->ti...
64,131,639
64,679,032
NVidia NSight "process creation failure"
When launching my game from NVidia NSight, I get the following error message: Preparing to launch... Launch failure: Process creation failure Launch failed. The game launches just fine, but with no way to attach to it, I can't do frame debugging or anything else. There is no other error message or information that is...
This is probably not the answer you were hoping for, but after running into the same problem, I sent a bug report to Nvidia (https://developer.nvidia.com/rdp/bugs/nsight-graphics-bug-reporting) and I was told that Arch isn't supported at the moment (see https://developer.nvidia.com/nsight-graphics-requirements). It's p...
64,131,844
64,132,023
Check for process on multiple platforms?
I'm using Qt, QProcess to launch a process, but there is presently no way to use QProcess to check existing running processes. I need a way of achieving this on multiple platforms. I have an application name that I want to look up, if its running I want to get it's PID. If it isn't running I will create an instance o...
On Posix systems, you could capture the output of ps by using popen and then parse it. The popen part looks like this: #include <iostream> #include <cstdio> int main() { FILE *f = popen ("ps -A", "r"); char s [1024]; while (fgets (s, sizeof (s), f)) std::cout << s; pclose (f); } Live demo
64,132,014
64,133,446
C++ Conditional For Loop, independent counter
I am writing some code for counting the number of vowels within a given word, I have already completed some run of mill code, however I was wondering if it was possible to do something along these lines bool isVowel(char inputcharacter) //Bool function to check the validity of a character as being a bool { set<cha...
Answer to your specific question is already given in comments. I would like to add an alternative, a maybe more sophisticated function, implemented as Lambda. So, the whole stuff can be done in one statement. Please first look at the code: #include <iostream> #include <algorithm> #include <string> int main() { std...
64,132,075
64,132,572
Problem with combining std::remove_if + str.erase()
I have a string that must be remove every characters from specified point till whitespace character. example(str = "I Have A Nice Day" specified Point: Beginning of Nice, what i want is take "Nice" (it can be every word that i don't know the range. must be till the whitespace char) ) I wrote this Code: Mystr = "I Have...
By using std::remove_if() you are removing ONLY whitespace characters, which is the opposite of what you want. Since you know the starting position, use std::find_if() instead to find the ending position, and then erase() everything in between. std::string Mystr = "I Have A Nice Day"; size_t startPos = ...; // 9 for “N...
64,132,324
64,132,468
The "no operator" operator, what is it?
What operator overload would allow me to do this? Is there a "no operator" operator? I understand that to get the value I must do some kind of call(), but I'd like to know if it's possible to clean it up. template<typename T> class Stuff{ private: T stuff{}; public: T& operator () (){ return stuff; } T& opera...
Yes there is a way: build a user-defined conversion function in Stuff: operator T() const { std::cout << "I'm here"; return 0; } Because myInt is a T type, this function will be called in the assignment myInt = stuff.
64,132,493
64,132,963
A vector/vertex but with integer values
I need something like QVector3D type but with integer values. It means, rather than: QVector3D(float xpos, float ypos, float zpos) I need: QVector3i(int first, int second, int third) Does Qt have such a type? If not, what would be the best workaround?
Thanks to @idclev463035818 suggestion, std::array<int, 3> does the job for me.
64,132,579
64,147,581
How can I see all copts (C/C++ build options) used in Bazel?
I'd like to see all copts used by my bazel build //my/target/... build command. How can I do so? I tried adding -s --verbose_explanations --explain=out.txt: bazel build -s --verbose_explanations --explain=out.txt //my/target/... ...but it just output all bazel build options into "out.txt", NOT C options passed to the ...
It turns out the answer is to use the -s option: bazel build -s //my/target/... You may also want to use --color=no to disable color output to the bazel command log file, so it doesn't have the special color escape chars in it. bazel build -s --color=no //my/target/... The reason I didn't see any useful output, howev...
64,132,715
64,157,683
Why doesn't partial specialization need forward declaration?
Today I write the code below with a mistake: template<int V> typename std::enable_if<(V > 0)>::type Test() { Test<V - 1>(); } template<int V> typename std::enable_if<(V == 0)>::type Test() { std::cout << "0" << std::endl; } int main() { Test<1>(); } The compiler errored my that no matching function for call to...
While the comments have addressed the problem—that each independent function template must be declared before use—the question about the difference can be answered simply by quoting [temp.class.spec.general]/7: Partial specialization declarations themselves are not found by name lookup. Rather, when the primary templa...
64,132,871
64,203,758
How to set AppendCheckItem to "check" by default in wxwidgets?
I have a drop down menu "menu" for which I want to add a check item which should be checked by default. How can I do the same in wxwidgets in C++? check_option = menu->AppendCheckItem(CHECK_ID, wxT("Check"));
From the discussion, In wxwidgets we don't have a one liner way to do the same. There is no other arguments that AppendCheckItem accepts. Hence we need to call the check function to do the same. check_option->Check(true);
64,133,506
64,133,659
virtual functions segmentation fault
I want to learn virtual functions. I have made print() in class Base virtual and my program crashes. Why do I have to create the two objects with new? #include <iostream> class Base { public: virtual void print(); }; void Base::print() { std::cout << "Base print method" << std::endl; } class Derived ...
Why do I have to create the two objects with new? You don't have to. It is a common misunderstanding that you need to dynamically create objects for polymorphism. Often polymorphism is used with dynamically created objects, but it is not strictly necessary to enable polymorphism. You need references or pointers for p...