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,795,375
64,795,451
Extracting templates from templated class
I'm trying to extract the type pack off an instance of a template class: template <template <class T, class... Ts> class> using first_in_template_class = T; I tried this and other similar variants, but I get this error: unknown type name 'T' How to go about this? P.S. I know I can use std::tuple_element in the std::...
You can use: template <typename T> struct extract_first {}; template <template <typename...> typename ClassTemplate, typename... ClassTemplateParams> struct extract_first<ClassTemplate<ClassTemplateParams...> > { using type = typename std::tuple_element<0, std::tuple<ClassTemplateParams...> >::type; };
64,795,633
64,798,568
Visual studio C++ 20 module import .h&.cpp lib
lib1 has two files math.h inline void hello(); and math.cpp #include <iostream> #include "math.h" void hello() { std::cout << "hello from math"; } lib2 is a c++ 2a module lib: export module Bar; import "math.h"; import std.core; export namespace bar { void BarFunc() { hello(); } } visual stud...
math.h inline void hello(); to void hello(); works.
64,795,636
64,795,668
Is there a way to iterate through a heap in its heap order without popping?
If I make a heap and iterate through it, it doesn't show it in the right order: vector<int> q; q.push_back(3); q.push_back(7); q.push_back(5); make_heap(q.begin(), q.end()); for (auto it = q.begin(); it != q.end(); ++it) { cout << *it << " "; } Outputs: 7 3 5 When I want 7 5 3 I know I can simply pop off the ma...
No, a heap is not fully sorted. Popping is the operation that sorts the heap, if you will.
64,795,749
64,795,806
can compiler deciding not to inline a function lead to multiple definitions?
I know that the compiler can decide whether to inline a function or not. Lets say someone defined a function as inline in a header file and the function body is also in the header file. Also, say the function is long and the compiler decides NOT to actually inline this function. f1.h: inline void f1() { /* really l...
In short: Any "optimization decisions" made by the compiler during compilation will never lead to a compile error. So the answer is NO.
64,795,963
64,797,226
How do I sort a 2d string array by a specific column's values in C++?
I have the following 2d array that I get/create from an external .txt file. string accountsArr[5][7] = { "bham@gnet.com", "Blake", "Ham", "squid62", "1987", "U", "Teacher", "jdark@att.net", "Jim", "Dark", "gymrat32", "1985", "A", "Master", "hgreen@lakes.net", "Hannah", "Green", "flower22", "2007", "U", "Apprentic...
So I finally figured this out by doing a "bubble sort". Here's how I implemented it. Hopefully this can help someone else who's having trouble finding any examples of sorting with 2d arrays by a specific column: int rows = 5; int col = 7; string accountsArr[rows][col] = { "bham@gnet.com", "Blake", "Ham", "squid62", "...
64,796,012
64,796,086
How do I properly overload a operator= when creating a copy constructor
I was having a lecture at my University for C++, and I couldn't really understand what the operator= is supposed to do and how to overload it properly. In almost all examples from lectures that i could find, the part of the code for the copy and move constructor would look like this: class MyClass { MyClass(const MyCla...
This has nothing to do, whatsoever, with copy constructors. This is checking for an edge case when an object gets assigned to itself: MyClass c; // Some code c=c; c=c is perfectly valid C++. You can assign an object to itself. Presumably, you expect this to do nothing. This object doesn't change. The comparison to t...
64,796,111
64,796,386
Slow std::vector vs [] in C++ - Why?
I am a bit rusty with C++ - having used it 20 years ago. I am trying to understand why std::vector is so much slower than native arrays in the following code. Can anyone explain it to me? I would much prefer using the standard libraries but not at the cost of this performance penalty: Vector: const int grid_e_rows =...
You are not compiling with optimizations. Compare: With vector of vector With array To give you a small taste of what the optimizer might be doing for you, consider the following modification to your H() function for the vector of vector case. int H(std::vector<std::vector<int>> &arg) { int h = 0; auto sig...
64,797,216
64,797,326
Calling non-const member function from const object without using this, why is it an error?
Running the code below in g++ will result the following error: error: passing 'const A' as 'this' argument discards qualifiers [-fpermissive] struct A{ void f(){}; }; int main(){ const A a; a.f(); return 0; } Where do we use this? fpermissive implies that the code is non-conformant. Where does the s...
The standard covers this in [class.this]. In particular, see example 2, where it says (in part): The call y.g() is ill-formed because y is const and s​::​g() is a non-const member function. When applied to your code, the equivalent statement is: The call a.f() is ill-formed because a is const and A​::f() is a non-co...
64,797,639
64,798,290
Why I can't escape in this while loop in Release mode?
There is a function that changes the value "bIsTrue" to true after 2sec. When bIsTrue is "true", the main thread can escape while loop and print out "Now bIsTrue is True!" in main() #include <iostream> #include <process.h> #include <Windows.h> using namespace std; bool bIsTrue; // global variable unsigned __stdcall ...
What may be happening is that your flag variable is being optimized out by the compiler because it think it can't change. Here is a case you could use volatile, and also std::atomic: volatile std::atomic<bool> bIsTrue = false; Also, I would check your use of WinAPI functions. I would suggest instead using the standard...
64,797,654
64,797,728
error: no matching function for call when compiled
I am trying to write a simple C++ function using iterator for a vector as follows: #include <iostream> #include<vector> #include<sstream> using namespace std; using vit = vector<string>::iterator; void print(const vector<string>& s) { for(vit it = s.begin(); it != s.end(); ++it ){ cout << *it << endl; } } ...
print() only accepts an std::vector<string>. You're passing an std::vector<int> which is not the same thing. If you want to be able to pass any std::vector you want, you'll need to create a template: template <class type> void print(const vector<type>& s) { for(auto it = s.begin(); it != s.end(); ++it ){ // vit is on...
64,797,767
64,830,877
pow is not working properly inside a __device__ function in CUDA
I am trying to use function pow inside a __device__ function in CUDA using Visual Studio 2019. __device__ double Len(double a, double b) { return pow(a, 2) + pow(b, 2); } However, it keeps giving me this error when I try to build the solution. Error Undefined reference to '_Z3powdi' in 'x64/Debug/kernel.cu.ob...
CUDA has supported pow (double, int) in device code since proper double-precision support was added around 2008. This was a required function since at least the C++98 standard (ISO/IEC 14882 section 26.5). Here is a complete example program incorporating OP's function, with error checking omitted for brevity: #include ...
64,798,137
64,798,246
Why the rvalue reference parameter cannot be passed between functions directly?
My code is as follows: #include <iostream> using namespace std; class A{ public: void sendByRvalue(string&& str){ cout << str << endl; } }; class B{ private: A a; void send(string&& str){ a.sendByRvalue(str); } public: void run(const string& str){ send("run " + str + "\...
str is a named rvalue reference, which is treated in the language as an lvalue. rvalues are only xvalues or prvalues, and str is neither. A note from the standard, on the xvalue rules: In general, the effect of this rule is that named rvalue references are treated as lvalues and unnamed rvalue references to objects ar...
64,798,199
64,798,296
Unexpected output from to_string(int)
I am trying to count the length of an int that may or may not have leading 0s. For instance 0100. I tried using the to_string() method and it turned 0100 into the string "64" for some reason & I don't understand why. I am relatively new to C++ and I think I may have fundamentally misunderstood how to_string() works. I ...
By starting your integer literal with 0, you actually declared the number in octal base. (100 in octal = 64 in decimal) See cppreference's page on integer literals for more details.
64,798,929
64,799,234
Getting Unexpected value
I was playing around with array and when i did this , im expecting IndexOutOfBound however , the program still ran and gave an output 54 Where does the extra number come from ? How to avoid these kind of indexing problem? #include <iostream> int main(){ int array[] = {1,2,3,4,5,6}; int total; for(int i = 0...
C++ does not do any checking to make sure that your indices are valid for the length of your array. Like churill notes above, indexing out of range is undefined behavior. For example, in your question, the value of array[6] is whatever is stored your memory at the location where the 6th element would have existed. In y...
64,799,155
64,799,877
How to implement class object types that derive from parent class using UML class diagram
I m learning C++ by creating simple traffic light logic using classes. In which I found this UML diagram and I want to create object types based on this. However, I created the TrafficLight class object struggling to understand control class logic part. EDIT To me, I just want to create traffic light for N, W, S and E...
Base on the diagram you have, your Control would have 4 instance of TrafficLight. While it doesn't say how exactly the would work, I would assume the intend is to call switchLight and createLight from switchControl and createLights, and you should not need to use switchLight and createLight directly. Some code would be...
64,799,446
64,799,505
How do I know the exact exception type?
We use CDynamicAccessor which inherits from CAccessorBase. The function MoveNext would throw HRESULT MoveNext() throw() but without telling what exception type it is. How do I know it?
No, throw() means the function is declared not to throw any exceptions. Note that it's deprecated (and removed in C++20); we can use noexcept (or noexcept(true)) since C++11.
64,799,741
64,800,414
Using std::condition_variable to wait in the message sending thread, a deadlock occurred
I am writing a network module, the sending of data is carried out in a separate thread, using a concurrent queue to synchronize data in the main thread. private: std::mutex mutex_; std::condition_variable blockNotification_; moodycamel::ConcurrentQueue<Envelope> sendQueue_; std::promise<bool> senderThre...
The Send() method isn't thread-safe. I would use a std:lock_guard in a new scope to lock the mutex and ensure it is unlocked before the notify_all call like this: Envelope AsyncTransport::Send(const Envelope& envelope) const { { const std::lock_guard<std::mutex> lock(mutex_); if (drain_) { ...
64,799,989
64,800,153
Finding majority element in an array ( getting wrong output for particular cases with long integer input)
I was solving a Majority_element problem, where I would be provided an int 'n' followed by an array whose size is n, as input. If any element's frequency in the array is more than n/2, then return 1, otherwise, return 0. Now, my program works correctly for small values of integer elements, but it's giving a false outpu...
As you do, you don't need std::sort. you need to reset count. check should be done in outer loop bool get_majority_element(const vector<int> &a) { for (size_t i{}; i < a.size() ; ++i) { int count{}; for (size_t j = i+1 ; j<a.size() ; ++j) { if (a.at(i) == a.at(j)){ count += 1; } } ...
64,800,071
64,800,186
Can you create std::map with only keys?
So, I want to use std::map to find if an element exists. So I basically only need the key, not any value. Is there any way to do something like std::map<std::string, void> for example? Or is there a better alternative to std::map for this kind of stuff? Worst case scenario a different container like std::vector<std::st...
Or is there a better alternative to std::map for this kind of stuff? Yes. The container that you describe is a set. There are std::set and std::unordered_set corresponding to their map counterparts in the standard library.
64,800,145
64,800,303
How to use a timer in C++ to get a user input within a given time?
I need the user input to press a key within a time range. If he doesn't press any key, the seconds variable is incremented. Below you can find the flowchart and my code. int DisplayMenu() //This function displays the user menu. { int userChoice{}; cout << "\t\t***************************" << end...
You can count how many seconds it took for the user to input a character: int DisplayMenu() //This function displays the user menu. { int userChoice{}; cout << "\t\t***************************" << endl; cout << "\t\t* 1-Add One Hour *" << endl; cout << "\t\t* 2-Add One Minute *" << endl;...
64,800,254
64,800,468
warning: zero as null pointer constant while comparing iterators
For a code segment as below: (or check https://godbolt.org/z/15bqMj) std::vector<int> v{1,2,1,2,1,2}; for (auto it = v.cbegin(); (it = find_if(it, v.cend(), somePredicate)) < v.cend(); ++it) { std::cout << *it << std::endl; } I got warnings from the compiler (clang 11 with -std=c++20 -Wzero-as-null-pointer-constan...
Usually iterators are compared only using == and !=. As far as I know other comparison operators are not defined for iterators. It looks like clang tries to use <=> operator for your < and because of it internal implementation gives your this warning. Edit: Random Access iterators should define all comparison operators...
64,800,553
64,800,882
How can an instance add itself to a vector?
I need to instantiate a class SpriteWithTimer and that the new object adds itself to a vector vsprites. Here's a code snippet: #include <vector> ... class SpriteWithTimer { public: SpriteWithTimer(); ~SpriteWithTimer(); ... }; static std::vector<SpriteWithTimer> vsprites; int main() { ... } ... SpriteWi...
The object stored inside a vector is always a brand new separately-constructed object. Therefore, you can't store to a vector an object created elsewhere. Either, you can store: a copy of that object: push_back(*this), an object with the content moved from that object: push_back(std::move(*this)), a pointer to that ob...
64,801,046
64,801,163
memcpy with initialized variable and negative numbers with cast
I have QByteArray bytes // Fullfilled earlier char id_c = bytes[7]; int _id; _id = 0; // If I comment this result would be different memcpy(&_id, &id_c, 1); int result = _id; I have _id variable and if I comment "_id=0" result variable result would be different with negative number. W...
Correct. Because this statement: memcpy(&_id, &id_c, 1); Is only copying a single byte from &id_c into an address representing a 4-byte integer, &_id. Only the first byte of memory occupied by _id gets anything copied into it. Without the zero init of _id first, the remaining three bytes of that value are left unde...
64,801,190
64,801,562
Swapping all smallest and largest number in an array/vector
I was trying to make a program that swaps all the biggest and smallest numbers in an array or a vector. I came up with a program but for some reason I'm not able to debug it to get the problem. Its not printing the vector, neither do I know what the issue is. Can anyone please help me. Desired Input and Output #include...
A simpler method would be to make a vector of indexes rather than sorting the vector and trying to find the values in the original vector. For example: #include <iostream> #include <algorithm> #include <vector> int main() { int n; std::cin >> n; std::vector<int> arr; std::vector<int> indexes; for (...
64,801,243
64,801,474
What does "class classname* funcname(void) "mean in C++?
I found the following code in a header file and the "BOOT" class is defined in another header file. class BOOT* boot(void); It looks like a declaration of a function, but it begins with class.
This is an elaborated type specifier: Elaborated type specifiers may be used to refer to a previously-declared class name (class, struct, or union) or to a previously-declared enum name even if the name was hidden by a non-type declaration. They may also be used to declare new class names. https://en.cppreference.com...
64,801,332
64,801,999
Imwrite format output filename
I have this piece of code down below: ImageFile is the file that i saved. And i want to save image with specific name char x[] = "Grey"; imwrite( format("ImageFile-%s.png", x), gray_image); Exampele ImageFile=test.png and output should be test-Grey.png So the output file name i want to be the initial name of file + st...
You can do it using sstream. #include <sstream> #include <string> // other includes int main() { //other codes std::string x{"Grey"}; std::stringstream ss; ss << "ImageFile-" << x << ".png"; imwrite(ss.str(), gray_image); }
64,801,353
64,801,401
How to check if a partition is empty in c++
I am using the std::partition to split a vector in two sub vectors. I want to know if the first partition is empty #include <algorithm> #include <vector> #include <iostream> using namespace std; int main() { vector<uint32_t> v {0,1,2,3,4,0,0,0}; auto bound = std::stable_partition(v.begin(), v.end(), [](auto ele...
bound == v.begin() when first partition is empty. bound == v.end() when second partition is empty.
64,801,409
64,801,721
In C++, can I make cout display doubles as doubles but without touching main()?
quite a specific question but I'm working on an assignment in which I have to use some operator overloads to manipulate some coordinates. The coordinates are doubles but C++ just outputs them as (1,4) when they're (1.0,4.0) as they're integers. I've seen that I can use std::cout.precision to force cout to work to 1dp b...
You might add your manipulator in your operator: ostream& operator<<(ostream& OutStream, const Coord& Coordinate) { OutStream << std::fixed << std::setprecision(1) << "(" << Coordinate.X << "," << Coordinate.Y << ")"; return OutStream; }
64,801,667
67,752,322
Box2d cannot cast to void*
https://www.iforce2d.net/b2dtut/collision-callbacks I am referencing this site to implement a crash listener. But while implementing BeginContact I get the following error: The result of getUserDate() cannot be cast to void* type. void BeginContact(b2Contact* contact) { void* data = contact->GetFixtureA()->GetBody(...
This error is because latest Box2D release by Erin Cato changed the return type from previous releases from returning a void* to returning b2BodyUserData&. The definition of the latter being: struct B2_API b2BodyUserData { b2BodyUserData() { pointer = 0; } /// For legacy compatibility uintp...
64,801,811
64,807,432
How to handle WM_ENDSESSION in a console app
I wrote a program to register mouse events, and I want it to terminate when the computer is shutdown (and then perform a flush and a final print). I tried with a CtrlHandler, but it works only with Ctrl-C and not when the system is shutdown, because I am using a Win32 library, according to MSDN: If a console applicati...
You can just create a hidden GUI window in console application and handle WM_ENDSESSION in the window procedure as shown below #include <Windows.h> HWND g_hidden_window = nullptr; LRESULT CALLBACK wnd_proc(HWND, UINT, WPARAM, LPARAM); // Main entry point of your app int main() { HMODULE current_instance = ::Get...
64,802,373
64,802,503
Lambda in for loop - static variable
Dear stackoverflow community! Recently, I was hunting for a bug at work, which led me to the following piece of code I wrote myself. Here is a simplified version: int main() { for(int i = 0; i < 5; ++i) { int j = i + 1; auto k = [j](){ static int s{j}; cout << s << endl;...
Think of a lambda expression as a terse recipe to define a class that overloads the call operator(). In your case: struct LambdaEquivalent { int j; auto operator() const { static int s{j}; cout << s << endl; } }; And you loop then is for(int i = 0; i < 5; ++i) { int j = i + 1; ...
64,802,814
64,803,265
sorting array of pointers in c++ using lambdas
I am trying to write sorting template function to make it work with custom classes. My code is: #include <iostream> #include <vector> struct test { int value; test(int a) : value(a){}; void print() { printf("the value is : %d", value); }; }; template <class T> void bubblesort(T *m_data, size_t size, bool ...
Your function has the wrong type; T is test*, so you need test* const& - "reference to const pointer to test" - as the error message says. (const test*& is "reference to pointer to const test.)
64,803,178
64,807,481
How can I build glibcxx 3.4.21 from source?
When building v8, I encounter the following error ./bytecode_builtins_list_generator: /lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./bytecode_builtins_list_generator) After doing some search, I learn that I have old glibc GLIBC_2.2.5 GLIBC_2.2.6 GLIBC_2.3 GLIBC_2.3.2 GLIBC_2.3.3 GLIBC_2.3.4 G...
After doing some search, I learn that I have old glibc No, you don't. Your problem has nothing to do with GLIBC, and everything to do with libstdc++.so (which is too old). See this answer for more detailed explanation. You need to install a newer version of libstdc++.so.6. The good news is that (unlike upgrading GLIB...
64,803,315
64,803,403
Creating a pointer, pass a pointer, pass an address of a pointer
What is a difference between these two codes? Can anybody explain in to me like: #1 do, #2 do, #3 do, please? I have some ideas what these codes do, but I am not sure about it. void test(char *msg) { /*3*/ msg = new char[5]; } int main() { /*1*/ char *msg; /*2*/ test(msg); } // I think // #2 Pass the pointer...
I suppose you are confused by too many pointers. Pointers are scary for a reason, but in many regards they are like any other variable. Modifying a pointer passed by value to a function has no effect on the pointer that was passed to the function. Reducing the scariness of your example a bit we get: void test(std::stri...
64,803,552
64,803,845
How do I write a function with variable number of arguments using pointers?
So I have a task to write a function "mult" with variable number of arguments using pointers. And this function must calculate the product of float numbers. I've followed the guide that our uni gave us but my product is still equal to zero. I found out that the problem is that every other number to be multiplied is zer...
You could write mult as a variadic function, and use std::accumulate with std::multiplies as the operator. #include <functional> #include <initializer_list> #include <iostream> #include <numeric> template<typename T, typename... Args> T mult(T t, Args... args) { std::initializer_list<T> values{args...}; return...
64,803,635
64,821,012
Dump apache thrift messages for debugging purposes?
Apache Thrift is one of the more popular choices for an opensource RPC frameworks (gRPC is also one that gets lot of tracktion since release into the open). In my setup in c++ Im using a TMultiplexedProcessor. I guess this could be any TProcessor for that matter since Im just interested in printing whatever is sent. Th...
There's TProtocolTap and TDebugProtocol. Usage example can be found in thrift_dump.cpp: shared_ptr<TProtocol> iprot(new TBinaryProtocol(itrans)); shared_ptr<TProtocol> oprot( new TDebugProtocol( shared_ptr<TTransport>(new TBufferedTransport( shared_ptr<TTransport>(new TFDTransport(STDOUT_FIL...
64,804,567
64,805,789
Cmake settings to add external c++ classes to a project
probably a bit of a noob question so bear with me. What do I want to do? I have a c++ class called main.cpp and with that I want to add the external classes of RtMidi. I can just move the RtMidi classes into the same folder as my main.cpp and include them from there, but it feels a lot cleaner if I can keep them in a s...
I can tell that you are new to cmake which is fine. Everyone has to start somewhere. Basically you aren't getting the proper include directories that your 'Music' needs. And honestly that's not your fault you linked against the 'RtMidi' if they wrote their cmake correctly your project should have compiled. Here is roug...
64,804,646
64,809,458
Regex unicode chars in C++
I have the following part of a configuration file (for example, .ini file) that is corrupted and I am developing a C ++ application that detects file corruption, using regex, detecting invalid characters in my configuration file: When I read this file, by using the istream, and storing into a string (sample) I am havi...
You're using the Perl /.../g syntax in your regular expression. C++ doesn't support that. Instead, only include the pattern between the slashes. Then, to search globally use std::regex_search: std::regex myexpr (R"([^\u0020-\u007E]|(\b.*(Mensagem|Antes|Loop|Movimentar|\|).*)|\\[0-9]{3,4})"); std::string sample = R"(\02...
64,805,037
64,805,178
Find the lone number
I’m trying to search through an array and print out the only number within it which doesn’t have a pair, so in this case '4'. The result keeps coming up as 2 so even though I feel I have the logic correct, I am definitely overlooking something. I've been trying to solve this for a while and keep getting stuck Many than...
You have counter, so you should use that to determine the index to inspect instead of the new variable i. Also to move the search position to +2 position, you should add 2 to the loop variable instead of modifying the array. #include <iostream> int main(void){ int arr[] = {1, 1, 2, 2, 3, 3, 4}; int n = sizeof(...
64,805,194
64,809,852
How to find sentences from txt file in. c++?
My problem is to read txt file and print 1 sentence per line but I am not sure how I can do this, I have the following code for finding of the sentence ending tho: #include <iostream> #include <string> #include <fstream> using namespace std; int main() { ifstream infile("test.txt",ios::in); string current; ...
You could store the sentence start and then once you have the sentence end create a substring. This substring will be between in the range [sentence_start, i]. int sentence_start = 0; for (int i = 0; i < current.size(); i++) { // if sentence end if (current[i] == '.' || current[i] == '?' || current[i] == '!') {...
64,805,225
64,973,473
SWIG wrapper adding new_ prefix to the class name and unable to get class method
I have written wrapper for simple C++ void function that takes 2 string parameters. For some reasons when I try to create an object of my class, I'm getting the name error that "name 'my class name' is not defined". When I tried create object and specify new_ prefix before class name the object was created, but I'm sti...
Used pybin11 instead of SWIG. For my task that was much easier solution than with swig.
64,805,246
64,810,158
Create a folder with the creation time as prefix (C++)
For each execution of the program I need to create a new folder that contain the date and time of the creation of the folder as prefix. for example if I execute the program at Date1Time1 the folder name will be Date1Time1_Folder, after a few minute Date1Time2 the name will be Date1Time1_Folder is there a way to do this...
First you need to get the date and time: std::time_t t = std::time(nullptr); std::tm tm = *std::localtime(&t); Then you need to format it to a style you want, I went for displaying day of the month and minute of the hour. See here for how to format it. // format date and time std::ostringstream date_and_time_ss; date_...
64,805,423
64,807,555
Exception thrown at exact same location on each build in C++ when trying to write .mat file
I am trying to write .mat files using C++. I am using Microsoft Visual Studio 2019 along with Qt to develop my application. MainWindow.h #include <QtWidgets/QMainWindow> #include "ui_mainwindow.h" #include "mat.h" class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = Q_NULLPTR); ...
After a lot of searching, I found the answer to the following question to "kind of" answer my problem. It basically says that any first chance exceptions (i.e. which do not cause application crash) are to be expected when working with Matlab libraries in C++. If anyone has a better explanation or a way to fix this prob...
64,805,558
64,806,815
Is there a way to use clang-format to do "indentation only"?
I have a large code base with indentation that is very inconsistent. I finally got some buy in from developers for running a code formatter. I would like to start with just fixing the indentation because indentation is a lighter touch than running clang-format with a style. I like correcting indentation only because ...
I don't have a Shell script for you that can do this on all source files, however, I use VSCode that allows me to specify the clang format fallback style in the settings.json so that every time I save my files, it applys the same formatting to each one consistently. Here is an example of my settings.json C_Cpp.clang_fo...
64,805,633
64,806,745
Trying to compile c code with cpp .so lib, with extern "C" { ... } segment
I need to compile c code with -lfoo cpp lib. foo.cpp looks like: #include "foo.hpp" extern "C" { /* some come for my class, that describes in foo.hpp*/ } foo.hpp : class Bar{ public: /* public fields */ /* public methods */ } So can i do that?
Since you want to use your lib from C code, the lib cannot export classes. You can only have function. you can hide classes behind opaque pointers passed out. In the library, use C++ as you wish, as long as all interface functions are plain-C and do not use classes or pointers-to-classes. For example, this header has a...
64,805,865
64,807,074
Binary tree preorder
My preorder method don't work from main, but array elem has been formed rightly (I checked it with printing every step). All functions/methods used in definition work correctly. I think the problem occurs because of line "return elem;". Can anyone suggest any idea, it's too important. T* TreeNode<T>::preorder()const {...
It's a bit difficult to see exactly what you're trying to do as it wasn't specified, but it seems that you're trying to grab all the data from your binary tree. This GFG article does a really simple explanation and breakdown of how to transverse a binary tree. Obviously your nodes are more complicated, but the general ...
64,806,705
64,806,996
Where does a Mat object store its data if it's not in data variable?
I need to transfer the image data from a Mat object (OpenCV) to a const unsigned char* within a ZXing::ImageView object; typically, I just use (assuming the object is named "object") object.data at my own risk and go from there if there are issues with the transfer. However, in this case, the data member variable is em...
Try to pass the reference to your Mat object to the functions, or if you want to copy the data for creating a new image, use explicitly the clone() method to get deep copy of your image. Like either: Mat applyThreshold(Mat& gradient) { Mat dest, gray; cvtColor(gradient, gray, COLOR_BGR2GRAY); threshold(gray...
64,806,926
64,812,855
Unable to write to serial device but able to read from it
I am using non-blocking IO where I simply try to write and read to a serial port. Reading of the serial port works as expected whereas writing doesn't. This is how I've set up the serial line. As you can see, it is setup to non-blocking and canonical. Maybe some of the flags are redundant, but they are mostly taken fro...
I am using select to wait for the IO resource to become available ... But even waiting 20 seconds, the device is still unavailable. Your program is not behaving as you expect because you have not properly programmed the select() call: int retval = select(1, NULL, &rfds, NULL, &tv); Per the man page the first argumen...
64,807,181
64,807,856
Why should someone create a default move constructor but delete the move assignment operator?
Today i came across a class with following layout (c++14) class A { //ctor A(..some specific parameter) :..init some members .. {}; //copy ctor A(A const&) = delete; //copy assign op A& operator=(A const&) = delete; //move operator A(A&&) = default; //move assign op A& operator=(A&&) = delete; //dtor ~A() = default;...
What this means is that, once an object is created, some aspect of its value cannot later be changed. You can move from it of course, but once that's done, you can't move back to it. Consider a unique_ptr that had this design. Such a pointer would allow you to transfer ownership, but only to a newly constructed unique_...
64,807,313
64,807,814
How do I invalidate canvas of an object owned by another thread?
I want to load data in a separate thread and than to call redraw method to invalidate canvas and draw the data. However, when I call redraw method, it triggers breakpoint with following message: ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by different thread..." I'm looking for...
The general idea is to send a signal from worker thread back to the main thread which then triggers the redraw. Something like this (I haven't tested it): class Worker : public QObject { Q_OBJECT public: ... void loadData() { ... // Do stuff emit dataLoaded(); } } class MainWindow...
64,807,464
64,808,325
Make ninja start from where it crashed
I was compiling CEF using ninja and it took 8 hours. There were 5 files left until it was done. The 5-th file was "libcef.dll" which I need for my project and I suspect that in one of the remaining 4 files there was "natives_blob.bin" which didn't generate and I need it. It crashed on the "libcef.dll" due to RAM being ...
Re-running the ninja command is enough.
64,807,522
64,862,665
Qt5 newline characters in translation text?
I'm working on correcting some missing translations from an application, and one particular translation isn't pulling the translated text from my TS file, and the culprit seems to be the newline character ("\n") in the source text, because when I remove that character from the source text and test the translation witho...
My solution was to write a helper method to split strings that have newlines into separated strings and also separate it into several entries in the TS file. Then it translated each line individually and stitches them back together with newlines. I mean, it would be nice if the translation file supported newlines, but ...
64,807,538
64,807,701
c++ - how to properly overload operator to do implicit type cast from __generic_buffer<void*> to __generic_buffer<const void*>?
To put it simple, i have the following code: template<typename p> requires(std::is_pointer<p>::value) struct __generic_buffer { p baseptr; size_t size; // member functions go here }; using buffer = __generic_buffer<void*>; using const_buffer = __generic_buffer<const void*>; and i want to be able to writ...
First things first. Types with __ in them are reserved by the C++ standard for your compiler and the standard library. Use of them in programs makes your program ill-formed, no diagnostic required. (also, _T starting with an _ and then a capital letter). This kind of bad habit comes from copying the coding style of ...
64,807,731
64,811,346
trying to create private member array, with size given from initializer list in C++(<vector> usage is forbidden)
So i'm trying to create a private member array on my School class where i'm going to be holding the address of some student objects. My goal is to simulate the stusents entering the school building if the capacity of the building allows as such (think of the problem with small numbers) I have managed to implement the ...
I finally managed to find the answer.The classes should look something like this. School class: class School { private: int class_capacity; Student** pointer_array; public: School(const int capacity)//constructor :class_capacity(capacity) { pointer_array = new Student*[cap...
64,807,808
64,808,160
Template generating a hundred C callback functions, without slow compilation
I need to pass order of a hundred callback functions to a C library. All my callbacks will be very similar, except that they need to know which "key" it was registered for. The C API doesn't allow an context to be passed back. In other words this is the API: void register_for_event(int event_type, void(*callback)()); ...
Here is a C++17 answer: template <std::size_t... I> void register_via_pack(std::index_sequence<I...>) { ( (register_for_event(I, event_handler<I>)),... ); } register_via_pack(std::make_index_sequence<100>{}); It expands a template parameter pack using a C++17 fold expression. Not sure if it compiles faster in you...
64,808,047
64,808,242
Compiled Elf binary is too big
long *video_memory = (long *)0xB8000; int main() { // long *video_memory = (long *)0xB8000; *video_memory = 0x5050505050505050; return 0; } Why this C code above creates a 2Mb binary file when I link it? If I comment the global var and uncomment the local one it works (the file has then has just a few byt...
The problem is that the linker has the ridiculous max-page-size of 2MB from a mistake in the x86_64 ABI, which ends up inducing 2MB alignment requirements in various places. Normally it will put text and data segments in the same part of the file, with the intent that it be mapped twice, but that's only possible with a...
64,808,158
64,808,251
Using std::enable::if and std::is_base_of to constraint inherintance
Given the following scenario: class A {}; class B : public A {}; class C : public A {}; class D : public A {}; template<typename T/*std::enable_if and std::is_base_of here*/> class X {}; When I declare an X Then I want to constraint the typename T to obligatorily be a sub-class of A, otherwise I'll get a compiling er...
A correct syntax for using enable_if is template<typename T, std::enable_if_t<std::is_base_of_v<A, T>, bool> = true> class X {}; and now if A is a base of T then std::is_base_of_v<A, T> is true and std::enable_if_t becomes bool and we give it the value of true. If A is not a base of T then the condition is false and...
64,808,173
64,808,973
c++ rapidjson get add value to exist array
I tried to create a class which will add a value to a Json array. I tried to do it like this: void functions::Json::SetArray(rapidjson::Document &JsonObj, std::string ArrayName, std::string value) { if (!JsonObj.IsObject()) JsonObj.SetObject(); rapidjson::Document::AllocatorType& alloc = Json...
Taking a look at rapidjson/document.h:1218, this appears to be how it errors when you use the [] operator with a member that doesn't exist, probably where you access JsonObj["array"]. If I use MemberFind to look up the member first, it works fine for me: rapidjson::Document::MemberIterator existingArray = JsonObj.FindM...
64,808,379
64,808,591
How to use swap() in C++ when the parameters must be 2D arrays using pointers
First of all, I want to make sure that I do access array members properly when using pointers. Is this equivalent? for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> a[i][j]; } } with for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) ...
You can use std::swap_ranges. If your pointers are decayed 2D arrays: void swap(int* a[N], int* b[N], int) { if (a != b) std::swap_ranges(&a[0][0], &a[N][N], &b[0][0]); } If your pointers are decayed arrays of pointers to arrays: void swap(int** a, int** b, int n) { if (a != b) std::swap_ranges(&a[0], &a[n...
64,808,541
64,808,589
How does the copy constructor work in this code?
I have been reading Bruce Eckel's "Thinking in C++" and I came across the copy constructor. While I understand mostly the need for a copy-constructor, I am a bit confused about the following code below: #include <iostream> using namespace std; class foo { static int objCount; public: foo() { objC...
y is an object of class foo, so why doesn't the compiler call the constructor and then copy the contents of x into y? It does. It calls the copy constructor, to do exactly that. Where does the default copy-constructor provided by the compiler fit in this picture? You didn't provide your own copy constructor which p...
64,808,561
64,808,806
c++ global variables with same name for different classes
Say I have different classes Knight, Spearman, Horseman, ... with exactly same properties: m_health, m_damage, ... (they vary in some methods, so classes are not exactly the same). They have to be initialized in constructor by global default values that are the same for a specific class, but vary across different class...
Just stick the values in the usual classes: class Knight { public: static const int HEALTH = 100; static const int DAMAGE = 25; Knight() : health(HEALTH), damage(DAMAGE) {} // ... }; Alternatively stick 'em in a global configuration querier. That way you can read the values from a ...
64,808,975
64,809,211
Creating a new array containing all the elements of the original array that are located before the first negative element
This is what I want: Based on the original array, create a new array containing all the elements of the original array that are located before the first negative element. Here is my code: #include <iostream> #include <ctime> #include <cmath> #include <iomanip> #include <vector> using namespace std; int main() { con...
Here you are using f as a flag which is initially false. This means you didn't get any negative yet. When The f will be true then you can say that you got at least one negative number and as f is true you will not push any elements further. So, You should push in the vector until you get at least 1 negative number. Whi...
64,809,586
64,827,067
I want to have a user select a number that they want to keep and put in an array. And have them put into separate index's
I so far have that the user is asked what dice they want held and I put those into an array. But when I put it in the array I want those numbers to stay. But for the next turn I want to be able to add to the array with other numbers without it changing the others. cin >> Hold; switch (Hold) { ...
The problem you are facing is mainly within the for loop and the switch statement. Each time you run it you overwrite the element that was on that same index. There are a a number of ways you could do this, but I would suggest using a vector instead because it will allocate memory for you. With a regular c-style array ...
64,809,594
64,809,662
Unexpected behaviour of vector.reserve() in c++14?
I wrote a code to sort a vector of Integer and noticed that one version is working fine and another one isn't. Version 1: Using vector.reserve #include <bits/stdc++.h> using namespace std; int main(void) { ios_base::sync_with_stdio(false); vector<int> a; a.reserve(4); int i = 0; while (i <...
The vector reserve method does not change the size of the vector, it changes the amount of allocated memory, possibly. You still cannot write to the indices 0 through 3 in the loop you have in the first example because the size of the vector is still 0. You'd want resize, which also changes the size.
64,810,143
64,810,276
Aggregate / designated initialization of c++ struct: Refer directly to another field
When using aggregate / designated initialization of a struct it is possible to refer to another field like this: #include <stdio.h> int main() { struct { int a; int b; } s = { .a = 3, .b = s.a + 1, }; return 0; } We use s.a in the initialization of s.b. However, we need to refer to s....
Is it possible to refer directly to s.a as just .a, or similar? No, .a in this context is a designator, and it cannot be referred to in the brace-or-equal-initializer used to initialize a given data member by means of its matching designator. struct Bar { int a; }; struct Foo { int a; Bar b; }; int main() {...
64,810,988
64,811,125
What is an unevaluated operand in the way a 'requires expression' sees it?
Note 2 in the standard [expr.prim.req.general] states: Expressions appearing within a requirement-body are unevaluated operands. Simply put, unevaluated operands are operands that is not evaluated. Consider the code below: #include <iostream> int fun(int) { return 5; } template<typename R> struct T { static R x; };...
An expression still needs to be grammatically correct (as in, in compliance with C++'s grammar as outlined by the standard), evaluated or not. int&&& is not valid per the grammar. (there is no such thing as a ref-qualifier ref-qualifier) (You can kinda get this by passing an lvalue to a template receiving T&&, but it w...
64,811,020
64,811,390
How to delete from the last node in a linked list to a specific node in that list using recursion
So i am trying to delete from a specific node in a linked list but the problem doesn't come from deleting from the node to end ,it comes from trying to delete from the last node to a specific node while trying to use a recursion. This is what I currently have (deleting from the node to last node) void rLL<T> :: recurs...
The answer to your question is to simply perform the recursive call before calling delete. However, even if you were able to delete the specified node without failure, the code you presented would still have a major flaw - it does not update the next field of the node prior to the specified node, so you would end up le...
64,811,257
64,811,325
Difference between " | " or " & " for calculations and inside IF statement
I'm trying using | inside a IF (or SWITCH) statement to compare if a variable is equal to a number or another. But I found (described as an example in code below) that using | operator to two numbers that I wanna compare is the same result as I put an || for two comparisons. But if I declare another variable that ORs t...
The expression in this if statement else if (n3 == n1 | n2) is equivalent to else if ( ( n3 == n1 ) | n2) The subexpression n3 == n1 ( 3 == 5 ) yields boolean value false that used in expressions is implicitly converted to 0. So 0 | n2 gives non-zero value equal to n2. Thus the result of the expression is boolean...
64,811,962
64,812,782
Is it possible to save a password in a c++ file without leaking my file
I am writing a ftp uploader file in c++ and i cant figure out how to login to the ftp server with the file without putting my password into the code. Here is my code: void UploadFTP(string uploadFile) { ofstream ftpFile; ftpFile.open("ftpcmd.dat", ios_base::app); ftpFile << "user <USER>\n"; ftpFile << "...
how to login to the ftp server with the file without putting my password into the code. You can choose one of these options: Configure the FTP server to not require a password Let the user input the password Store the password in a separate file that the program reads If you wanted to prevent the user from finding ...
64,812,062
64,812,444
Multiple parameter packs as factory function arguments
I am trying to create a factory method that instantiates a template class by passing the constructor arguments for the component classes as template parameter packs. The ProducerConsumer template is parameterized on the types of the Producer and Consumer, which are aggregated by ProducerConsumer. Arguments to the facto...
Two issues: forwarding reference is reserved to T&&, C<T&&> is not forwarding reference. tuple variable is not a variadic variable, you cannot use ... on it. in C++17, there is std::make_from_tuple to do what you want: template < typename ... ProducerArgs, typename ... ConsumerArgs > static ProducerConsumer* cr...
64,812,126
64,812,228
Avoid double-move when returning a pair in C++
I'm trying to write a function that returns a pair of objects, one of which is harder to construct than the other. This code comes close to illustrating what I'm trying: #include<iostream> #include<tuple> using namespace std; struct A { int i; A(A&& a): i(a.i) { cout << "move-constructing A: "<<a.i<<"\n"; } A(i...
You might use std::forward_as_tuple to avoid extra move constructor: return {piecewise_construct, std::forward_as_tuple(move(a)), make_tuple(10)}; Demo So you have std::tuple<A&&> instead of std::tuple<A> (which move construct).
64,812,138
64,812,579
How template explicit instantiation works and when?
Here is an exercise from C++ primer 5th edition: "Exercise 16.26: Assuming NoDefault is a class that does not have a default constructor, can we explicitly instantiate vector<NoDefault>? If not, why not?" Here is my guess: Yes we can instantiate it: template <typename T> class Foo { public: void func(){cout << x_.v...
In the Standard, the [temp.explicit] section explains what happens in an explicit instantiation. In particular, p12 provides that: An explicit instantiation definition that names a class template specialization explicitly instantiates the class template specialization and is an explicit instantiation definition of onl...
64,812,447
64,812,653
C++: Syntax of passing a pointer array through a function
So I have these 2 methods: the first is meant to take in 5 integer values, sum them up, then call the findLowest() method that returns the lowest found value, and subtracts that from the sum (then divides by 4 and prints results to screen). I think the issue I'm having is the values it's returning are memory addresses....
You are almost there, but you should not dereference on this line: sum -= findLowest(*arr); Instead, just pass in the array, because that is what the function expects: sum -= findLowest(arr); Unrelated: If you can, use a std::vector or std::array, the former for dynamically sized arrays, the latter for a compile tim...
64,812,534
64,813,534
vector persistent and transient in C++
Can someone help me to understand this code? What are transient() and persistent() doing here? Reference: CppCon 2017: Juan Pedro Bolivar Puente, "Postmodern immutable data structures" Time stamp: 19:03 vector<int> myitoa(vector<int> v, int first, int last) { auto t = v.transient(); for (auto i = first; i < las...
vector in this case is not std::vector, which has no transient() or persistent() methods, as the compiler error states. It is actually an immer::vector, as Juan states at 18:06: So, I'm using the immer namespace everywhere here. Nothing is std vector. This is an immutable vector ... If you listen to the video carefu...
64,812,771
64,812,815
Pass string literal to template function
I try to specialize a template function for a few types, one of them is const char*. template<typename T = const char*> void f(T&&); template<> void f<int>(int&& k) { std::cout << "Now in int fcn (" << k << ")!\n"; } template<> void f<const char*>(const char* && k) { std::cout << "Now in cc* fcn (" << k << ")!\n"; } ...
A string literal is not a const char*. A string literal has the type const char[N] where N is the number of characters plus a null terminator. That means when you call the function T gets deduced to const char[6], which does not match any of the specializations so the main template is used. Since you have not define...
64,813,063
64,814,399
Understanding XML CharData EBNF
The following EBNF rule expressed as CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) is really hard for me to understand. Can someone give a few examples of valid and invalid strings. A brief explanation of the what is being expressed in the rule would also be very helpful. Although perhaps asking a little much. It would...
The EBNF production for CharData, [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*) means that XML character data can consist of any characters except <, which begins markup (tags, comments, XML declarations, CDATA sections, and PIs) &, which begins entity references, the string of characters, ]]>, which ends a CDATA...
64,813,125
64,813,513
c++ : Initialize constexpr std-2DArray programmatically
I am new to C++ and in the process of learning. I have a matrix deftype: using Matrix = std::array<std::array<T, COL>, ROW>; I can initialize a constexpr matrix "manually" as such constexpr Matrix<int, 2,2> mat{ { {{ 1,2 }}, {{ 3, 4 } } }}; This is not feasible for large examples of ROW,COL. Instead i...
You can use an immediately invoked lambda: constexpr auto mat = []() { Matrix<int, 2, 2> result{}; int value = 1; for (std::size_t i = 0; i < result.size(); ++i) { for (std::size_t j = 0; j < result[0].size(); ++j) { result[i][j] = value; ++value; } } return...
64,813,376
64,813,424
How to properly read touch events and get position on a QWidget Qt
I'm trying to develop a game controller for an android app in qt and am having some issues. The controller works perfectly fine when I just use QMouseEvents instead of QTouchEvents, but the problem is that it doesn't support multiple points of contact. There doesn't seem to be an equivalent for QWidget::mousePressEvent...
The compiler may not know it's a touch event, but as long as you know it, you can downcast: case QEvent::TouchBegin: { QTouchEvent * te = static_cast<QTouchEvent *>(event); // now you can call te->touchPoints(), etc here } Note that the above code will invoke undefined behavior if event isn't actually pointing t...
64,813,455
64,813,490
Is memmove copying 0 bytes but referencing out of bounds safe
I have read online that memmove is expected to perform no action if the number of bytes to copy is 0. However what I want to know is if it is expected that the source and destination pointers will not be read in that case Below is a simplified version of some of my code, the section I am interested in is shiftLeft: #in...
The memmove function will copy n bytes. If n is zero, it will do nothing. The only possible issue is with this, where index is already at the maximum value for array elements: &arr[index + 1] However, you are permitted to refer to array elements (in terms of having a pointer point to them) within the array or the hypo...
64,813,929
64,814,202
What is the proper way to average a set of complex numbers in c++?
I have inherited some C++ code that needs to average some complex numbers. Given a collection, it adds those values which pass a condition to an accumulator, then divides by the number of values added. Using gcc (currently, gcc 8) I get template argument deduction/substitution failed if I use stand-alone operator/ but ...
Not sure what the most proper way to do division for it, but if you look through all the parameters operator/ and operator/= take, you would notice that: operator/ takes in either std::complex<T> or T. So if you have your original complex created with double, then it should only take in another value that is either d...
64,814,163
64,814,247
I can only access elements of a vector while inside a for loop
I have a function with a vector that is passed in by reference. I am able to use the vector inside a for loop to write its contents to a file. However, if I try to access any index of the vector outside of the loop, is gives me this error: terminate called after throwing an instance of 'std::out_of_range' what(): ve...
I can only access elements of a vector while inside a for loop No, you can access elements of a vector anywhere where the vector is is scope. But you need to ensure you're accessing actual elements, not made-up ones :-) With regard to the (slightly modified) code: //cout << wordVector.at(0) << endl; // TH...
64,814,420
64,814,421
How can I create and use a dynamic library ".so" from CUDA C++ and use it inside C# code under Linux environment (CentOS)?
I am trying to create a dynamic library .so using CUDA C++ kernel to use it inside C# code under Linux environment (CentOS). I searched for a way yo do this, but unfortunately didn't find a complete clear solution for it. Some solutions only make partial part of it, like creating C++ shared library on Linux, or creatin...
After searching multiple different solutions, and trying to collect and test the available possibilities, I finally reached to this simple method. The original C++ library can be made using gcc in one step like this answer. gcc -shared -o dll.so -fPIC dllmain.cpp but make sure to add extern "C" before the required fun...
64,814,437
64,848,087
*FIXED *constantly update console using cpp (msfs2020 SimConnect)
example picture Im trying to constantly update the console number related to altitude. At the moment its a static number, and does not update while the plane is gaining, or loosing altitude. There is a comment near the bottom of the text referring to the prinf() that im using to send it to console(not sure what all was...
Found the issue. If you CTRL-F "hr = SimConnect_RequestDataOnSimObject(hSimConnect, REQUEST_AP_SETTINGS, DEFINITION_ID_AP, SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_PERIOD_ONCE);", you can see that I use SIMCONNECT_PERIOD_ONCE. looking into the documentation (https://www.prepar3d.com/SDKv4/sdk/simconnect_api/references/str...
64,814,746
64,814,774
Is there a C or C++ equivalent to 'pass' in python?
Is there a C or C++ equivalent to 'pass' in python? Also the same with break. For example: while True: if x == 1: break else: pass But in C/C++ instead?
Is there a C or C++ equivalent to 'pass' in python? Yes. There are actually two equivalents. One is the null statement: ; Another is the empty block statement: {} These are in most cases inter-changeable except the null statement cannot be used in all cases where the empty block statement can. For example, the func...
64,814,789
64,814,913
How can I de-duplicate code without declaring an additional function in C/C++?
I am developing a chess engine and am working on move generation. For example, here is my function for generating moves for the black knight: /** Pseudolegal moves don't take check into account. */ std::vector<uint8_t> generate_pseudolegal_bknight_moves(std::shared_ptr<Position> position, ...
If you don't want overhead you can use a template parameter and if constexpr: enum class Color { WHITE, BLACK }; template <Color C> std::vector<uint8_t> generate_pseudolegal_knight_moves(std::shared_ptr<Position> position, uint8_t square) { ... if constexpr (C == Color::WHITE) { ...
64,815,196
64,816,518
Print User Selected Line
In the program, each line of the text file is read into an array. I need to have the user input a line number, then that line of the text file will be printed. How is this done? Thanks! #include <iostream> #include <fstream> #include <string> using namespace std; void file() { string array[2990]; short loop=0;...
I am assuming that you wanted to print the line that the user inputs to so for example if user input line 3, then you will print the third line. If that is so, the following will work. #include<bits/stdc++.h> using namespace std; struct OpenFailException : public exception{ const char* what() const throw (){ ...
64,815,385
64,815,417
Issue in initialization of constructor from derived class
In a.hpp file class top { public: class Base { int x; int y; public: Base(int p, int q) : x(p), y(q) {} }; class Derived : public Base { public: Derived():Base ( NULL, NULL ); // error }; }; I have a base class and a derived class. While calling the constructor of derived class I wa...
// error What wrong am I doing here? When you get an error, the first step is to read the error message. You are doing these wrong: You initialise a integers with NULL. NULL is only for pointers. Not all null pointer constants are integer literals, so this may or might not be ill-formed on all language implementat...
64,815,712
64,817,253
How to specify a custom decimal separator for numbers in Boost.Locale?
I've read the Boost.Locale docs several times through, but still can't find the answer to this seemingly easy problem: I need to output using a specific locale (e.g. ru_RU), but with a customized decimal separator (e.g. dot instead of comma). Is this possible? For dates, there's the "ftime" manipulator that allows to s...
You can use the C++ <locale> library. std::string russian_number_string(int n) { std::stringstream ss; ss.imbue(std::locale("ru_RU")); ss << n; return ss.str(); }
64,815,748
64,816,886
"engine.rootObjects().first()" in main.cpp crashes when main.qml imports over HTTP
We have a line of code that I've been using forever (or longer) to fetch a pointer to the root window. We've recently started importing our components from a server using the HTTP syntax for import. When we put then together, the program crashes, with engine.rootObjects().first() returning empty. Here is a simplified "...
There is nothing obscure but it is expected behavior. The rootObjects are assigned to C++ when the object is finished building and since you have an asynchronous loading url (the http) then the construction is asynchronous. So if you want to get root then you must use the objectCreated signal: QObject::connect(&engine,...
64,815,831
64,816,194
(C++) How to call a variable name or get the value of a variable in different cpp files?
enter image description here if I want to call use the value of char slide_piece in another cpp file. How do i implement the header file and how to call the function? Thanks
GameLogic is a class and slide_piece should be a member of it. Than you have to add a getter function: // GameLogic.h class GameLogic { public: char get_slide_piece() // getter function { return m_slide_piece; } // The rest of the class: bool MouseDown( char file, char rank, wxPoint ...
64,816,035
64,816,998
Using Poco ProcessHandle to send commands and get the result is getting exception
I am trying to send a simple commands such as "dir" in Windows via Poco's ProcessHandle and get the result from it in C++. But it is not able to return me anything, I'm getting exceptions ("System exception") from the code below. I have similar usage of the ProcessHandle but it is usually about opening an .exe file and...
I found the answer. It seems that I just have to do something like this: Poco::Process::Args args; args.push_back("/c"); args.push_back("dir"); string command = "cmd.exe"; Poco::Pipe outPipe; Poco::ProcessHandle ph(Poco::Process::launch(command, args, 0, &outPipe, 0)); Poco::PipeInputStream istr(outPipe); std::strin...
64,816,417
64,816,805
Getting Runtime Error(SIGSEGV) on SPOJ , can't find out what's wrong in my code
I know this type of question has been asked before but I can't find a solution to this, I know its a invalid memory reference error or array out of bounds, but I can't seem to find the cause of the error in my code. I just tried this problem on SPOJ, it was the 'Transform the Expression' https://www.spoj.com/problems/O...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long int t; cin>>t; while(t--){ string str; std::stack<char> f ; cin>>str; string ans=""; for(int i=0;i<str.size();i++){ switch(str[i]){ case '(': br...
64,817,399
64,817,442
how to convert cpp typeid(T).hash_code() to type. (having void* destroy function PROB)
I'm making some Manager class like this. #pragma once #include <iostream> #include <unordered_map> using namespace std; class TestMgr { public: TestMgr() = default; ~TestMgr() { for (auto iter = m_test.begin(); iter != m_test.end(); ) { delete iter->second; // void* doesn't call d...
The easiest solution would be a virtual CObjectBase::~CObjectBase. Now you don't need a void* anymore.
64,817,785
64,818,009
C++ multithreading; use of deleted function / invocable of conversion to rvalues
I'm writing an multithreading programing in C++. I'm also new to C++. I use the SFML library for it. I want to execute an method in an object in a new thread. Here's the code I want to execute: // [...] Protocol user_connection; std::thread new_con (&Protocol::connect, &user_connection, std::ref(client)); // [...] The...
The code in your example ain't a minimal reproducible example, so I created one on compiler-explorer. The problem you are having is a mismatch between the arguments you pass via std::thread to the function with the arguments the function accepts that is passed. Let's look at std::thread new_con (&Protocol::connect, &us...
64,818,000
64,818,439
dead-lock with condition_variable
I'm having a dead-lock when trying to notify a condition_variable from a thread. Here is my MCVE: #include <iostream> #include <boost/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> static boost::mutex m_mutex; static boost::condition_variable m_cond; void threadFunc() { ...
The problem is that if timed_wait completes before notify_all is called it will then have to wait for the thread to release the mutex (i.e. after it has called notify_all) before it resumes then will call timed_wait again, the thread has finished so timed_wait will never succeed. There are two scenarios where this can ...
64,818,577
64,818,719
Why is designated initialization accepted by gcc with no effect, and generated aggregate is somehow passed as arguments to class constructor
Ok, we have this code: #include <iostream> using namespace std; class A{ public: A(double b, int g) { cout << "b = " << b << ", g = " << g << endl; } }; int main() { A a = {.g = 5.0, .j = 10}; // output: b = 5, g = 10 A b = {.b = 5.0, .g = 10}; // output: b = 5, g = 10 A bb ...
A class that has a user defined constructor is not an aggregate class. If designated initialiser is used, then the class shall be an aggregate. Your program uses designated initialiser on a non-aggregate, therefore it is an ill-formed program. Compilers are allowed to not compile it and are required to diagnose the iss...
64,818,759
64,818,831
How to do a specific double "for" loop to do a calcul
I would like to be able to do a loop that be able to make a count like this : 00 01 02 03 04 10 11 12 13 14 20 12 22 23 24 30 31 32 33 34 40 41 42 43 44 The way they are wrote is not important, I just want to be able do a count from 0 to 4 on the right number, then it do a + to the left number, and...
This should do the trick: for (int i = 0; i < TAILLE; i++) { for (int j=0; j <TAILLE; j++) { cout << i << j << ' '; } cout << endl; } some notes on this code: 1.- Instead of i<=TAILLE -1 use i<TAILLE it is shorter and easier to read. Also it is more computationally efficient since you avoid the sub...
64,818,867
64,876,439
Compile a TensorFlow Lite project for microcontrollers with arm-none-eabi-gcc
I just downloaded the TensorFlow repository from github (https://github.com/tensorflow/tensorflow (v.2.3.1)). I included it in my C++ project. After I make my Makefile I got the error: make arm-none-eabi-gcc -L -std=c11 -Wall -Wextra --pedantic -DSTM32 -DSTM32F7 -DSTM32F746xx -DSTM32F746NGHx -DSTM32F746G_DISCO -mcpu=co...
I got the solution. In your Makefile you have to include the directory of your TensorFlow library. This part of my Makefile looks in my case like this:\ Includes and Defines\ INCLUDES += -I ./inc\ INCLUDES += -I ./lcd/inc\ INCLUDES += -I ./STM32F7_library/Drivers/CMSIS/Include\ INCLUDES += -I ./STM32F7_library/Drivers/...
64,819,262
64,820,893
compile failed with gcc but success with msc++
I use gcc compile, the version is (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0 in Ubuntu 18.0.4 64 bits. The below code can be compiled success with msvc++ 2015, but failed with gcc. class BaseClass { }; template <typename T> class CPIPtr { public: CPIPtr() { _p = nullptr; } CPIPtr(const CPIPtr& item...
The problem is in the line, ITest1Ptr test1 = test; This would call the copy constructor, but before that it fails in type conversion, instead use, ITest1Ptr test1 = static_cast<ITest1Ptr>(test); or, ITest1Ptr test1 (test); This following line is calling the assignment operator, which is ok, test = test1;
64,819,628
64,820,074
Extracting message content from JSON using regular expresions
I need to extract content of messages from JSON, I am not allowed to use JSON parser so I tried using regular expressions, however I got stuck on extracting message content. I am using C++. Here's an example of the JSON file: { "id":"776752463986294785", "type":0, "content":"\"", "channel_id":"7621068390548...
You can make it escape \" as follows: "content"[ :]+(\"(?:\\.|[^"])*\") It creates a non-capturing group that matches every \ with the following character, as well as the original [^"] criteria.