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
69,604,839
69,617,582
Unable to display image opencv (c++)
I finally managed to build the opencv4.5.4 library from source but now I'm facing errors that I'm unable to fix. I'm using this medium article as my guide https://medium.com/analytics-vidhya/how-to-install-opencv-for-visual-studio-code-using-ubuntu-os-9398b2f32d53 When I try to execute a simple program that prints the version of opencv installed, it executes without errors. #include <opencv2/opencv.hpp> #include <iostream> int main() { std::cout << "OpenCV Version: "<< CV_VERSION << std::endl; return 0; } makefile: CC = g++ PROJECT = new_output SRC = new.cpp LIBS = `pkg-config --cflags --libs opencv4` $(PROJECT) : $(SRC) $(CC) $(SRC) -o $(PROJECT) $(LIBS) Output: username@Inspiron-7591:~/SeePluPlu/opencv-test$ sudo make g++ new.cpp -o new_output `pkg-config --cflags --libs opencv4` username@Inspiron-7591:~/SeePluPlu/opencv-test$ sudo ./new_output OpenCV Version: 4.5.4-dev Now when I try to run another program to display an image things get out of hand really quick. #include <iostream> #include <opencv2/opencv.hpp> #include<opencv2/highgui.hpp> using namespace cv; using namespace std; // Driver code int main(int argc, char** argv) { // Read the image file as // imread("default.jpg"); Mat image = imread("lena.jpg",IMREAD_GRAYSCALE); // Error Handling if (image.empty()) { cout << "Image File " << "Not Found" << endl; // wait for any key press cin.get(); return -1; } // Show Image inside a window with // the name provided imshow("Window Name", image); // Wait for any keystroke waitKey(0); return 0; } Output: username@Inspiron-7591:~/SeePluPlu/opencv-test$ ./new_output Gtk-Message: 18:49:40.321: Failed to load module "atk-bridge" Gtk-Message: 18:49:40.324: Failed to load module "canberra-gtk-module" terminate called after throwing an instance of 'cv::Exception' what(): OpenCV(4.5.4-dev) /home/username/opencv/modules/core/src/alloc.cpp:73: error: (-4:Insufficient memory) Failed to allocate 120542625076320 bytes in function 'OutOfMemoryError' Aborted (core dumped) but when I give root privilages... username@Inspiron-7591:~/SeePluPlu/opencv-test$ sudo ./new_output Gtk-Message: 18:49:31.985: Failed to load module "canberra-gtk-module" terminate called after throwing an instance of 'cv::Exception' what(): OpenCV(4.5.4-dev) /home/username/opencv/modules/core/src/alloc.cpp:73: error: (-4:Insufficient memory) Failed to allocate 112126257730176 bytes in function 'OutOfMemoryError' Aborted when I rerun the binary file (./new_output) over and over again I end up getting assertion errors as well. I searched for loading the canberra-gtk-module and atk-bridge but whatever I found was not of any help https://askubuntu.com/a/565789 https://askubuntu.com/a/1300284 https://askubuntu.com/questions/342202/failed-to-load-module-canberra-gtk-module-but-already-installed (all solutions in this thread) Note: I'm positive that the image is being read and I'm able to print its size using image.size() function and I think it has something to do with the imshow() function... Not sure. Any help or detail is very much appreciated. Thanks in advance!
When I tried to build opencv4 again, I was able to figure out that cmake was unable to find the gtk+-3.0 module that's installed in my system. username@Inspiron-7591:~$ pkg-config --modversion gtk+-3.0 Package gtk+-3.0 was not found in the pkg-config search path. Perhaps you should add the directory containing `gtk+-3.0.pc' to the PKG_CONFIG_PATH environment variable No package 'gtk+-3.0' found even though it was already installed... username@Inspiron-7591:~$ sudo apt-get install libgtk-3-dev [sudo] password for username: Reading package lists... Done Building dependency tree Reading state information... Done libgtk-3-dev is already the newest version (3.24.20-0ubuntu1). libgtk-3-dev set to manually installed. 0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded. I stumbled upon this gem of a thread while googling my issue https://stackoverflow.com/a/50038996/15341103 and I was able to make pkgconfig detect gtk+-3.0 I rebuilt opencv4 again this time and it works!
69,605,048
69,605,126
Calling a callback passed from another class
I want to register a callback handler (method) of the one class (Y) in another (X). I can't use std::function because of possible heap allocation and I must have an access to members of a class that registers the handler. I also want to avoid static functions. I've came up with some workaournd but got stuck on calling the callback: template<class T> using clbkType = void(T::*)(void); template<class T> class X { public: void registerClbck(clbkType<T> clbk) { callback = clbk; } void call() { callback(); // ERROR C2064: term does not evaluate to a function taking 0 arguments. //(((X<T>*)this)->X<T>::callback)(); // same error } private: clbkType<T> callback; }; class Y { public: Y() { x.registerClbck(&Y::handler); } // just for a test: fire a callback in class X void fire() { x.call(); } int getA() { return a; } private: int a{ 0 }; X<Y> x{}; void handler() { a = 5; } }; int main() { Y y; y.fire(); return y.getA(); } link to code: https://godbolt.org/z/PhY41xsWE PS. I'm not sure if this is a safe solution, so please put any comment on that. Thanks!
The member function pointer needs a specific class object to invoke, so you need to do this: template<class T> class X { public: // ... void call(T& obj) { (obj.*callback)(); } // ... }; class Y { public: // just for a test: fire a callback in class X void fire() { x.call(*this); } // ... }; Demo.
69,605,073
69,605,540
antlr visitor: lookup of reserved words efficiently
I'm learning Antlr. At this point, I'm writing a little stack-based language as part of my learning process -- think PostScript or Forth. An RPN language. For instance: 10 20 mul This would push 10 and 20 on the stack and then perform a multiply, which pops two values, multiplies them, and pushes 200. I'm using the visitor pattern. And I find myself writing some code that's kind of insane. There has to be a better way. Here's a section of my WaveParser.g4 file: any_operator: value_operator | stack_operator | logic_operator | math_operator | flow_control_operator; value_operator: BIND | DEF ; stack_operator: DUP | EXCH | POP | COPY | ROLL | INDEX | CLEAR | COUNT ; BIND is just the bind keyword, etc. So my visitor has this method: antlrcpp::Any WaveVisitor::visitAny_operator(Parser::Any_operatorContext *ctx); And now here's where I'm getting to the very ugly code I'm writing, which leads to the question. Value::Operator op = Value::Operator::NO_OP; WaveParser::Value_operatorContext * valueOp = ctx->value_operator(); WaveParser::Stack_operatorContext * stackOp = ctx->stack_operator(); WaveParser::Logic_operatorContext * logicOp = ctx->logic_operator(); WaveParser::Math_operatorContext * mathOp = ctx->math_operator(); WaveParser::Flow_control_operatorContext * flowOp = ctx->flow_control_operator(); if (valueOp) { if (valueOp->BIND()) { op = Value::Operator::BIND; } else if (valueOp->DEF()) { op = Value::Operator::DEF; } } else if (stackOp) { if (stackOp->DUP()) { op = Value::Operator::DUP; } ... } ... I'm supporting approximately 50 operators, and it's insane that I'm going to have this series of if statements to figure out which operator this is. There must be a better way to do this. I couldn't find a field on the context that mapped to something I could use in a hashmap table. I don't know if I should make every one of my operators have a separate rule, and use the corresponding method in my visitor, or if what else I'm missing. Is there a better way?
With ANTLR, it's usually very helpful to label components of your rules, as well as the high level alternatives. If part of a parser rule can only be one thing with a single type, usually the default accessors are just fine. But if you have several alternatives that are essentially alternatives for the "same thing", or perhaps you have the same sub-rule reference in a parser rule more than one time and want to differentiate them, it's pretty handy to give them names. (Once you start doing this and see the impact to the Context classes, it'll become pretty obvious where they provide value.) Also, when rules have multiple top-level alternatives, it's very handy to give each of them a label. This will cause ANTLR to generate a separate Context class for each alternative, instead of dumping everything from every alternative into a single class. (making some stuff up just to get a valid compile) grammar WaveParser ; any_operator : value_operator # val_op | stack_operator # stack_op | logic_operator # logic_op | math_operator # math_op | flow_control_operator # flow_op ; value_operator: op = ( BIND | DEF); stack_operator : op = ( DUP | EXCH | POP | COPY | ROLL | INDEX | CLEAR | COUNT ) ; logic_operator: op = (AND | OR); math_operator: op = (ADD | SUB); flow_control_operator: op = (FLOW1 | FLOW2); AND: 'and'; OR: 'or'; ADD: '+'; SUB: '-'; FLOW1: '>>'; FLOW2: '<<'; BIND: 'bind'; DEF: 'def'; DUP: 'dup'; EXCH: 'exch'; POP: 'pop'; COPY: 'copy'; ROLL: 'roll'; INDEX: 'index'; CLEAR: 'clear'; COUNT: 'count';
69,605,973
69,606,233
Comparison of two vectors leads to an exception
Comparing the two vectors in the if statement throws an exception (segmentation fault). I was having an attempt to create a system, which, user details are being saved in a file and being read to give security questions to the user. #include <iostream> #include <string> #include <vector> #include <fstream> int main(int argc, char** argv) { std::vector<std::string>setup_file_contents_vec{}; std::ifstream setup_file_required_scan( "exposcan.txt" ); std::string buffer; while(setup_file_required_scan >> buffer) { setup_file_contents_vec.push_back(buffer); } std::vector <std::string> user_details_confirmation(3); std::cout << " Login details 1/3\n\n"; std::cout << "First Name : "; std::cin >> user_details_confirmation[0]; if(user_details_confirmation[0] != setup_file_contents_vec[0]) {/* code */} /*Exception occurs*/ }
Thanks to @IgorTandetnik the issue was that the file was empty.
69,606,301
69,606,443
How can i create multiple threads cleaner?
so i creating multiple threads with the following way: std::thread Thread1(func1); Thread1.detach(); std::thread Thread2(func2); Thread2.detach(); I doing that around 10 times, and it works perfectly fine, but it just looks ugly, is there any method to do it cleaner? Thanks!
You can achieve this syntax for (auto func : { func1, func2 }) async(func); with this example : #include <chrono> #include <functional> #include <vector> #include <thread> #include <iostream> void func1() { std::cout << "1"; } void func2() { std::cout << "2"; } // Make functions out of repeated things template<typename Fn> void async(Fn fn) { std::thread(fn).detach(); } int main() { for (auto func : { func1, func2 }) async(func); // I really don't like sleeps. // but async doesn't allow for any kind of synchronization // so allow for some time to pass so functions can show output std::this_thread::sleep_for(std::chrono::seconds(2)); return 0; }
69,606,521
69,607,314
How to remove the last number 0 in the fibonacci series in c++?
I m trying to remove the last 0 in the fibonacci series as i m removing return 0; the last value is showing garbage value something like 735150 what should i edit to get the desired output as 0 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 as i m getting the output 0 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 0 #include <iostream> using namespace std; class fibo { private: unsigned long int n1,n2,final; public: fibo() { n1 = 0; n2 = 1; final = n1 + n2; } fibo(int x1,int x2) //Parameterised Constructor { n1 = x1; n2 = x2; for (int x = 0;x<=8; x++) { final = n1 + n2; cout << final << " "; n1 = n2; n2 = final; } } int calc() { for (int x = 0;x<=8; x++) { final = n1 + n2; cout << final << " "; n1 = n2; n2 = final; } return 0; } fibo(fibo &i); // Copy Constructor }; fibo::fibo(fibo &i) { n1= i.n1; n2 = i.n2; final = i.final; } int main() { cout << "0 " ; fibo f1(0,1); fibo f2 = f1; cout << f2.calc() << endl; return 0; }
I'm perfectly aware this isn't code review but OP asked for a simpler version. This is not conforming to the odd copy constructor requirement, but rather to show that printing the fibonacci numbers can be dealt with in a few(8) lines of code. #include <iostream> #include <vector> #include <algorithm> // This is a poor time to use a classes and objects, // This is simply a straightforward algorithm. // calculation is not an object // As Nathan says, it is a bizarre design // Generate numbers std::vector<int> fibonacci_numbers(int N){ auto n0 = 0; // not used in output auto n1 = 1; // first value in output auto next_fib = [&n0,&n1](){ auto value = n1; auto next = n0 + n1; n0 = n1; n1 = next; return value; }; auto result = std::vector<int>(N); std::generate(result.begin(), result.end(), next_fib); return result; } // Print void print_fibo(int N){ int n0 = 0; // not for printing int n1 = 1; while(N--){ auto next_fib = n0 + n1; std::cout << n1 << ", "; n0 = n1; n1 = next_fib; } } int main() { // seems like you want 19 numbers // generating auto fibs = fibonacci_numbers(9); for(auto e:fibs){ std::cout << e << ", "; } // just printing std::cout << '\n'; print_fibo(19); std::cout << '\n'; return 0; }
69,606,918
69,608,298
Maximum number of packets
There are r red balls, g green balls and b blue balls. Also there are infinite number of packets given to you. Each packet must be filled with only 3 balls and should contain balls of at least 2 different colors. Find the maximum number of packets that can be filled? Here is my approach using Dynamic Programming which is straight forward map<multiset<int>,int> store; int packets(int r,int g,int b){ if (r<0||g<0||b<0){ return 0; } if (r==g&&g==b){ return r; } if ((r+g==0)||(g+b==0)||(b+r==0)){ return 0; } if (r==0&&b==0&&g==0){ return 0; } multiset<int> key; key.insert(r);key.insert(g);key.insert(b); if (store.find(key)!=store.end()){ return store[key]; } int max_packets = packets(r-2,g-1,b)+1; max_packets = max(max_packets,packets(r-2,g-1,b)+1); max_packets = max(max_packets,packets(r-1,g-2,b)+1); max_packets = max(max_packets,packets(r-2,g,b-1)+1); max_packets = max(max_packets,packets(r-1,g,b-2)+1); max_packets = max(max_packets,packets(r,g-2,b-1)+1); max_packets = max(max_packets,packets(r,g-1,b-2)+1); max_packets = max(max_packets,packets(r-1,g-1,b-1)+1); store[key] = max_packets; return max_packets; } My solution may be logically correct but is surely inefficient for large values of r,g and b. I also identified some patterns for r,g,b vs maximum packets but cannot prove them logically. Can someone help me with their idea?. Thank you
Assume without loss of generality that r ≥ g ≥ b by permuting the colors. The answer is at most ⌊(r+g+b)/3⌋ because every packet needs 3 balls. The answer is at most g+b because every packet needs a green ball or a blue ball. It turns out that the answer is equal to the minimum of these two quantities (so without the assumption, min((r+g+b)/3, r+g, r+b, g+b) assuming truncating division as in C++). We form b packets with one blue ball and two of whichever of red or green has more balls remaining, or one of each if they’re tied. After these packets, let r′ be the number of red balls remaining and g′ be the number of green balls remaining. If r′ > 2g′ and there are at least three balls remaining, then we cannot have used any green balls yet, and we hit our quota of g+b by packing them with two red balls each. Otherwise, we form packets with either two red balls and one green ball or one red ball and two green balls so as to leave less than three balls, which means that we have formed ⌊(r+g+b)/3⌋ packets, as required.
69,607,185
69,607,296
How to know which keys are pressed in SDL2
How would I know what keys are currently being pressed in SDL2 (not event)?
if (SDL_GetKeyboardState(nullptr)[SDL_SCANCODE_???]) {/*the key is held*/} where ??? is a key name, one of those.
69,607,408
69,644,189
C26485 and pointer decay with TCHAR in exception handler
I don't understand this C26485 warning I receive. My code is an exception handler: catch (CDBException* e) { TCHAR szError[_MAX_PATH]; e->GetErrorMessage(szError, _MAX_PATH); AfxMessageBox(szError); } It is saying: Expression szError: No array to pointer decay (bounds.3). Both GetErrorMessage and AfxMessageBox are flagging this. It doesn't make sense to me. Thanks for your help.
This diagnostic is an unfortunate result of the code analysis taking too narrow a view, ignoring hints that are readily available. C26485 warns against array-to-pointer decay, one of C++' most dangerous features. When passing the name of an array to a function that expects a pointer, the compiler silently converts the array into a pointer to its first element, thereby dropping the size information that's part of the array type. Clients that call into an interface that accepts individual arguments (pointer and size) to describe an array must make sure that the size actually matches that of the array. This has caused countless CVE's, and there's no reason to believe that the situation is getting any better. Array-to-pointer decay is dangerous and having tooling guard against it is great. In theory. Here, however, things are different. The declaration (and definition) of GetErrorMessage have SAL Annotations that allow the compiler to verify, that pointer and size do match, at compile time. The signature is as follows: virtual BOOL GetErrorMessage(_Out_writes_z_(nMaxError) LPTSTR lpszError, _In_ UINT nMaxError, _Out_opt_ PUINT pnHelpContext = NULL) const; The _Out_writes_z_(s) annotation establishes a compile-time verifiable relationship between the pointer lpszError and its corresponding array's size nMaxError. This is helpful information that should be taken advantage of whenever possible. First, though, let's try to address the immediate issue, following the recommendation from the documentation: An explicit cast to the decayed pointer type prevents the warning, but it doesn't prevent buggy code. The most compact way to turn an array into a pointer to its first element is to literally just do that: catch (CDBException* e) { TCHAR szError[_MAX_PATH]; e->GetErrorMessage(&szError[0], _MAX_PATH); AfxMessageBox(&szError[0]); } This fixes the immediate issue (on both function calls, incidentally, even if for different reasons). No more C26485's are issued, and—as an added bonus—passing an incorrect value as the second argument (e.g. _MAX_PATH + 1) does get the desired C6386 diagnostic ("buffer overrun"). This is crucially important, too, as a way of verifying correctness. If you were to use a more indirect way (say, by using a CString, as suggested here), you'd immediately give up on that compile-time verification. Using a CString is both computationally more expensive, and less secure. As an alternative to the above, you could also temporarily suppress the C26485 diagnostic on both calls, e.g. catch (CDBException* e) { TCHAR szError[_MAX_PATH]; // Decay is safe due to the _Out_writes_z_ annotation #pragma warning(suppress : 26485) e->GetErrorMessage(szError, _MAX_PATH); // Decay is safe; the previous call guarantees zero-termination #pragma warning(suppress : 26485) AfxMessageBox(szError); } Which of those implementations you choose is ultimately a matter of personal preference. Either one addresses the issue, with the latter being maybe a bit more preserving as far as code analysis goes. A word on why the final call to AfxMessageBox is safe: It expects a zero-terminated string, and thus doesn't need an explicit size argument. The _Out_writes_z_(s) annotation on the GetErrorMessage signature makes the promise to always zero-terminate the output string on return. This, too, is verified at compile time, on both sides of the contract: Callers can rely on receiving a zero-terminated string, and the compiler makes sure that the implementation has no return path that violates this post-condition.
69,607,416
69,607,512
Operator Overloading Matrix Multiplication
The issue I am having is how to get the correct number columns to go through for the inner most loop of K. An example is a 2x3 matrix and a 3x2 matrix being multiplied. The result should be a 2x2 matrix, but currently I dont know how to send the value of 2 to the operator overloaded function. It should be int k = 0; k < columns of first matrix;k++ Matrix::Matrix(int row, int col) { rows = row; cols = col; cx = (float**)malloc(rows * sizeof(float*)); //initialize pointer to pointer matrix for (int i = 0; i < rows; i++) *(cx + i) = (float*)malloc(cols * sizeof(float)); } Matrix Matrix::operator * (Matrix dx) { Matrix mult(rows, cols); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { mult.cx[i][j] = 0; for (int k = 0; k < ?;k++) //????????????? { mult.cx[i][j] += cx[i][k] * dx.cx[k][j]; } } } mult.print(); return mult; //calling Matrix mult(rowA, colB); mult = mat1 * mat2; }
Linear algebra rules say the result should have dimensions rows x dx.cols Matrix Matrix::operator * (Matrix dx) { Matrix mult(rows, dx.cols); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { mult.cx[i][j] = 0; for (int k = 0; k < cols;k++) //????????????? { mult.cx[i][j] += cx[i][k] * dx.cx[k][j]; } } } mult.print(); return mult;
69,607,484
69,607,550
Generate string lexicographically larger than input
Given an input string A, is there a concise way to generate a string B that is lexicographically larger than A, i.e. A < B == true? My raw solution would be to say: B = A; ++B.back(); but in general this won't work because: A might be empty The last character of A may be close to wraparound, in which case the resulting character will have a smaller value i.e. B < A. Adding an extra character every time is wasteful and will quickly in unreasonably large strings. So I was wondering whether there's a standard library function that can help me here, or if there's a strategy that scales nicely when I want to start from an arbitrary string.
You can duplicate A into B then look at the final character. If the final character isn't the final character in your range, then you can simply increment it by one. Otherwise you can look at last-1, last-2, last-3. If you get to the front of the list of chars, then append to the length.
69,607,662
69,607,757
Why does This program have a logical error
this is the code i wrote for simple grading exams (im still a very beginner) but when i do a wrong input in (Grades) it doesnt go to the function i made which is called (FalseInput) to make the user able to re-enter the (Grades) any suggestions to how to solve? and how to improve in general ? here is an example of whats the problem : Please Type Your Name : rafeeq Please Insert The Grade : as (which is an input error) you failed thanks. #include <iostream> #include <string> using namespace std; char Name[30]; int Grades; const int MinGrade(50); void FalseInput() { cout << "pleae enter the number again : "; cin >> Grades; if (Grades >= MinGrade) { cout << Name << " : " << "you passed\n"; cout << Grades; } else if (Grades < MinGrade and cin.fail() == 0) { cout << "you failed\n"; } else if (cin.fail() == 1) { cout << "its not a valid number\n"; cin.clear(); cin.ignore(1000, '\n'); cout << endl; FalseInput(); } } int main() { cout << "Please Type Your Name : "; cin.getline(Name, 30); cout << "Please Insert The Grade : "; cin >> Grades; if (Grades >= MinGrade) { cout << Name << " : " << "you passed\n"; cout << "The Grade Achieved : " << Grades << "%"; } else if (Grades < MinGrade) { cout << "you failed\n"; } else if (cin.fail() == 1) { cout << "its not a valid number\n"; cin.clear(); cin.ignore(1000, '\n'); cout << endl; FalseInput(); } return 0; }
You don't check if the extraction of an int succeeds here: cin >> Grades; You can check the state of the input stream after extraction like this and it needs to be the first condition or else the program will make the comparisons with MinGrade first and will get a true on Grades < MinGrade. if(!(cin >> Grades)) { if(cin.eof()) { // You can't recover the input steam from eof so here you need // to handle that. Perhaps by terminating the program. } cin.clear(); cin.ignore(1000, '\n'); cout << endl; FalseInput(); } else if(Grades >= MinGrade) { cout << Name << " : " << "you passed\n"; cout << "The Grade Achieved : " << Grades << "%"; } else if(Grades < MinGrade) { cout << "you failed\n"; } You do have a lot of unnecessary code duplication and you also use an array of char to read the name - but you have included <string> so I assume you're familiar with std::string. I suggest using that. Simplification: #include <iostream> #include <limits> #include <string> int main() { const int MinGrade = 50; std::string Name; int Grades; std::cout << "Please Type Your Name : "; if(std::getline(std::cin, Name)) { while(true) { std::cout << "Please Insert The Grade : "; if(!(std::cin >> Grades)) { if(std::cin.eof()) { std::cout << "Bye bye\n"; break; } std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "That's not a valid number!\nPlease enter the " "number again!\n"; } else if(Grades >= MinGrade) { std::cout << Name << " : " << "you passed\n"; std::cout << "The Grade Achieved : " << Grades << "%\n"; break; } else { // no need to check "Grades < MinGrade" here std::cout << "you failed\n"; break; } } } }
69,607,676
69,608,519
C++ and reading large txt files
I have a lot of txt files, around 10GB. What should I use in my program to merge them into one file without duplicates? I want to make sure each line in my output file will be unique. I was thinking about making some kind of hash tree and use MPI. I want it to be effective.
build a table of files, so you can give every filename simply a number (a std::vector<std::string> works just fine for that). For each file in a table: open it, do the following: read a line. Hash the line. Have a std::multimap that maps line hashes (step 3) to std::pair<uint32_t filenumber, size_t byte_start_of_line>. If your new line hash is already in the hash table, open the specified file, seek to the specified position, and check whether your new line and the old line are identical or just share the same hash. if identical, skip; if different or not yet present: add new entry to map, write line to output file read next line (i.e., go to step 3) This only takes the RAM needed for the longest line, plus enough RAM for the filenames + file numbers plus overhead, plus the space for the map, which should be far less than the actual lines. Since 10GB isn't really much text, it's relatively unlikely you'll have hash collisions, so you might as well skip the "check with the existing file" part if you're not after certainty, but a sufficiently high probability that all lines are in your output.
69,607,679
74,289,942
Cereal seems to not properly serialize an std::string
I am trying to serialize a class into a binary, to that effect I first started trying to serialize an std::string member within the class, I wrote this serialization method: template<typename Archive> void ShaderProgram::serialize(Archive& archive, ShaderProgram& program) { archive(CEREAL_NVP(program.program_name)); } Then I am trying to serialize and immediately read the class: ShaderProgram program; std::filesystem::create_directories(fs::path(cached_shader_path).parent_path()); std::ofstream os(cached_shader_path, std::ios::binary); cereal::BinaryOutputArchive archive_out( os ); ShaderProgram::serialize(archive_out, program); std::ifstream is(cached_shader_path, std::ios::binary); cereal::BinaryInputArchive archive_in( is ); ShaderProgram::serialize(archive_in, program); Which results in: terminate called after throwing an instance of 'cereal::Exception' what(): Failed to read 8 bytes from input stream! Read 0 The class I am testing this with is trivial: struct ShaderProgram { std::string program_name = "name"; template<typename Archive> static void serialize(Archive& archive, ShaderProgram& program); }; template<typename Archive> void ShaderProgram::serialize(Archive& archive, ShaderProgram& program) { archive(CEREAL_NVP(program.program_name)); } I don;t understand why this fails.
Here is an example. All is fine with cereal. In plain C++ remove Rcpp connections. // [[Rcpp::depends(Rcereal)]] #include <string> #include <fstream> #include <cereal/archives/binary.hpp> #include <cereal/types/string.hpp> #include <cereal/access.hpp> #include <Rcpp.h> struct ShaderProgram { ShaderProgram(){}; ShaderProgram(std::string program_name) : program_name{program_name}{}; ~ShaderProgram() = default; std::string get_program_name() const { return program_name; } private: std::string program_name{}; friend class cereal::access; template<class Archive> void serialize(Archive& archive) { archive(program_name); } }; // [[Rcpp::export]] int main() { { ShaderProgram sp("King Kong 8"); std::ofstream os("Backend/Serialize_StringProgram.bin", std::ios::binary); cereal::BinaryOutputArchive oarchive(os); oarchive(sp); } { ShaderProgram sp{}; std::ifstream is("Backend/Serialize_StringProgram.bin", std::ios::binary); cereal::BinaryInputArchive iarchive(is); iarchive(sp); Rcpp::Rcout << sp.get_program_name() << std::endl; } }
69,607,808
69,607,842
Why is my change to a range-for loop not work?
I'm at a loss. I am trying to sum two numbers of vector such that they equal target, then return their indices; however, when running the code with a C++11 for-loop, the result is incorrect. With vector [2,7,11,15] and target=9, the result for the C++11 loop is [0, 0]. Using the C-style loop, it is [0,1]. What gives? class Solution { public: vector<int> twoSumCstyle(vector<int>& nums, int target) { vector<int> sol(2); bool found = false; for (int i = 0; i< nums.size()-1; i++ ){ for ( int x = i +1; x <nums.size(); x++){ if (nums[i] + nums[x] == target) { sol[0] = i; sol[1] = x; found = true; break; } } if (found) break; } return sol; } vector<int> twoSumC11(vector<int>& nums, int target) { vector<int> sol(2); bool found = false; for (int i : nums ){ for ( int x = i +1; x <nums.size(); x++){ if (nums[i] + nums[x] == target) { sol[0] = i; sol[1] = x; found = true; break; } } if (found) break; } return sol; } };
Your outer loop is setting i to the actual value within your nums vector, but your inner loop is using it as if it's an index! As an explicit example, on the first iteration of your outer loop, i will be 2 and so your inner loop will start at x : 3. Since you're actually interested in the index as part of your calculations, it probably just makes the most sense to use the traditional-style for-loop.
69,608,219
69,608,598
Getting incorrect vectors when trying to do mouse picking in OpenGL 3
I am trying to get a direction vector to where my cursor is on the screen, however it gives me large values instead of the actual values. When doing mouse picking I am getting extremely small numbers for my world coordinates such as Mouse is pointing at World X: 4.03225e-05 Y: -0.00048387 Z: -1 Am I doing something wrong here, I have adapted this code from here. I am using glm::intersectLineTriangle() to test if the line is pointing at the triangles world coordinates in question. Here is the relevant code: double mouse_x, mouse_y; glfwGetCursorPos(GL::g_window, &mouse_x, &mouse_y); int width, height; glfwGetFramebufferSize(GL::g_window, &width, &height); // these positions must be in range [-1, 1] (!!!), not [0, width] and [0, height] float mouseX = (float)mouse_x / ((float)width * 0.5f) - 1.0f; float mouseY = (float)mouse_y / ((float)height * 0.5f) - 1.0f; glm::mat4 invVP = glm::inverse(projection * view); glm::vec4 screenPos = glm::vec4(mouseX, -mouseY, 1.0f, 1.0f); glm::vec4 worldPos = invVP * screenPos; glm::vec3 mouseClickVec = glm::normalize(glm::vec3(worldPos)); std::cout << "Mouse is pointing at World X: " << mouseClickVec.x << " Y: " << mouseClickVec.y << " Z: " << mouseClickVec.z << '\n'; glm::vec3 intersect; if(glm::intersectLineTriangle(glm::vec3(0.0f, 0.0f, 0.0f), mouseClickVec, m_vertices_world[0], m_vertices_world[0], m_vertices_world[0], intersect)) { std::cout << "Intersect at X: " << intersect.x << " Y: " << intersect.y << " Z: " << intersect.z << '\n'; setColor(glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)); } else { setColor(glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); }
When using orthographic (parallel) projection, the point of view is not (0, 0, 0), (not in view space and of course not in world space). You have to create a ray from the near plane (-1) to the far plane (1): glm::vec4 worldPosFar = invVP * glm::vec4(mouseX, -mouseY, 1.0f, 1.0f); glm::vec3 mouseClickVecFar = glm::normalize(glm::vec3(worldPosFar)); glm::vec4 worldPosNear = invVP * glm::vec4(mouseX, -mouseY, -1.0f, 1.0f); glm::vec3 mouseClickVecNear = glm::normalize(glm::vec3(worldPosNear)); if (glm::intersectLineTriangle(mouseClickVecNear, mouseClickVecFar, m_vertices_world[0], m_vertices_world[0], m_vertices_world[0], intersect)) { // [...] }
69,608,300
69,608,382
Why does this char array need to be static?
const char * u8_to_bstr(const uint8_t & u8) { static char s[9]; // space for 8-char string s[8] = 0; // terminate string char * sp = s; for (uint8_t xbit = 0b10000000; xbit > 0; xbit >>= 1) { cout << s << endl; *(sp++) = ((u8 & xbit) == xbit) ? '1' : '0'; } return s; } I encountered this piece of code studying that converts a uint8 to a string representing its binary. My question is, why do we need the static qualifier for static char s[9]? When I remove the static qualifier I get some very strange behavior but I don't understand why.
The function returns s, which is declared on the stack of this function. Were it not static, it would go out of scope, effectively disappear, once the function returns because all the storage on the stack is made available for reuse once a function returns. By making it static, it’s forced to have a persistent address in memory. However, it’s still bad design - if you call this function from multiple threads, they’ll fight with each other for use of the static memory space.
69,608,468
69,687,474
How to force llvm cmake to use only given path to libs?
I try to build llvm on a system where I have no root access. So, I've got some problems: I have been obliged to install gcc, cmake in my $HOME path because system's gcc and cmake are very old and I cannot update them with sudo. I finely installed gcc and cmake and mentioned new paths to PATH env variable. I ran cmake for llvm with this: cmake -S llvm -DCMAKE_BUILD_TYPE=Debug -DBUILD_SHARED_LIBS=ON -DLLVM_TARGETS_TO_BUILD=all -DLLVM_ENABLE_PROJECTS="clang;lld" -DCMAKE_INSTALL_PREFIX=/home/my_user/local -DCMAKE_C_COMPILER=/home/my_user/local/bin/gcc -DCMAKE_LIBRARY_PATH=/home/my_user/local/lib ../llvm It successfully generate make-file. When I run, it throws: ../../../../bin/clang-tblgen: /lib64/libstdc++.so.6: version `CXXABI_1.3.9' not found (required by ../../../../bin/clang-tblgen) ../../../../bin/clang-tblgen: /lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ../../../../bin/clang-tblgen) ... but I've already got convenient libstdc++.so.6 in my /home/my_user/local/lib64 and /home/my_user/local/lib when I installed new gcc but I don't understand how to force cmake or make to consider only these paths instead /lib64. What an option should I pass to cmake or do I need to add some env variable to fix the problem?
I found a solution that worked out for me. Find out what a path contains needed libraries (in my case it is /home/my_user/local/lib64 and then run LD_LIBRARY_PATH=/home/my_user/local/lib64 make!
69,609,113
69,609,158
For loop won't run when comparing length of Vector to a negative number in C++
I have a pair of nested for loops and I am attempting to print the following structure: 0 1 2 3 4 0 - - - - - 1 - - - - - 2 - - - - - 3 - - - - - 4 - - - - - If I attempt to initialize the row counter of the outer loop to -1, and compare it to the length of the vector using .length(), the outer loop simply does not run. I've tested this by putting print statements within the outer loop and they never get executed. My compiler also issues the following warning: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<std::vector<char> >::size_type’ {aka ‘long unsigned int’} [-Wsign-compare] I attempted to change the row counter from an int to a long unsigned int, and while that suppresses the warning message, the loop still won't run. What is the reason for this behavior and how can I resolve it? #include <iostream> #include <string> #include <vector> using namespace std; void print_board(vector<vector<char>> board) { int row, col; cout << " "; for (row = -1; row < board.size(); row++) { if (row > -1) cout << row << " "; for (col = 0; col < board[row].size(); col++) { if (row == -1) cout << col << " "; else cout << board[row][col] << " "; } cout << endl; } } int main() { int max_rows = 5; vector<vector<char>> player_one_board(max_rows, vector<char>(max_rows, '-')); print_board(player_one_board); return 0; }
If all you're doing is printing out the board, you really shouldn't be starting at -1, but 0 instead. That is: std::cout << " "; for (std::size_t col = 0; col < board[0].size(); ++col) { std::cout << col << " "; } std::cout << std::endl; for (std::size_t row = 0; row < board.size(); ++row) { std::cout << row << " "; for (std::size_t col = 0; col < board[row].size(); ++ col) { std::cout << board[row][col] << " "; } std::cout << endl; }
69,609,483
69,611,541
c++ partial template specialization with requires statement: error: out-of-line definition of 'foo' from class Bar<T> without definition
Consider the following code which attempts to implement a partial specialization of class Bar. In the first case, the foo member function is defined inline and in the second case out of line. The out of line definition produces a compile error which I cannot figure out: error: out-of-line definition of 'foo' from class 'Bar<T>' without definition template<class T> struct Bar; template<class T> requires std::is_same_v<T, int> struct Bar<T> { int foo(T a) { return a + 5; } }; template<class T> requires std::is_same_v<T, double> struct Bar<T> { double foo(T a); }; template<class T> requires std::is_same_v<T, double> double Bar<T>::foo(T a) { return a + 5; }; I am using clang-11 with the c++20 compilation option. I am unsure if this is my misunderstanding, a feature or a bug. Any help is appreciated.
Might be clang bug. It was reported at https://bugs.llvm.org/show_bug.cgi?id=50276. Anyway GCC is fine
69,609,675
69,609,719
What does explicit *this object parameter offer in C++23?
In C++23, deducing this is finally added to the standard. Based on what I've read from the proposal, it opens up a new way of creating mixins, and possible to create recursive lambdas. But I'm confused if this parameter creates a "copy" without using templates since there is no reference or does the explicit this parameter have its own rules of value category? Since: struct hello { void func() {} }; may be the equivalent of: struct hello { void func(this hello) {} }; But their type is different because for &hello::func, the first one gives void(hello::*)(), while the second one gives void(*)(hello) For instance, I have this simple function: struct hello { int data; void func(this hello self) { self.data = 22; } }; Doesn't this parameter need to be a reference to change the value of hello type? Or it basically follows the cv-ref qualifier rules of member function as same as before?
Section 4.2.3 of the paper mentions that "by-value this" is explicitly allowed and does what you expect. Section 5.4 gives some examples of when you would want to do this. So in your example, the self parameter is modified and then destroyed. The caller's hello object is never modified. If you want to modify the caller's object, you need to take self by reference: void func(this hello& self) { self.data = 22; }
69,609,778
69,619,946
Using ctypes to call a C++ method with parameters from Python results in "Don't know how to convert parameter" error
I'm trying to use the following C++ class from Python3.7, but can't get the first method 'Set' to work, much less the operator overload methods. I've tried many variations of the Python wrapper and the extern block but I either get the "Don't know how to convert parameter 5" error or a segmentation fault. The examples online and SO answers I've found are too basic or address other issues. Should my argtypes 1st argument be a pointer to the object? I don't know what syntax would be used to indicate that. CMatrix.h: #include <stdio.h> class CMatrix { public: CMatrix(int d1); CMatrix(int d1, int d2); CMatrix(int d1, int d2, int d3); CMatrix (float f1, float f2, float f3); ~CMatrix(); void Set(int x, int y, int z, float f); void operator=(const float f); CMatrix& operator=(const CMatrix &cm); inline float& operator()(const int i) { return m[i];} inline float& operator()(const int i, const int j) { return m[i*s2+j];} inline float& operator()(const int i, const int j, const int k) { return m[i*s23+j*s3+k];} int s1, s2, s3; // dimensions of array int s23; // s2*s3; float *m; // pointer to first element of matrix. int dimensions; // 1, 2, or 3. }; extern "C" { CMatrix* CMatrix_new1(int i) {return new CMatrix(i); } CMatrix* CMatrix_new2(int i, int j) {return new CMatrix(i, j); } CMatrix* CMatrix_new3(int i, int j, int k) {return new CMatrix(i, j, k); } void CMatrix_Set(CMatrix* cm, int x, int y, int z, float f) {cm->Set(x, y, z, f); } } cmWrapper.py: import ctypes as c lib = c.cdll.LoadLibrary('./libCMatrix.o') lib.CMatrix_Set.argtypes = [c.c_int, c.c_int, c.c_int, c.c_float] class CMatrix(object): def __init__(self, i, j, k): if j==0 and k==0: self.obj = lib.CMatrix_new1(i) elif k==0: self.obj = lib.CMatrix_new2(i, j) else: self.obj = lib.CMatrix_new3(i, j, k) def Set(self, x, y, z, f): lib.CMatrix_Set(self.obj, x, y, z, f) cm = CMatrix(2, 3, 0) cm.Set(1, 2, 0, 99.0) The traceback: >>> import cmWrapper Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/.../ctypes/cmWrapper.py", line 18, in <module> cm.Set(1, 2, 0, 99.0) File "/.../ctypes/cmWrapper.py", line 15, in Set lib.CMatrix_Set(self.obj, x, y, z, f) ctypes.ArgumentError: argument 5: <class 'TypeError'>: Don't know how to convert parameter 5 If it matters, I compiled the C++ code using: g++ -c -fPIC CMatrix.cpp -o CMatrix.o g++ -shared -Wl -o libCMatrix.o CMatrix.o This is on a Mac running 10.15.7. From lldb: Executable module set to "/Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python". Architecture set to: x86_64h-apple-macosx-. (lldb) There is a running process, detach from it and attach?: [Y/n] n (lldb) thread list Process 57460 stopped * thread #1: tid = 0x47364c, 0x00007fff202f5656 libsystem_kernel.dylib`__select + 10, queue = 'com.apple.main-thread', stop reason = signal SIGSTOP (lldb) thread continue Resuming thread 0x47364c in process 57460 Process 57460 resuming Process 57460 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x13835f20) frame #0: 0x00000001015f19b2 libCMatrix.o`CMatrix::Set(int, int, int, float) + 34 libCMatrix.o`CMatrix::Set: -> 0x1015f19b2 <+34>: movl (%rax), %esi 0x1015f19b4 <+36>: movl 0x4(%rax), %edx 0x1015f19b7 <+39>: movl 0x8(%rax), %ecx 0x1015f19ba <+42>: movl 0xc(%rax), %r8d Target 0: (Python) stopped.
You have to match the arguments exactly. Set the .argtypes and .restype of every function you use so ctypes can properly marshal the parameters to C and back again. If you do not set .restype ctypes assumes the return value is c_int (typically a signed 32-bit integer) instead of a (possibly 64-bit) pointer. Here's a working example. I didn't flesh out every function because one should be sufficient. Tested on both 32- and 64-bit Python. test.cpp (built with MS compiler, cl /LD /EHsc /W4 test.cpp): #include <stdio.h> // Needed to export functions on Windows #ifdef _WIN32 # define API __declspec(dllexport) #else # define API #endif class CMatrix { public: CMatrix(int d1) : s1(d1) { m = new float[d1]; } ~CMatrix() { delete [] m; } const float* Get(int& s) { s = s1; return m; } void Set(int x, float f) { m[x] = f; } int s1; float *m; }; extern "C" { API CMatrix* CMatrix_new(int i) {return new CMatrix(i); } API const float* CMatrix_Get(CMatrix* cm, int& x) { return cm->Get(x); } API void CMatrix_Set(CMatrix* cm, int x, float f) { cm->Set(x, f); } API void CMatrix_delete(CMatrix* cm) { delete cm; } } test.py import ctypes as ct # For type checking the returned pointer. class _CMatrix(ct.c_void_p) : pass PCMatrix = ct.POINTER(_CMatrix) class CMatrix: _dll = ct.CDLL('./test') _dll.CMatrix_new.argtypes = ct.c_int, _dll.CMatrix_new.restype = PCMatrix _dll.CMatrix_Get.argtypes = PCMatrix, ct.POINTER(ct.c_int) _dll.CMatrix_Get.restype = ct.POINTER(ct.c_float) _dll.CMatrix_Set.argtypes = PCMatrix, ct.c_int, ct.c_float _dll.CMatrix_Set.restype = None _dll.CMatrix_delete.argtypes = PCMatrix, _dll.CMatrix_delete.restype = None def __init__(self, i): self.obj = self._dll.CMatrix_new(i) def Set(self, x, f): self._dll.CMatrix_Set(self.obj, x, f) def Get(self): size = ct.c_int() m = self._dll.CMatrix_Get(self.obj, ct.byref(size)) return m[:size.value] def __del__(self): self._dll.CMatrix_delete(self.obj) cm = CMatrix(2) cm.Set(0, 1.5) cm.Set(1, 2.5) print(cm.Get()) Output: [1.5, 2.5]
69,610,000
69,610,043
Why does the compiler not recognize Node as a type? It is a private class within AVLTree
class AVLTree{ struct Node { K key; V value; Node* left; Node* right; int height; /** * Node constructor; sets children to point to `NULL`. * @param newKey The object to use as a key * @param newValue The templated data element that the constructed * node will hold. */ Node(const K& newKey, const V& newValue) : key(newKey), value(newValue), left(NULL), right(NULL), height(0) { } }; ============================================================== Node* AVLTree::findParent(Node *&current, Node *& child ) { if (current == NULL) { return NULL; } if (current->right == child || current->left == child) { return current; } else { findParent(current->right, child); findParent(current->left, child); } } Trying to write a function that finds the parent of a node in an AVL Tree so I can use it in the rotation functions. However whenever I try and compile I get this error: tests/../avltree.cpp:72:1: fatal error: unknown type name 'Node' Node* AVLTree::findParent(Node *&current, Node *& child ) { Why is this happening? Find parent is in avltree.cpp and is listed as a private member in the AVLTree class, so what's the issue? I also tried doing AVLTree::Node, but then got this error: AVLTree::Node* AVLTree::findParent(Node *&current, Node *& child ) { ^ tests/../avltree.h:20:7: note: 'AVLTree' declared here class AVLTree
The basic issue is that the return type is parsed in the global scope, and not in the scope of the method (due to the fact that it is before the method name and its scope specifier). So you need to explicitly scope it: AVLTree::Node* AVLTree::findParent(Node *&current, Node *& child ) {
69,610,082
69,610,741
How do I get accurate outputs when reading large amounts of data from a file?
I'm trying to use a for loop to read 100,000 int values from a file. I also want to add them up, find a min, and find a max. My code right now only reads correctly if I change the number of read values from 100,000 down to just 100. Even at 200 values, my code just skips data and doesn't give correct outputs. Can anyone see where my code could go wrong when reading for larger amounts of values? Thank You! #include <cmath> #include <iostream> #include <iomanip> #include <fstream> using namespace std; int main() { int number; int sum; int big, small = 0; string file; cout << "Enter a file name: "; cin >> file; ifstream inFile(file); for (long i = 0; i < 100000; i++) { if (!(inFile >> number)) { cout << "ERROR!"; return 1; } } for (long i = 0; i < 100000; i++) { inFile >> number; sum = sum + number; if (number < small) { small = number; } if (number > big) { big = number; } } cout << sum << endl; cout << big << endl; cout << small << endl; return 0; } Also, my input file is arranged like this 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 ... ... ... of course with other numbers
As others have stated, your 1st loop is reading and discarding integers, and then your 2nd loop picks up where the 1st loop left off, rather than starting at the beginning of the file again. You should be using only 1 loop. You are also not initializing your sum and big variables before entering the loop that increments them. Try something more like this instead: #include <iostream> #include <fstream> using namespace std; int main() { int number, sum, big, small; string file; cout << "Enter a file name: "; cin >> file; ifstream inFile(file); if (!(inFile >> number)) { cout << "ERROR!"; return 1; } sum = small = big = number; for (int i = 1; i < 100000; ++i) { if (!(inFile >> number)) { cout << "ERROR!"; return 1; } sum += number; if (number < small) { small = number; } if (number > big) { big = number; } } cout << sum << endl; cout << big << endl; cout << small << endl; return 0; }
69,610,608
69,611,460
windows mingw32-make "no such file" error when installing opencv
I've been trying to build OpenCV-4.5.1 from source with CMake 3.22.0-rc1. When execute "mingw32-make", this problem below showed up. I guess something went wrong with the CMakeList but I'm not sure. I found that there's no such file named "thread.c.obj", so I tried to compile thread.c with gcc, but some reference errors occured (I'll post screenshots or copy/paste the errors in the comment zone if needed) this is the description of the error: D:\Code\opencv\sources\build>mingw32-make [ 0%] Built target opencv_highgui_plugins [ 0%] Building C object 3rdparty/openjpeg/openjp2/CMakeFiles/libopenjp2.dir/thread.c.obj process_begin: CreateProcess(C:\Users\12271\AppData\Local\Temp\make6172-1.bat, C:\Users\12271\AppData\Local\Temp\make6172-1.bat, ...) failed. make (e=2): 系统找不到指定的文件。//which means there's no such file mingw32-make[2]: *** [3rdparty\openjpeg\openjp2\CMakeFiles\libopenjp2.dir\build.make:76: 3rdparty/openjpeg/openjp2/CMakeFiles/libopenjp2.dir/thread.c.obj] Error 2 mingw32-make[1]: *** [CMakeFiles\Makefile2:1650: 3rdparty/openjpeg/openjp2/CMakeFiles/libopenjp2.dir/all] Error 2 mingw32-make: *** [Makefile:165: all] Error 2 It's my first time to ask question in this forum, and I'm not familiar with the question format, if there is something inappropriate please tell me. Thanks!
The error you get is from mingw32-make trying to run .bat files, which can't be be run by CreateProcess (which is internally used to execute programs), as it requires something like CMD /C to run. You could try using CMake flag -GNinja in combination with Ninja as build tool. This is also a lot faster. Another solution would be to have all the third party prerequisites available when building, so CMake doesn't have to build everything from the 3rdparty folder. Or you could switch from Command Prompt to MSYS2 shell. As it behaves very much like a Linux/Unix prompt chances are much better libraries will build right away (as this completely avoids calling .bat files).
69,610,798
69,610,934
How to retain filesystem path while converting to string?
#include <iostream> #include <filesystem> namespace fs = std::filesystem; using namespace std; int main() { fs::path p = fs::current_path(); cout << p << endl; string p_string = p.string(); cout << p_string << endl; return 0; } When printing out 'p' the path is shown as this. "C:\\Users\\tp\\source\\repos\\test" But after the conversion to a string it comes out like this. C:\Users\tp\source\repos\test Is there a way I could retain the original form of the path?
From cppreference's page on operator<<(std::filesystem::path): Performs stream input or output on the path p. std::quoted is used so that spaces do not cause truncation when later read by stream input operator. So we'll get the same string by manually calling std::quoted: #include <iostream> #include <iomanip> #include <filesystem> namespace fs = std::filesystem; using namespace std; int main() { fs::path p = fs::current_path(); // Should be same cout << p << endl; cout << std::quoted(p.string()); return 0; }
69,611,248
69,611,277
What does someone mean when they write something to "gobble a newline"? C++
I am currently learning how to write a code that prompts the user to define how many players and rounds they want in a dice game, with the additional goal to output the results of both into a file. A couple of resources I have seen have suggested when defining the string variable, you want a secondary string for the sole purpose to "gobble newlines." Here is the snippet of the code I was looking at: int main() { int nPlayers, nRounds, score; **string name, dummy;** cout <<"Enter number of players: "; cin >> nPlayers; cout << "Enter number of rounds: "; cin >> nRounds; **getline (cin, dummy); // gobble up newline** ofstream ofs ("scores.txt"); ofs << nPlayers << " " << nRounds << endl; My question is based around the two lines denoted with double asterisks. Why the need to write a string like this?
Many input streams have extra newline characters between inputs. "Gobble up a newline" is to get rid of those to get the correct output. For example: 5 //number of inputs //empty newline character 89 //first input value ... The dummy variable is used to store it since it is not of much use to store a newline character.
69,611,558
69,612,249
How does *node copy *next?
I understand how linked lists work but this particular code is tough to grasp for me. Its this leetcode problem (basically we are given address of a node which is to be deleted) whose solution can be implemented like the code snippet below: 1. class Solution { 2. public: 3. void deleteNode(ListNode* node) { 4. ListNode* next = node->next; 5. *node = *next; 6. delete next; 7. } 8. }; I know that: &node would mean the address of node variable node means the value (information) stored at address called node *node is used to dereference the pointer variable called node. My doubt: [IMP] If we need to dereference a node pointer to get its data (like in line 5), then why not do so while accessing its member elements too (in line 4 node->next)? [Not IMP] Then, how does *node copies *next's data?
node->next is actually equivalent to (*node).next. So there's an implicit dereference there already. As for the copying, I assume you understand assignment between e.g. plain int variables? As in: int a = 5; int b = 10; a = b; It's quite natural that the value of b will be copied into a. Now lets do the same again, but with one pointer to b: int a = 5; int b = 10; int* pb = &b; // pb is pointing to b a = *pb; This is really doing exactly the same as a = b. And another example with a pointer to a instead: int a = 5; int b = 10; int* pa = &a; // pa is pointing to a *pa = b; Again this is the same as a = b. Now putting them together: int a = 5; int b = 10; int* pa = &a; // pa is pointing to a int* pb = &b; // pb is pointing to b *pa = *pb; It's still the same as a = b. It doesn't really matter if the pointers are to plain int variables or values, or to structures, it works the same for all pointers.
69,611,696
69,611,882
hHow to fill remaining places with zeros?
#include <bits/stdc++.h> using namespace std; int main() { array<vector<int>,10>arr1; arr1[0].push_back(1); arr1[0].push_back(2); arr1[0].push_back(3); arr1[1].push_back(4); arr1[1].push_back(5); arr1[2].push_back(6); arr1[7].push_back(100); for(auto i:arr1) { for(auto j :i) cout<<j<<" ";cout<<"\n"; } } I'm creating array of vectors and pushing some values and I can't figure out how to make remaining places zeros. I have an idea , first making all vectors inside each array inside to hold zeros of size 10. and instead of using push_back , I will use at(). But I need code to make vectors inside array zeros for size 10. output : 1 2 3 4 5 6 100 Q2) what is difference between array<vector<int>,10>arr; and vector<int> arr[10];
You can do: array<std::vector<int>,10>arr1; for ( auto& vec : arr1 ) vec = std::vector<int>(10, 0); To fill all the vectors with 0s by default. But, you can no longer do push_back as it will insert at the 11th position. Second question: They are both equivalent ( static arrays holding pointers to dynamic arrays) . array<vector<int>,10>arr is probably the better way, since it allows you to use the range-loop and other STL-algorithms.
69,611,697
69,611,811
Divide without divide c++
There is a problem I am supposed to solve that is normally easy, but it has a catch. There are 2 types of candy. One type weighs m1 kg and is sold for s1 Euro. A second type weighs m2 kg and is sold for s2 Euro. All numbers are integers. The question is, which type of candy costs more per kg? The catch is, you can't use divide operation at all, neither / nor %. For example, if we have the numbers as m1=2, s1=17, m2=3, and s2=14 then the answer needs to be that the first candies are more expensive as 17/2=8.5 and 14/3=4.(3). As I am a C++ student, I am restricted to use only that which has been taught so far in the class to determine the more expensive candy. The only thing we learned so far was + - / * % and if statement with else. Also == > < && ||.
Compare X ≡ s1 * m2 with Y ≡ s2 * m1. If X > Y, then s1 / m1 > s2 / m2. No division is required to do the comparison. The caveat to this solution is that s1, s2, m1, and m2 should all have the same sign, and m1 and m2 should be non-zero. Let's assume all the values are positive integers (hence, greater than 0). Consequently m1 * m2 is positive as well. Let z be the number such that: z + (s1 / m1) = s2 / m2 By multiplying by m1 * m2 on both sides, we get: z' + (s1 * m2) = s2 * m1 ∵ z' ≡ z × (m1 * m2) Since z and z' have the same sign, the relational order of s1 / m1 and s1 / m2 is the same as the relational order of s1 * m2 and s2 * m1.
69,611,945
69,613,196
C++ template argument deduction for pointers to overloaded member function
I'm currently working on a template function that deals with pointers to member functions. It originally looked like this: template <typename C, typename RT, typename... P> auto CreateTestSuite(RT(C::* pFunc)(P...)) {...} However, I soon found that if I try to pass to it a pointer to a const member function, the template will not recognize this. So I then added this overloaded version: template <typename C, typename RT, typename... P> auto CreateTestSuite(RT(C::* pFunc)(P...) const) {...} For two different member functions with const and non-const respectively, it works fine. However, if I try to call CreateTestSuite for a pointer to an overloaded member function, a problem arises. For example, assume I have the following class A: class A { public: return_type test(...) {...} return_type test(...) const {...} }; And now when I try to make the function call CreateTestSuite(&A::test); The compiler will not be able to tell which overloaded version I am using. In addition, this problem cannot be solved by explicitly specifying the template arguments, because they are the same for the overloaded versions of CreateTestSuite. How do I explicitly select from the two versions? Edit: I can accept minor modification to CreateTestSuite. Many thanks.
As your issue is just to select the right overload, you might write helpers: template <typename C, typename RT, typename... P> constexpr auto non_const_overload(RT (C::*pFunc)(P...)) { return pFunc; } template <typename C, typename RT, typename... P> constexpr auto const_overload(RT (C::*pFunc)(P...) const) { return pFunc; } With usage CreateTestSuite(non_const_overload(&A::test)); CreateTestSuite(const_overload(&A::test)); Demo Note: You might need 24 helpers to handle all combinations with volatile, reference to this and C-ellipsis. or MACRO (with c++20 lambda immediate-called): #define OVERLOAD(name, /*qualifiers*/...) []<typename C, typename RT, typename... P>(RT (C::*pFunc)(P...) __VA_ARGS__){ return pFunc; }(name) CreateTestSuite(OVERLOAD(&A::test)); /*no const*/ CreateTestSuite(OVERLOAD(&A::test,)); /*no const*/ CreateTestSuite(OVERLOAD(&A::test, const)); Demo
69,612,041
73,302,460
Simple and easy way to move visual studio vcxproj files from one folder to another
So I have a bunch of vcxproj files under the following folder E:. ├───vddproject │ └───scrproj │ └───pjrdir │ └───winsix │ └───Arithmetic.vcxproj There are bunch of vcxproj under winsix, I have taken one example here. The files for Arthmetic.vcxproj are stored under E:. ├───vddproject │ └───scrproj │ └───mediadir │ └───Idexter │ ├───create.cpp │ ├───update.cpp │ ├───read.cpp │ ├───delete.cpp The vcxpproj file is present under the solution file math.sln E:. ├───vddproject │ └───scrproj │ └───mediadir │ └───Idexter2 │ └───math.sln the content of sln file being Project("{506CAAF2-81A4-4731-B667-24899A39FC25}") = "Arithmetic", "..\..\pjrdir\winsix\Arithmetic.vcxproj", "{DCB15F39-4E20-439D-A949-368B48CF261E}" EndProject Now I need the smart and simple solution to move my vcxproj from its current folder to another folder Arithmetic with structure as E:. ├───vddproject │ └───scrproj │ └───mediadir │ └───Idexter │ └───Arithmetic How can I do this without me manually editing the vcproj, vcxproj.users, vcxproj.filters files
Here is what you need to do. Remove the project Arithmetic from the sln Math from the solution explorer. Move the following files from winsix to your folder Idexter->Arithmetic Note : You don't need to move Arithmetic.vcxproj.user files as these are automatically created. Arithmetic.vcxproj Arithmetic.vcxproj.filters Move any rc2 or rc files. Check for Arithmetic*.rc and Arithmetic.rc2 files. Edit the Arithmetic.vcxproj file These are some basic tags for which you need to edit the corresponding path, there might be more, please confirm the same ImportGroup PropertyGroup IntDir and OutDir AdditionalIncludeDirectories AdditionalDependencies(check if you have any relative paths here) AdditionalLibraryDirectories AdditionalIncludeDirectories ItemGroup : This contains the relative path to your actual source file Edit the Arithmetic.vcxproj.filters file Check for any relative path here that needs to be edited. Basic tags being ItemGroup. Now add the vcxproj file to the solution by right clicking on the solution name : Add existing project. Your solution file will also be updated in the process, no need to make any changes here
69,613,009
69,616,999
Is a float member guaranteed to be zero initialized with {} syntax?
In C++17, consider a case where S is a struct with a deleted default constructor and a float member, when S is initialized with empty braces, is the float member guaranteed by the standard to be zero-initialized? struct A { int x{}; }; struct S { S() = delete; A a; float b; }; int main() { auto s = S{}; // Is s.b guaranteed to be zero? } In my opinion, cppreference.com is not clear, saying both that: If the number of initializer clauses is less than the number of members and basesor initializer list is completely empty, the remaining members and bases (since C++17) are initialized by their default member initializers, if provided in the class definition, and otherwise (since C++14) copy-initialized from empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates). If a member of a reference type is one of these remaining members, the program is ill-formed. (from here), which implies that b is guaranteed to be zero In all cases, if the empty pair of braces {} is used and T is an aggregate type, aggregate-initialization is performed instead of value-initialization. (from here) which implies that b is not guaranteed to be zero. There is also a discussion that seems to imply that while not guaranteed, all known compiler zero-initialize anyway: The standard specifies that zero-initialization is not performed when the class has a user-provided or deleted default constructor, even if that default constructor is not selected by overload resolution. All known compilers performs additional zero-initialization if a non-deleted defaulted default constructor is selected. Related to Why does aggregate initialization not work anymore since C++20 if a constructor is explicitly defaulted or deleted?
Because S is an aggregate, S{} will perform aggregate initialization. The rule in the standard about how members are initialized when there are no initializers in the list is basically what you cited: If the element has a default member initializer ([class.mem]), the element is initialized from that initializer. Otherwise, if the element is not a reference, the element is copy-initialized from an empty initializer list ([dcl.init.list]). So for b, that's the equivalent of float b = {};. Per the rules of list initialization, we have to get all the way down to 3.10: Otherwise, if the initializer list has no elements, the object is value-initialized. And value initialization will initialize a float to 0.
69,613,399
69,613,553
Does the compiler really optimize to make these two functions the same assembly?
I plugged this into Godbolt and was pleasantly surprised that these two function calls a() and b() are equivalent under anything other than -O0 (using most major compilers): #include <cmath> struct A { int a,b,c; float bar() { return sqrt(a + b + c); } }; struct B { int a[3]; float bar() { int ret{0}; for (int i = 0; i<3; ++i) { ret += a[i]; } return sqrt(ret); } }; float a() { A a{55,67,12}; return a.bar(); } float b() { B b{55,67,12}; return b.bar(); } The Godbolt output is: a(): movss xmm0, DWORD PTR .LC0[rip] ret b(): movss xmm0, DWORD PTR .LC0[rip] ret .LC0: .long 1094268577 I am no assembly expert, but I'm wondering if this could actually be true, that they are doing identical work. I can't even see where in this assembly there is a call to a sqrt, or what that long "constant" (?) is doing in there.
This function: float a() { A a{55,67,12}; return a.bar(); } Has exactly the same observable behavior as this one: float a() { return sqrt(55+67+12); } The same is true for b(). Further, sqrt(55+67+12) == sqrt(134) == 11.5758369028. Binary representation of the IEEE-754 floating point value 11.5758369028 is 01000001001110010011011010100001. And that binary as integer is 1094268577. The compiler applied the so-called as if rule to replace both functions with assembly that has the exact same observable behavior as the original code: Both functions return a float with value 11.5758369028.
69,613,809
69,614,033
how can i show Gaussian cube file with vtk?
I have a file with .cube format. I want show it with vtk as such as this image. how can i show this file with C++ vtk?
I stop working with VTK some years ago, but I think you're searching for a Gaussian Cube file reader. Some research leads here: https://vtk.org/doc/nightly/html/annotated.html In the provided link, you can find some official examples, in particular there are two classes that I think could help you: vtkGaussianCubeReader2.h: Read a Gaussian Cube file and output a vtkMolecule object and a vtkImageData vtkGaussianCubeReader.h: Read ASCII Gaussian Cube Data files Hope these can help.
69,613,884
69,613,957
c++ char array returns some strange value
After inserting values in dynamic char array, trying to get first value from the top. Method gives me back ² value. Can you help me with understanding, what I am doing wrong? Here is main method: char* arr = new char[5](); arr[0] = 'h'; arr[1] = 'e'; arr[2] = 'l'; arr[3] = 'l'; char result = topValue(arr, 5); cout << result; Here is topValue() method: char topValue(char* stackArr, int stackSize) { for (int i = stackSize; i >= 0; i--) { std::cout << "In top: " << stackArr[i] << std::endl; if (stackArr[i] != '\0') { return stackArr[i]; } } }
In the first iteration of the loop, you access the array outside of its bounds, and the behaviour of the program is undefined. Note that your function doesn't handle the potential case where all elements are the null terminator character. In such case the function would end without returning a value and the behaviour of the program would be undefined. Either handle that case, or carefully document the pre-condition of the function. Furthermore, the program leaks memory. I recommend avoiding the use of bare owning pointers. After inserting values in dynamic char array ... You aren't inserting values into an array. It isn't possible to insert values into an array. The number of elements in an array is constant.
69,614,109
69,619,614
Why does C++23 string::resize_and_overwrite invoke operation as an rvalue?
In order to improve the performance of writing data into std::string, C++23 specially introduced resize_and_overwrite() for std::string. In [string.capacity], the standard describes it as follows: template<class Operation> constexpr void resize_and_overwrite(size_type n, Operation op); Let — o = size() before the call to resize_and_overwrite. — k be min(o, n). — p be a charT*, such that the range [p, p + n] is valid and this->compare(0, k, p, k) == 0 is true before the call. The values in the range [p + k, p + n] may be indeterminate [basic.indet]. — OP be the expresion std::move(op)(p, n). — r = OP. [...] Effects: Evaluates OP, replaces the contents of *this with [p, p + r), and invalidates all pointers and references to the range [p, p + n]. But I found out that this function will use std::move to convert op into an rvalue before invoking it, which means that we cannot pass in a callable that only has lvalue overloaded operator() (demo): #include <string> int main() { struct Op { int operator()(char*, int) &; int operator()(char*, int) && = delete; } op; std::string s; s.resize_and_overwrite(42, op); // ill-formed } This behavior seems a bit strange, but since this change was made in the last edition of the paper, it is obviously intentional. So, what are the considerations behind this? Is there any benefit in the mandate that op must be invoked as an rvalue?
op is only called once before it is destroyed, so calling it as an rvalue permits any && overload on it to reuse any resources it might hold. The callable object is morally an xvalue - it is "expiring" because it is destroyed immediately after the call. If you specifically designed your callable to only support calling as lvalues, then the library is happy to oblige by preventing this from working.
69,614,204
69,614,290
Why is lambda not converted to function in this case?
I'm writing code with parameter packs and std::function. The goal is to be able to pass a function and a pack of parameters into a function, and be able to call the function of that pack (and do some other work). Here is the stripped down example of what I want: #include <functional> #include <iostream> template<typename... Args> using MyFunc = std::function< void(Args...) >; template<typename... Args> void call(MyFunc<Args...> f, Args... args) { f(args...); } int main() { auto lambda = [](int a, double b) {std::cout << a << b << std::endl;}; call<int, double>(lambda, 1, 2.0); // but this works? //call(MyFunc<int, double>(lambda), 1, 2.0); return 0; } When I compile this with clang 13.0 I get: could not match 'function<void (int, double, type-parameter-0-0...)>' against '(lambda at pack.cpp:13:19)'. For g++ 7.5 I get a similar: ‘main()::<lambda(int, double)>’ is not derived from ‘std::function<void(Args ...)>’. As you can see, I commented an example that works: explicitly converting the argument to std::function. But why can't it do it implicitly? P.S. I can't use a templated F instead of std::function for a reason that is out of scope of this simple example.
The problem is template argument deduction for Args on the 1st function parameter f fails since implicit conversion (from lambda to std::function) won't be considered in the deduction. You can use std::type_identity (since C++20; it's quite easy to write one for pre-C++20) to exclude f from deduction. E.g. template<typename... Args> void call(std::type_identity_t<MyFunc<Args...>> f, Args... args) { f(args...); } BTW even template arguments are specified template argument deduction is still performed to determine the end of parameter pack. And in this case you don't need specify them, you can just call it as call(lambda, 1, 2.0);.
69,614,345
69,614,454
Child constructor uses grandparent constructor
I have the following class hierarchy with a virtual GrandParent and non-virtual Parent and Child: class GrandParent { protected: explicit GrandParent(const float &max_dur); virtual ~GrandParent() {} private: const float _max_dur; }; class Parent : public virtual GrandParent { public: explicit Parent(const float &max_dur = 0); }; class Child : public Parent { public: explicit Child(const float &max_dur = 0); }; Their constructors are nested like so: // GrandParent constructor GrandParent::GrandParent(const float &max_dur) : _max_dur{max_dur} {} // Use GrandParent constructor Parent::Parent(const float &max_dur) : GrandParent{max_dur} {} // Use Parent constructor Child::Child(const float &max_dur) : Parent{max_dur} {} // <- error occurs here When I build, I get the following error message: error: no matching function for call to ‘GrandParent::GrandParent()’ Codesnippet here. It seems as if the Child constructor is ignored and it jumps to GrandParent instead. Modifying the Child constructor to directly call the GrandParent constructor (thus skipping a generation), I can bypass the error but it seems like the wrong approach. Thanks in advance for your help! Solution Fixed by following 463035818-is-not-a-number's answer to call the GrandParent's constructor explicitly and 康桓瑋's suggestion in order to call the Parent's constructor as well: Child::Child(const float &max_dur) : GrandParent{max_dur}, Parent{max_dur} {}
From the faq: What special considerations do I need to know about when I inherit from a class that uses virtual inheritance? Initialization list of most-derived-class’s ctor directly invokes the virtual base class’s ctor. Because a virtual base class subobject occurs only once in an instance, there are special rules to make sure the virtual base class’s constructor and destructor get called exactly once per instance. The C++ rules say that virtual base classes are constructed before all non-virtual base classes. The thing you as a programmer need to know is this: constructors for virtual base classes anywhere in your class’s inheritance hierarchy are called by the “most derived” class’s constructor. The constructor of Child calls the constructor of GrandParent directly, because GrandParent is a virtual base. And because you did not call it explicitly, the default constuctor is called, but GrandParent has no default constructor. Modifying the Child constructor to directly call the GrandParent constructor (thus skipping a generation), I can bypass the error but it seems like the wrong approach. This is exactly the right approach. Childs constructor does call GrandParents constructor, you cannot do anything about that when GrandParent is a virtual base and Child is the most-derived-class. What you can do is: Choose the right constructor instead of letting the compiler try to call the non-existent default constructor.
69,614,745
69,614,887
Access to derived class members through a base class reference
considere a simle class stDeriv which inherits from stBase. I'am surprised to see that we cannot access to the stDeriv class members through a stBase reference. Below the basic example to illustrate my point : #include <fstream> // std::ifstream #include <iostream> // std::cout using namespace std; typedef struct stBase { public: virtual ~stBase() { ; } stBase(int iB) { iB_ = iB; } // Copy operator stBase &operator=(const stBase &src) { iB_ = src.iB_; return *this; } virtual void Hello() { cout << " Hello from stBase" << endl; } private: int iB_ = 0; } stBase; typedef struct stDeriv : public stBase { public: int iD_ = 0; stDeriv(int iB) : stBase(iB), iD_(0) { ; } virtual void Hello() { cout << " Hello from stDeriv" << endl; } // Copy operator stDeriv &operator=(const stDeriv &src) { iD_ = src.iD_; return *this; } } stDeriv; int main(int, char *[]) { int iErr = 0; stBase aBase(0); stDeriv aDeriv(1); stDeriv &rDeriv = aDeriv; stBase &rBase = aBase; rBase.Hello(); // OK result : "Hello from stBase" rDeriv.Hello(); // OK result : "Hello from stDeriv" rBase = rDeriv; // KO!!! Cannot access to aDeriv.iD_ through rBase !!! rBase.Hello(); // KO!!! result : "Hello from stBase" !!! return iErr; } Why do I fail to access to stDeriv::iD_ through rBase after "rBase = rDeriv;" ?
You cannot rebind references like you do. rBase already has a value and cannot be assigned to again. why doesn't C++ allow rebinding a reference? So just make a new reference: int main(int, char* []) { int iErr = 0; stBase aBase(0); stDeriv aDeriv(1); stDeriv& rDeriv = aDeriv; stBase& rBase = aBase; rBase.Hello(); // OK result : "Hello from stBase" rDeriv.Hello(); // OK result : "Hello from stDeriv" // Make a new reference and all is fine stBase& rBase2 = rDeriv; rBase2.Hello(); // OK result : "Hello from stDeriv" return iErr; }
69,614,880
69,615,425
Is there any way that data can be inherited from one class to another?
I am trying to learn object oriented programming, and I got stuck at a problem. I have two class A and B. I am passing command line argument into class A, which then performs some computations and forms a 2d vector. (lets call the vector data) I want class B to inherit class A. So I was wondering is there any way, in which when default constructor of class B is called and it prints the contents of 2d vector data. Sample code of what I have tried class A { public: vector<vector<string>>data; fstream file; string word, filename; A() { } A(string fileOpen) { file.open(fileOpen); while (file >> word) { vector<string>rowTemp={word}; data.push_back(rowTemp); } } vector<vector<string>> getVector() { return data; } }; class B:A { public: B() { for(auto i:data) { for(auto j:i) { cout<<j<<' '; } cout<<endl; } } }; int main(int argc, char* argv[]){ fstream file; string word, filename; file.open(argv[1]); string fileOpen=argv[1]; A s(fileOpen); B c; return 0; } I basically want class B to have access 2d vector data so that I can perform further computations on it, while logic of computation remains inside class B. Is there a way to do this? Also, as you can see inside class A the default constructor is empty. But it is needed because without it, I received an error that default constructor of class B cannot be called. Is there a better way to write this? As having an empty default constructor looks bad.
You seem to misunderstand how inheritance works, it is just not clear what you expected. The thing is: Members of a base class are always inherited. Their access can be limited, but they are still there. Consider this simplified example: #include <iostream> class A { public: int data = 42; A() = default; A(int value) : data(value) {} int getData() { return data; } }; class B : A { public: B() { std::cout << A::data; // ok std::cout << A::getData(); // ok } }; int main(){ B c; //std::cout << c.data; // error: data is private! } Output is: 4242 Because B does inherit the data member from A. Inside B you can access data either directly or via getData because both are public in A. However, because B inherits privately from A (thats the default inheritance for classes defined via class) you cannot directly access either data nor getData in main. Furtermore, when you write: A s(fileOpen); B c; Then s and c are two completely unrelated objects. I suppose you rather want: B c{fileOpen}; and call As constructor from the constructor of B: B(const std::string& filename) : A(filename) { // now you can access A::data // which has been initialized in // constructor of A }
69,615,670
69,618,642
Convert numbers into letters and multiply the number by itself
Sample Input #2 8 5 12 12 15 23 15 18 12 4 Sample Output #2 helloworld 8:8-16-24-32-40-48-56-64 5:5-10-15-20-25 12:12-24-36-48-60-72-84-96-108-120-132-144 12:12-24-36-48-60-72-84-96-108-120-132-144 15:15-30-45-60-75-90-105-120-135-150-165-180-195-210-225 23:23-46-69-92-115-138-161-184-207-230-253-276-299-322-345-368-391-414-437-460-483-506-529 15:15-30-45-60-75-90-105-120-135-150-165-180-195-210-225 18:18-36-54-72-90-108-126-144-162-180-198-216-234-252-270-288-306-324 12:12-24-36-48-60-72-84-96-108-120-132-144 4:4-8-12-16 #include <iostream> #include <iomanip> using namespace std; char secretCode(char number) { if(number >= 1 && number <= 26) { return static_cast<char>('a' - 1 + number); } else if (number >= 27 && number <= 52) { return static_cast<char>('a' - 27 + number); } else if (number >= 53 && number <= 104) { return static_cast<char>('a' - 53 + number); } } void printSequence(int number[10]) { for (int i = 0; i < 10; i++) { cout << secretCode(number[i]); } } int main() { int number[10]; for (int x = 0; x < 10; ++x) { cin >> number[x]; printSequence(number); for (int y = number[x]; y <= number[x]; ++y) { for (int z = 1; z <= number[x]; ++z) { if (z > 1) { cout << "-"; } if (z < 1) { cout << number[x] * -1; } else cout << number[x] * z ; } } } } I think I got the answer but I'm doing something wrong in my code, I'm pretty new to programming still and have been doing fine so far till I encounter the loop and functions..
#include<iostream> #include<iomanip> #include <iterator> using namespace std; char secretCode(char number) { if(number >= 1 && number <= 26) { return static_cast<char>('a' - 1 + number); } else if (number >= 27 && number <= 52) { return static_cast<char>('a' - 27 + number); } else if (number >= 53 && number <= 104) { return static_cast<char>('a' - 53 + number); } } void printSequence(int number[10]) { for (int i=0; i<10; i++) { cout << secretCode(number[i]); } cout << endl; int len = 0; while(len < 10){ cout << number[len] << ":"; for(int z=1; z<=number[len]; ++z){ if (z>1) { cout << "-"; } if (z<1) { cout <<number[len]; } else cout << number[len]*z ; } cout << endl; len += 1; } } int main() { int number[10]; for(int x=0; x<10; ++x) { cin >> number[x]; } printSequence(number); }
69,615,772
69,615,866
Make extern variable can't be accessed in specific files
So I have: foo.h #ifndef FOO_H #define FOO_H extern int bar; void change_bar_value(const int& value); #endif foo.cpp #include "foo.h" int bar = 10; void change_bar_value(const int& value) { bar = value; } and main.cpp #include "foo.h" int main() { bar = 20; change_bar_value(20); } So I want that you can't direcly change bar in main.cpp, but you can call a function that changes the value of bar. So how can I do it?
"Don't make it extern" is the obvious answer, and the generally preferrable solution. If you desparately want something is globally readable but not writeable, alias it with a const reference. (And don't pass primitives by const reference - it is a pointless pessimization.) foo.h: extern const int& bar; void change_bar_value(int value); foo.cpp: static int local_bar; const int& bar = local_bar; void change_bar_value(int value) { local_bar = value; }
69,616,001
71,200,363
Input C++ Vector into C function
I have a std::vector<float> containing sound data. Without copying its data, I'd like to use this vector as input to the sonicChangeFloatSpeed function of the Sonic library. This method expects a float* as first argument and mutates the input array. After completion, the pointer in first argument would point to the result data. data gives me access to the internal array of a C++ vector and with assign, I can replace the vector's contents. Hence, I tried the following: float* ptr = vec.data(); int num_samples = sonicChangeFloatSpeed(ptr, vec.size(), 1., 1.5, 1., 1., 0, 41000, 1); vec.assign(ptr, ptr + num_samples); But when I run this program, I get the error double free or corruption (!prev) with a SIGABRT at this location. What is the problem of this approach and how would this question be solved more appropriately?
As I mentioned, I solved this problem by not using sonicChangeFloatSpeed at all, but the code within it. Before reading the results from the stream into vec, I do vec.resize(numSamples): sonicStream stream = sonicCreateStream(16000, 1); sonicSetSpeed(stream, speed); sonicSetPitch(stream, pitch); sonicSetVolume(stream, volume); sonicSetRate(stream, rate); auto length = static_cast<int>(vec.size()); sonicWriteFloatToStream(stream, vec.data(), length); sonicFlushStream(stream); int numSamples = sonicSamplesAvailable(stream); vec.resize(numSamples); sonicReadFloatFromStream(stream, vec.data(), length); sonicDestroyStream(stream);
69,616,145
69,616,197
My C++ program can't print out an entity's attribute
This is a simple C++ program that I made, I'm only using classes and constructors on this code. The problem here is, if I print out one of the entity's attributes, C++ would give me a runtime error where it won't print out the entity's height, weight, material or place. It just prints nothing. here's the code: #include <iostream> using namespace std; class Monolith{ public: int height; int weight; string material; string place; Monolith (int height, int weight, string material, string place){ height = height; weight = weight; material = material; place = place; } }; int main() { Monolith EiffelTower(300, 10000, "Iron", "Paris"); cout << EiffelTower.place; return 0; }
You're assigning nothing at all, because you assign to your local variables. Either try: Monolith (int height, int weight, string material, string place){ this->height = height; this->weight = weight; this->material = material; this->place = place; } or this: Monolith (int height, int weight, string material, string place) : height(height), weight(weight), material(material), place(place) { } To elaborate on what's going wrong: The problem is 'variable scope'. 'Local' tops 'class', 'class' tops 'global', in this order. So if you have local variables that have the same name as the class variables, you need to declare your 'target scope' explicitely (hence the this->, which explicitely addresses the class variables). If you wanted to write to global variables, you'd need to prefix it with ::. The second example uses the 'initialization syntax', where you call the constructor of the named attribute with the passed item. Prefer this syntax if applicable, because it avoids default construction.
69,616,430
69,616,549
Can lambda() that never evaluates to a constant expression be a `constexpr`-function in C++?
Lambda's operator() is implicitly constexpr according to https://en.cppreference.com/w/cpp/language/lambda When this specifier (constexpr) is not present, the function call operator or any given operator template specialization will be constexpr anyway, if it happens to satisfy all constexpr function requirements And a requirement of a constexpr-function according to https://en.cppreference.com/w/cpp/language/constexpr there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression (for constructors, use in a constant initializer is sufficient) (since C++14). No diagnostic is required for a violation of this bullet. In the next example, the function t() always throws an exception by calling lambda l(): auto l = []()->bool { throw 42; }; constexpr bool t() { return l(); } GCC rejects this function with the error: call to non-'constexpr' function '<lambda()>' but Clang accepts the program (until the function t() is used in a constant evaluation), meaning that it considers l() a constexpr-function, demo: https://gcc.godbolt.org/z/j1z7ee3Wv Is it a bug in Clang, or such compiler behavior is also acceptable?
All three compilers do issue an error when you actually try to use the result of t() in a context that requires a constant expression. For example: auto l = []()->bool { throw 42; }; constexpr bool t() { return l(); } template <bool x> struct dummy {}; int main() { dummy< t() > d; // error: t() is not a constant expression } As mentioned in a comment by NathanOliver, your quote already states: [...] No diagnostic is required for a violation of this bullet. Compilers need not necessarily proove that there is no set of argument values that allow the function to return a constant expression. On the other hand, a compiler can easily verify for a given argument value, that the result is not a constant expression.
69,616,631
69,616,690
Why I don't get any error (C-style casting)
char c{ 10 }; int* i = (int*)&c; *i = 1; // Run-Time Check Failure #2 - Stack around the variable 'c' was corrupted. But I don't get any error in this case char* c = new char{ 10 }; int* i = (int*)&c; *i = 1; //delete c; Why is it so?
With int* i = (int*)&c; you make i point to the variable c itself, not where c is actually pointing. Thus *i = 1 will change the value of the pointer variable c not the value of *c. If you want to get the same (or similar) behavior you should make i point to where c is pointing: int* i = (int*) c; As for why it doesn't give you any error, it's because on modern system int is 32 bits wide, while a pointer (like c) will be at least 32 bits wide as well (and 64 bits on a 64-bit system). Lastly a note about doing C-style casts in C++: You should always take it as a sign that you're doing something wrong.
69,616,738
69,617,027
Allocator in create publisher ROS2
Based on ROS2 documentation there is a third argument called an allocator that can be used when creatinga publisher. How can this allocator be used ? Does it allocate memory for the publisher ? std::shared_ptr< PublisherT > rclcpp::node::Node::create_publisher ( const std::string & topic_name, const rmw_qos_profile_t & qos_profile = rmw_qos_profile_default, std::shared_ptr< Alloc > allocator = nullptr )
The custom allocator will be used for all heap allocations within the context of the publisher. This is the same as how you would use a custom allocator with an std::vector as seen here. For ROS2, take the following example of a custom allocator. template<typename T> struct pointer_traits { using reference = T &; using const_reference = const T &; }; // Avoid declaring a reference to void with an empty specialization template<> struct pointer_traits<void> { }; template<typename T = void> struct MyAllocator : public pointer_traits<T> { public: using value_type = T; using size_type = std::size_t; using pointer = T *; using const_pointer = const T *; using difference_type = typename std::pointer_traits<pointer>::difference_type; MyAllocator() noexcept; ~MyAllocator() noexcept; template<typename U> MyAllocator(const MyAllocator<U> &) noexcept; T * allocate(size_t size, const void * = 0); void deallocate(T * ptr, size_t size); template<typename U> struct rebind { typedef MyAllocator<U> other; }; }; template<typename T, typename U> constexpr bool operator==(const MyAllocator<T> &, const MyAllocator<U> &) noexcept; template<typename T, typename U> constexpr bool operator!=(const MyAllocator<T> &, const MyAllocator<U> &) noexcept; Then, your main setup would look essentially the same as it would without a custom allocator. auto alloc = std::make_shared<MyAllocator<void>>(); auto publisher = node->create_publisher<std_msgs::msg::UInt32>("allocator_example", 10, alloc); auto msg_mem_strat = std::make_shared<rclcpp::message_memory_strategy::MessageMemoryStrategy<std_msgs::msg::UInt32, MyAllocator<>>>(alloc); std::shared_ptr<rclcpp::memory_strategy::MemoryStrategy> memory_strategy = std::make_shared<AllocatorMemoryStrategy<MyAllocator<>>>(alloc); For a more complete example I would suggest looking at the TLSF allocator which is designed to be useful for hard real time systems. It can be found here and a full example can be found here
69,616,858
69,616,920
Template member function syntax
I'm currently implementing containers in C++ and I have a question about the syntax used to declare member functions. I have a Vector_declaration.hpp file where I declare the vector class and all its components for instance: reference operator[](size_type n); Where reference is defined by typedef typename Allocator::reference reference; In another file called vector.hpp I want to implement the elements defined in Vector_declaration.hpp and I found that the only way to do that was with the following syntax: template <typename T, typename Allocator> typename vector<T, Allocator>::reference vector<T, Allocator>::operator[](size_type n) I don't understand what role typename vector<T, Allocator>::reference plays here, why do I have to rewrite the typename each time I use it in a function, shouldn't I be able to just use the word reference instead? Is there anyway to do so, so the code would be cleaner?
Here: template <typename T, typename Allocator> typename vector<T, Allocator>::reference vector<T, Allocator>::operator[](size_type n); The typename vector<T, Allocator>::reference is the return type of the method. Consider how it would look without templates: struct foo { using reference = int&; reference bar(); }; foo::reference foo::bar() { /*...*/ } reference is declared in the scope of foo. If you want to refer to it outside of the scope of foo you need to qualify the name foo::reference. Because this: reference foo::bar() { /*...*/ } would result in an error: "reference is not declared". Moreover, typename is needed because vector<T, Allocator>::reference is a dependent name (ie you need to tell the compiler that it is a type, in a specialization it might be the name of a member or not exist at all).
69,617,121
69,617,228
Lemires Nearly Divisionless Modulo Trick
In https://lemire.me/blog/2019/06/06/nearly-divisionless-random-integer-generation-on-various-systems/, Lemire uses -s % s to compute something which according to the paper is supposed to be 2^L % s. According to https://shufflesharding.com/posts/dissecting-lemire this should be equivalent, but I'm getting different results. A 32-bit example: #include <iostream> int main() { uint64_t s = 1440000000; uint64_t k1 = (1ULL << 32ULL) % s; uint64_t k2 = (-s) % s; std::cout << k1 << std::endl; std::cout << k2 << std::endl; } Output: ./main 1414967296 109551616 The results aren't matching. What am I missing?
Unary negation on integers operates on every bit (two's complement and all that). So if you want to simulate 32 bit operations using uint64_t variables, you need to cast the value to 32 bits for that step: #include <iostream> int main() { uint64_t s = 1440000000; uint64_t k1 = (1ULL << 32ULL) % s; uint64_t k2 = (-uint32_t(s)) % s; std::cout << k1 << std::endl; std::cout << k2 << std::endl; } Which leads to the expected result: Program returned: 0 Program stdout 1414967296 1414967296 See on godbolt
69,617,341
69,617,449
c++ Variadic boost fusion map alias template
Consider this snippet: #include <boost/fusion/container/map.hpp> #include <boost/fusion/include/pair.hpp> struct MsgA {}; struct MsgB {}; using MsgList = std::tuple<MsgA, MsgB>; template <typename Msg> class MsgSignal {}; template <typename... Args> using MsgSignals = boost::fusion::map<boost::fusion::pair<Args, MsgSignal<Args>>, ...>; int main() { MsgSignals<MsgList> signals; // signals should be of type boost::fusion::map<boost::fusion::pair<MsgA, MsgSignal<MsgA>, boost::fusion::pair<MsgB, MsgSignal<MsgB>>> > } Demo I'm struggling with the alias template MsgSignals. What is the right syntax such that the type of signals becomes boost::fusion::map<boost::fusion::pair<MsgA, MsgSignal<MsgA>, boost::fusion::pair<MsgB, MsgSignal<MsgB>>>
You can use template partial specialization to extract the types in std::tuple: template <typename Tuple> struct MsgSignalsImpl; template <typename... Args> struct MsgSignalsImpl<std::tuple<Args...>> { using type = boost::fusion::map<boost::fusion::pair<Args, MsgSignal<Args>>...>; }; template <typename Tuple> using MsgSignals = typename MsgSignalsImpl<Tuple>::type; Demo.
69,617,421
69,617,594
Why use iter = lst.insert(iter, word) and not just lst.insert(iter, word)
I'm still learning about insert() on C++. Why use iter = here? list<string> lst; auto iter = lst.begin(); while (cin >> word) iter = lst.insert(iter, word); Why not like this? list<string> lst; auto iter = lst.begin(); while (cin >> word) lst.insert(iter, word); I'm confused because there is also this case, which doesn't use slist.begin() =: list<string> slist; slist.insert(slist.begin(), "Hello!");
The difference becomes immediately apparent when you look at the output of the following input: 1 2 3 A: #include <list> #include <iostream> using namespace std; int main() { std::list<std::string> st; auto iter = st.end(); std::string word; while (cin >> word) iter = st.insert(iter, word); for (const auto& w : st) std::cout << w << " "; } output: 3 2 1 B: #include <list> #include <iostream> using namespace std; int main() { std::list<std::string> st; auto iter = st.end(); std::string word; while (cin >> word) st.insert(iter, word); for (const auto& w : st) std::cout << w << " "; } output: 1 2 3 Note that I used end() instead of begin(), because begin() looks a little fishy when there is no element yet in the list. However, for an empty list, begin() == end(), so it does not change the result. std::list::insert() inserts the element before the one referenced by the iterator you pass, and then returns an iterator to the newly inserted element. Hence, A inserts the next element always before the last element that was inserted. On the other hand, B always inserts the next element at the end of the list, because iter always points to the list's end.
69,617,802
69,618,235
How to overwrite conan shared option inside my project?
I have a project with the following conan recipe: from conans import ConanFile, CMake class MyLibConan(ConanFile): name = "mylib" version = "1.16.0" generators = "cmake" settings = "os", "arch", "compiler", "build_type" options = {"shared": [True, False]} default_options = "shared=False" exports_sources = ["*"] url = "some-url" license = "my license" description = "my library" def build(self): cmake = CMake(self) cmake.configure() cmake.build() def package(self): # do some copying here def package_info(self): self.cpp_info.includedirs = ['include'] self.cpp_info.libdirs = ['lib'] self.cpp_info.libs = ['mylib'] This library is supposed to be built in static mode. But the company servers build this as shared and my library tests fail because they can't find the .lib files. Even though I have set the default type as static, it gets overwritten when the server runs it's script. I have also removed the True value from the options but then the whole script fails because True is not an option. options = {"shared": [False]} How can I make sure the library is always built in static mode without the server script failing?
The obvious suggestion is fixing your server script, because your library can be built as shared and static. Another possibility is updating your server script to generate static and shared, not only one option. If in your company you need to maintain an internal script, I would suggest using Conan Package Tools instead, where you can define a set of configuration to be built. However, if it's not a possible scenario and you really need a workaround, you still can enforce your package option in configure(self) method: def configure(self): self.options.shared = False It will override any value passed by argument when building. Also, the package ID will be same, as your package will be always static.
69,617,908
69,623,018
How to call a x64 Assembly procedure in C#
I am working on a project and currently have the following structure: C# WPF project containing the User Interface as well as calls to external methods. C++ DLL project containing an algorithm. ASM DLL project containing an algorithm. For simplicity, let's assume the algorithm simply takes no parameters and returns the sum of two, predefined numbers. Here's the function signature and implementation in the C++ (second) project: int Add(int x, int y) { return x + y; } extern "C" __declspec(dllexport) int RunCpp() { int x = 1, y = 2; int z = Add(x, y); return z; } And here's how I call the function in C#: [DllImport("Algorithm.Cpp.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int RunCpp(); This works just fine - calling the function in C# returns the value 3, everything is working proplerly, no exceptions thrown. However, I am now struggling to call the ASM procedure in C# code. I have seen (and tested myself to an extent) that it's impossible to call a MASM DLL directly in C# code. However, I've heard that it's possible to call ASM in C++ and call that function in C#. 1. My first question is - is calling ASM code actually possible directly in C#? When I try that, I get an exception that basically says the binary code is incompatible. 2. I have tried to use C++ to indirectly call the ASM DLL, and while I get no exception, the returned value is "random", as in, it feels like a remainder left in memory, for example: -7514271. Is this something I'm doing wrong, or is there another way to achieve this? Here's the code for calling ASM in C++: typedef int(__stdcall* f_MyProc1)(DWORD, DWORD); extern "C" __declspec(dllexport) int RunAsm() { HINSTANCE hGetProcIDDLL = LoadLibrary(L"Algorithm.Asm.dll"); if (hGetProcIDDLL == NULL) { return 0; } f_MyProc1 MyProc1 = (f_MyProc1)GetProcAddress(hGetProcIDDLL, "MyProc1"); if (!MyProc1) { return 0; } int x = 1, y = 2; int z = MyProc1(x, y); FreeLibrary(hGetProcIDDLL); return z; } Here, the code for calling C++ in C#: [DllImport("Algorithm.Cpp.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int RunAsm(); And here's the ASM code of MyProc1, if needed: Main.asm: MyProc1 proc x: DWORD, y: DWORD mov EAX, x mov ECX, y add EAX, ECX ret MyProc1 endp Main.def: LIBRARY Main EXPORTS MyProc1
is calling ASM code actually possible directly in C#? Example of this with two projects, C# and assembly based DLL. Looks like you already know how to get a C++ based DLL working. The project names are the same as the directory names, xcs for C# and xcadll for the dll. I started with empty directories and created empty projects, then moved source files into the directories and then added existing items to each project. xcadll properties: Configuration Type: Dynamic Library (.dll) Linker | Input: xcadll.def xcadll\xcadll.def: LIBRARY xcadll EXPORTS DllMain EXPORTS Example xcadll\xa.asm properties (for release build, /Zi is not needed): General | Excluded From Build: No General | Item Type: Custom Build Tool Custom Build Tool | General | Command Line: ml64 /c /Zi /Fo$(OutDir)\xa.obj xa.asm Custom Build Tool | General | Outputs: $(OutDir)\xa.obj xcadll\xa.asm: includelib msvcrtd includelib oldnames ;optional .data .data? .code public DllMain public Example DllMain proc ;return true mov rax, 1 ret 0 DllMain endp Example proc ;[rcx] = 0123456789abcdefh mov rax, 0123456789abcdefh mov [rcx],rax ret 0 Example endp end xcs\Program.cs: using System; using System.Runtime.InteropServices; namespace xcadll { class Program { [DllImport("c:\\xcadll\\x64\\release\\xcadll.dll")] static extern void Example(ulong[] data); static void Main(string[] args) { ulong[] data = new ulong[4] {0,0,0,0}; Console.WriteLine("{0:X16}", data[0]); Example(data); Console.WriteLine("{0:X16}", data[0]); return; } } } For debug, use [DllImport("c:\\xcadll\\x64\\debug\\xcadll.dll")] xcs properties | debug | enable native mode debugging (check the box)
69,618,468
69,621,175
How can i set text size in wxWidgets?
Compiled application I want to make the Hello World text bigger, but i can't figure out how I tried using staticText1->SetSize(32), staticText1->SetSize(wxSize(32,32)) and replacing wxDefaultSize with wxSize(32, 32), but nothing works (I am not getting errors, it just doesnt change the text size) This is my current code: #include <wx/wx.h> class Frame : public wxFrame { private: wxStaticText* staticText1 = new wxStaticText(this, wxID_ANY, "Hello, World!", wxDefaultPosition, wxDefaultSize, wxALIGN_CENTER); public: Frame() : wxFrame(nullptr, wxID_ANY, "spageta", wxDefaultPosition, wxSize(400, 200)) { staticText1->SetForegroundColour(wxTheColourDatabase->Find("Black")); } }; class App : public wxApp { public: App(); private: wxFrame* NewFrame = nullptr; public: virtual bool OnInit(); }; App::App() { } bool App::OnInit() { NewFrame = new Frame(); NewFrame->Show(true); return true; } wxIMPLEMENT_APP(App);
You need to change the font size and not the window size. The best way to do it is to change the size of the same font it already uses, e.g. window->SetFont(window->GetFont().Scale(1.5)), which would make the font 1.5 times bigger. The same approach can be used to make it bold, or italic etc.
69,618,469
69,635,732
C++/OpenGL Texture appearing Pixelated
Here is my code for generating the texture(MRE): glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); if(readAlpha) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); Here is how Tex Coords are generated: for (int y = 0; y < resolution; y++) { for (int x = 0; x < resolution; x++) { int i = x + y * resolution; glm::vec2 percent = glm::vec2(x, y) / ((float)resolution - 1); glm::vec3 pointOnPlane = (percent.x - .5f) * 2 * right + (percent.y - .5f) * 2 * front; pointOnPlane *= scale; vertices[i] = Vert(); vertices[i].position = glm::vec3(0.0f); vertices[i].position.x = (float)pointOnPlane.x; vertices[i].position.y = (float)pointOnPlane.y; vertices[i].position.z = (float)pointOnPlane.z; vertices[i].texCoord = glm::vec2(percent.x, percent.y)*textureScale; vertices[i].normal = glm::vec3(0.0f); if (x != resolution - 1 && y != resolution - 1) { inds[triIndex] = i; inds[triIndex + 1] = i + resolution + 1; inds[triIndex + 2] = i + resolution; inds[triIndex + 3] = i; inds[triIndex + 4] = i + 1; inds[triIndex + 5] = i + resolution + 1; triIndex += 6; } } } Here is the shader: VERT: #version 330 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec3 aNorm; layout (location = 2) in vec2 aTexCoord; uniform mat4 _PV; uniform mat4 _Model; out DATA { vec3 FragPos; vec3 Normal; vec2 TexCoord; mat4 PV; } data_out; void main() { gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); data_out.FragPos = aPos; data_out.Normal = aNorm; data_out.TexCoord = aTexCoord; data_out.PV = _PV; } GEOM: #version 330 core layout(triangles) in; layout(triangle_strip, max_vertices = 3) out; out vec3 FragPos; out vec3 Normal; out vec2 TexCoord; in DATA { vec3 FragPos; vec3 Normal; vec2 TexCoord; mat4 PV; } data_in[]; void main() { gl_Position = data_in[0].PV * gl_in[0].gl_Position; Normal = data_in[0].Normal; TexCoord = data_in[0].TexCoord; FragPos = data_in[0].FragPos; EmitVertex(); gl_Position = data_in[0].PV * gl_in[1].gl_Position; Normal = data_in[1].Normal; TexCoord = data_in[0].TexCoord; FragPos = data_in[1].FragPos; EmitVertex(); gl_Position = data_in[0].PV * gl_in[2].gl_Position; Normal = data_in[2].Normal; TexCoord = data_in[0].TexCoord; FragPos = data_in[2].FragPos; EmitVertex(); EndPrimitive(); } FRAG: #version 330 core out vec4 FragColor; uniform vec3 _LightPosition; uniform vec3 _LightColor; uniform sampler2D _Diffuse; //unifrom float _UseTexutres; in vec3 FragPos; in vec3 Normal; in vec2 TexCoord; void main() { //vec3 objectColor = vec3(0.34f, 0.49f, 0.27f); vec3 objectColor = vec3(1, 1, 1); objectColor = texture(_Diffuse, TexCoord).xyz; vec3 norm = normalize(Normal); vec3 lightDir = normalize(_LightPosition - FragPos); float diff = max(dot(norm, lightDir), 0.0f); vec3 diffuse = diff * _LightColor; vec3 result = (vec3(0.2, 0.2, 0.2) + diffuse) * objectColor; FragColor = vec4(result, 1.0); } I am getting pixilated texture even thought I am using a 8K texture. If you want to see the entire source : https://github.com/Jaysmito101/TerraGen3D Here is the result:
Your geometry shader does not make sense: First of all, you use the same data_in.TexCoords[0] for all 3 vertices of of the output triangle, which means that all fragments generated for this triangle will sample the exact same location of the texture, resulting in the exact same output color, so the "pixelated" structure of the image emerges. Like you do already for Normal and FragPos, you should forward the data for each vertex. This already should solve your issue. However, there are more issues with your approach. You do forward mat4 PV as per-Vertex data from the VS to the GS. However, the data you forward is an uniform, so this is a waste of resources. Every shader stage has access to all of the uniforms, so there is no need to forward this data per vertex. But the real elephant in the room is what this geometry shader is supposed to be doing. The actual transformation with the uniform matrices can - and absolutely should - be carried out directly in the vertex shader. And the rest of your geometry shader is basically an attempt at a pass-through implementation (just a faulty one). So what do you need this shader for? You can do the transformation in the VS and completely remove the geometry shader. And performance-wise, this will also be a win as geometry shaders are rather inefficent and should be avoided if not absolutely needed.
69,618,549
69,618,824
Do C++ Objects (Standard Definition) persist in memory map files?
Question inspired by Dealing with large data binary files Link to Object Program (1) creates a memory-mapped file and writes some Objects (C++ Standard definition) to it, closes the file and exits. Program (2) maps the above file into memory and tries to access the Objects via reinterpret_cast. Is this legal by the Standard as the object representations have not changed and the Objects still exist in the file ? If this was attempted between 2 processes, not with a file, but using shared process memory is this legal ? Note - this question is not about storing or sharing local virtual addresses as this is obviously a bad thing.
No, objects do not persist this way. C++ objects are defined primarily by their lifetime, which is scoped to the program. So if you want to recycle an object from raw storage, there has to be a brand new object in program (2) with its own lifetime. reinterpret_cast'ing memory does not create a new object, so that doesn't work. Now, you might think that inplace-newing an object with a trivial constructor at that memory location could do the trick: struct MyObj { int x; int y; float z; }; void foo(char* raw_data) { // The content of raw_data must be treated as being ignored. MyObj* obj = new (raw_data) MyObj(); } But you can't do that either. The compiler is allowed to (and demonstrably does sometimes) assume that such a construction mangles up the memory. See C++ placement new after memset for more details, as well as a demonstration. If you want to initialize an object from a given storage representation, you must use memcpy() or an equivalent: void foo(char* raw_data) { MyObj obj; static_assert(std::is_standard_layout_v<MyObj>); std::memcpy(&obj, raw_data, sizeof(MyObj)); } Addendum: It is possible to do the equivalent of the desired reinterpret_cast<> by restomping the memory with its original content after creating the object (inspired by the IOC proposal). #include <type_traits> #include <cstring> #include <memory> template<typename T> T* start_lifetime_as(void *p) requires std::is_trivially_copyable_v<T> { constexpr std::size_t size = sizeof(T); constexpr std::size_t align = alignof(T); auto aligned_p = std::assume_aligned<align>(p); std::aligned_storage_t<size, align> tmp; std::memcpy(&tmp, aligned_p, size); T* t_ptr = new (aligned_p) T{}; std::memcpy(t_ptr , &tmp, size); return std::launder<T>(t_ptr); } void foo(char* raw_data) { MyObj* obj = start_lifetime_as<MyObj>(raw_data); } This should be well-defined in C++11 and up as long as that memory location only contains raw data and no prior object. Also, from cursory testing, it seems like compilers do a good job at optimizing that away. see on godbolt
69,619,660
69,629,318
How can I guarantee the position of data inside a separate linker section does not change when I extend it?
In an embedded C++ context, I have defined a separate linker section in flash memory, far away from the rest of the code/data, in which I store data that the user may modify at runtime. (EEPROM emulation, basically) I also have a custom device firmware updater, that's going to overwrite the read-only code/data in flash, except this section (and that of the firmware updater), because I want the persistent configuration changes the user has made to persist, even if they perform a firmware update. As part of these firmware, I may extend the amount of configuration the user can do. So, I have one code file that's essentially a list of global variables, that's getting linked at a given position in flash, and would be adding lines at the end. Of course, I really want to ensure that the position in memory of the variables that were here before don't change. What am I guaranteed about this ? Going by Memory layout of globals, I'm not sure I'm guaranteed that sequentially adding lines at the end of the file wouldn't alter the position of the previous variables. I believe the data members of the same access level in a struct will always be ordered in memory by the compiler, so I could define a struct somewhere, instantiate it in my dedicated linker section and extend it with future updates. But even then, I know just enough about alignment guarantees to know I don't know a whole lot about them, so I'm still not sure I'm safe. So, how should I do this ?
Several compilers and/or linkers order variables by some (to us users) unknown (hashing?) algorithm. If you rename a variable or add a variable, each of the variables might change its location. However, there is help, as the standard says in chapter 6.5.2.3 paragraph 6 (emphasis by me): One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the completed type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members. So if you define a structure for the saved data, you can append new members without fear. Use this structure to define the single variable of saved values. Even more, you can define a union of structures, which have a common initial sequence of members that you can use to distinguish the sequence of following members. Anyway, you need to locate this single variable by appropriate attributes and linker script entries. But you do this already.
69,619,831
69,620,374
How to pass jthread stop_token to functor?
I'm trying to work with the new jthreads and have started a std::jthread where the operator() does get called, but I am unable to get it to stop. I want to create the thread by calling it as a function object. my_thrd = std::make_shared<std::jthread>(&Test::operator(), &test); If operater() of my Test class is written as the following, it compiles: void Test::operator()() { using namespace std::literals; while (!token.stop_requested()) { std::cout << "Working ...\n" << std::flush; std::this_thread::sleep_for(5s); } close_connection(); } But since it wasn't stopping, I thought I needed to somehow pass std::stop_token to class Test, like so. void Test::operator()(std::stop_token token) { ... } But this doesn't compile. I did change the header as well. /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/thread: In instantiation of ‘static std::thread std::jthread::_S_create(std::stop_source&, _Callable&&, _Args&& ...) [with _Callable = void (Test::)(std::stop_token); _Args = {Test}]’: /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/thread:450:28: required from ‘std::jthread::jthread(_Callable&&, _Args&& ...) [with _Callable = void (Test::)(std::stop_token); _Args = {Test}; = void]’ /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/bits/stl_construct.h:97:14: required from ‘constexpr decltype (::new(void*(0)) _Tp) std::construct_at(_Tp*, _Args&& ...) [with _Tp = std::jthread; _Args = {void (Test::)(std::stop_token), Test}; decltype (::new(void*(0)) _Tp) = std::jthread*]’ /usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/g++-v10/bits/alloc_traits.h:514:4: required from ‘static constexpr void std::allocator_traitsstd::allocator<_CharT >::construct(std::allocator_traitsstd::allocator<_CharT >::allocator_type&, _Up*, _Args&& ...) [with _Up = std::jthread; _Args = {void (Test::)(std::stop_token), Test}; _Tp = std::jthread; std::allocator_traitsstd::allocator<_CharT >::allocator_type = std::allocatorstd::jthread]’ Thoughts?
You can use std::bind to bind &test to &Test::operator(), then use std::placeholders::_1 to reserve a place for unbound std::stop_token: struct Test { void operator()(std::stop_token token) { using namespace std::literals; while (!token.stop_requested()) { std::cout << "Working ...\n" << std::flush; std::this_thread::sleep_for(5s); } } }; int main() { Test test; auto my_thrd = std::make_shared<std::jthread>( std::bind(&Test::operator(), &test, std::placeholders::_1)); } Demo. As @Nicol Bolas commented, we can also use C++20 std::bind_front to do this, which is more lightweight and intuitive than std::bind: auto my_thrd = std::make_shared<std::jthread>( std::bind_front(&Test::operator(), &test));
69,620,024
69,620,052
Including constants without functions
I am making a c++ library and I want to include fcntl.h in the header (for the permission constants) But I have a function called open, the argument list contains classes that can be casted to the fcntl's open argument list types. That means when i use #include<fcntl.h> I am getting an ambiguous error. I want the library to be as portable as possible. I thought of changing the name from open to Open but is there a better solution? Like including the header without parsing the functions(eg. Just including the constants).
is there a better solution? Use a namespace: namespace my_lib { int open(const char *pathname, int flags); } And to be clear, a library should always declare its functions/classes/constants/etc... in a namespace, not just as a means to fix a specific issue. This way, you avoid potential conflicts with other libraries that users might be including that you have no visibility on. Edit: From the followup in the comment, if prefixing things with a namespace gets annoying, you can locally use individual identifiers from a namespace, and that will not be ambiguous, nor will is cause conflicts elsewhere in the code. #include <fcntl.h> namespace my_lib { int open(const char *pathname, int flags); } void foo() { using my_lib::open; open("aaa", 0); } You should never resort to using namespace my_lib. However, should you be painted in a corner (e.g. the using namespace is in code you can't change), you can resolve conflicts by explicitly referring to the namespace for the ambiguous symbol. #include <fcntl.h> namespace my_lib { void bar(); int open(const char *pathname, int flags); } using namespace my_lib; void foo() { bar(); // use the open() from fcntl.h ::open("aaa", 0); // Use the open() from my_lib ::my_lib::open("aaa", 0); }
69,620,442
69,620,561
Why does my reference update the element array it is referencing?
Could anyone explain to me in layman's terms why my reference is updating the element array that it is referencing? I thought the whole point of a reference was to only reference a value. #include <iostream> int main() { int arr[4] = { 0,0,0,0 }; arr[0] = 1; int& reference = arr[0]; reference = 2; std::cout << arr[0]; }
In layman terms, as requested: References and pointers are basically the same thing, the main difference being that references cannot be null and simplified syntax when you work with them. Also, array variables are also pointers. arr is a pointer to the beginning of the array, arr[1] is the pointer to the second element, it is the same thing as arr + 1. When you do int& reference = arr[0], you assign your reference to point at the first element of your array. When you then call reference = 2 it means the same as if you did arr[0]=2 or int * pointer = arr + 0; *pointer = 2;
69,620,861
69,620,912
Unable to create object from Main
I'm new to C++. This question might be easy, but I didn't find a proper answer to it after my Internet searches. I have a class with a public method to do some task. From the main() method, I'm trying to instantiate an object of my class to further call my method. I'm getting a compile-time error: MyClass: undeclared identifier I checked undeclared identifier issues to be resolved by wrong spelling or missing namespaces, but didn't find any luck in my case. I have a single .cpp file as below: int main() { MyClass sln; //Error here sln.MyMethod(); } class MyClass { public: void MyMethod() { //some code } };
You have to put the class definition before main() here, because it (the compiler) has to know the size of the object it is creating (instantiating). //class definition class MyClass { public: void MyMethod() { //some code } }; int main() { MyClass sln; sln.MyMethod(); } Check out the working program here.
69,621,052
69,621,117
C++ nested try-catch catching the same exceptions - how should I rewrite this code?
I currently have code in C++ 14 that looks like this: try { // create objects, process input myObject obj; // may throw std::invalid_argument in constructor for (i = 0; i < n_files; i++) { try { process_file(); // may throw std::invalid_argument and std::runtime_error() } catch (std::exception& e) {// print error continue; } } catch (std::exception& e) {// print error return 0; } For my own functions, I'm just throwing std exceptions like std::runtime_error and std__invalid_exception. The idea is that, objects created in the outer try block should throw exceptions and be caught by the outer catch block, which would then end the program. Exceptions thrown by process_file() would be caught by the inner try block, which would just print some error but not result in program termination, and the program would continue onto processing the next file. The outer try block contains object constructor calls that would then be used in inner try-catch, so I can't simply move it to its own try-catch otherwise the objects would be undefined in the loop. But this code as is won't work from what I understand, because exceptions thrown in the outer try block would hit the inner catch statement first, as that is the first catch statement reachable in the code. Also, nested try-catch like this would be bad form/confusing to read from what I've read. What would be the proper way of doing this instead? Thanks!
this code as is won't work from what I understand Yes, it will work just fine, for the scenario you have described. exceptions thrown in the outer try block would hit the inner catch statement first, as that is the first catch statement reachable in the code. That is not correct. It is not about the order in code, but the order in scope. The inner try is not in scope if the outer try throws. The exception goes up the call stack, starting at the current scope, then its nearest outer scope, then the next outer scope, and so on, until it finds a matching catch. For example: try { // if any std exception is thrown here, jumps to A below... try { // if std::invalid_argument is thrown here, jumps to B below... // if any other std exception is thrown here, jumps to A below... for (int i = 0; i < n_files; ++i) { try { // if any std exception is thrown here, jumps to C below... } catch (std::exception& e) // C { // print error continue; } } // if std::invalid_argument is thrown here, jumps to B below... // if any other std exception is thrown here, jumps to A below... } catch (invalid_argument& e) // B { // print error return 0; } } catch (exception& e) // A { // print error return 0; } nested try-catch like this would be bad form/confusing to read from what I've read. That is also not correct. There is nothing wrong with using nested try blocks. However, in this example, it would make more sense to have the inner try catch ONLY std::invalid_argument and std::runtime_error specifically, since those are the 2 types it is expecting and willing to ignore to continue the loop. Don't catch std::exception generally at that spot. That way, if process_file() throws something unexpected (say std::bad_alloc, for instance), then the outer catch should handle it to terminate the process. try { // if any std exception is thrown here, jumps to A below... try { // if std::invalid_argument is thrown here, jumps to B below... // if any other std exception is thrown here, jumps to A below... for (int i = 0; i < n_files; ++i) { try { // if std::invalid_argument is thrown here, jumps to D below... // if std::runtime_error is thrown here, jumps to C below... // if any other std exception is thrown here, jumps to A below... } catch (std::invalid_argument& e) // D { // print error continue; } catch (std::runtime_error& e) // C { // print error continue; } } // if std::invalid_argument is thrown here, jumps to B below... // if any other std exception is thrown here, jumps to A below... } catch (invalid_argument& e) // B { // print error return 0; } } catch (exception& e) // A { // print error return 0; } The best way to design a catch is to have it catch only the specific types of exceptions it knows how to handle at that spot in the code. Let an outer catch handle everything else. If an exception is thrown and no matching catch is found to handle it, the process will terminate by default.
69,621,111
69,621,340
Are mutex locks necessary when modifying values?
I have an unordered_map and I'm using mutex locks for emplace and delete, find operations, but I don't use a mutex when modifying map's elements, because I don't see any point. but I'm curious whether I'm wrong in this case. Should I use one when modifying element value? std::unordred_map<std::string, Connection> connections; // Lock at Try_Emplace connectionsMapMutex.lock(); auto [element, inserted] = connections.try_emplace(peer); connectionsMapMutex.unlock(); // No locks here from now auto& connection = element->second; // Modifying Element connection.foo = "bar";
Consider what can happen when you have one thread reading from the map and the other one writing to it: Thread A starts executing the command string myLocalStr = element->second.foo; As part of the above, the std::string copy-constructor starts executing: it stores foo's character-buffer-pointer into a register, and starts dereferencing it to copy out characters from the original string's buffer to myLocalStr's buffer. Just then, thread A's quantum expires, and thread B gains control of the CPU and executes the command connection.foo = "some other string" Thread B's assignment-operator causes the std::string to deallocate its character-buffer and allocate a new one to hold the new string. Thread A then starts running again, and continues executing the std::string copy-constructor from step 2, but now the pointer it is dereferencing to read in characters is no longer pointing at valid data, because Thread A deleted the buffer! Poof, Undefined Behavior is invoked, resulting in a crash (if you're lucky) or insidious data corruption (if you're unlucky, in which case you'll be spending several weeks trying to figure out why your program's data gets randomly corrupted only about once a month). And note that the above scenario is just on a single-core CPU; on a multicore system there are even more ways for unsynchronized accesses to go wrong, since the CPUs have to co-ordinate their local and shared memory-caches correctly, which they won't know to do if there is no synchronization code included. To sum up: Neither std::unordered_map nor std::string are designed for unsynchronized multithreaded access, and if you try to get away with it you're likely to regret it later on.
69,621,131
69,621,525
Find a sum of all positive matrix elements that located before of the largest positive element
here is what i tried before: //finding maximum for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (arr[i][j] > max) { max = arr[i][j]; imax = i; jmax = j; } } } //finding a sum for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (arr[i][j] > 0) { if (i <= imax && j < jmax) sum += arr[i][j]; } } } cout << "sum = " << sum << endl; } but that algorithm doesn't count it right, how should i do to make it work? looks like that my code is "limitng" the range of search, because of wrong condition and i duuno how to make it right?
Let's think step by step. Assuming, imax is the row number and jmax is the column number of the maximum elements present in the matrix. Row selection procedure: So, to accomplish our object, we will traverse row which is <= imax. That means, we'll consider the value of the current row as our answer only if current row <= imax. If the current row becomes larger than row, then we can stop traversing . //finding a sum for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (arr[i][j] > 0) { if(i <= imax) { // do something } else { break; } } } } We can also do it in below way: //finding a sum for (int i = 0; i < n && i <= imax; ++i) { for (int j = 0; j < n; ++j) { if (arr[i][j] > 0) { } } } Column selection procedure: It's a little bit different from the row selection procedure. We can consider every column unless current row is equal to imax. That means when current row < imax we will consider values of every column, but when current row == imax we'll only consider smaller column's value as our answer. //finding a sum for (int i = 0; i < n && i <= imax; ++i) { for (int j = 0; j < n; ++j) { if(i < imax && arr[i][j] > 0) { // consider the value for answer } else { // here i == imax // so we'll only consider smaller column's value as our answer if(j < jmax && arr[i][j] > 0) { // consider the value for answer } else if(j >= jmax) // we've come out of the boundary. No matter the value is positive or negative, we don't need to check any further { break; } } } } Overall code of finding sum portion will look like this: //finding a sum for (int i = 0; i < n && i <= imax; ++i) { for (int j = 0; j < n; ++j) { if(i < imax && arr[i][j] > 0) { // consider the value for answer sum += arr[i][j]; } else { // here i == imax // so we'll only consider smaller column's value as our answer if(j < jmax && arr[i][j] > 0) { // consider the value for answer sum += arr[i][j]; } else if(j >= jmax) // we've come out of the boundary. No matter the value is positive or negative, we don't need to check any further { break; } } } } Note: Don't forget to initialize the value of max , imax, jmax and sum properly.
69,621,633
69,621,884
Microsoft Visual Studio - Default/Auto apply settings?
How do I auto apply certain settings? For example: In this example, I want these settings to stick and not have to reapply them, but if I make a new project I have to constantly reapply them. How do I make them stay in those specific settings?
You can create your own template for the wizard, or just modify an existing one. Here are the steps: https://learn.microsoft.com/en-us/visualstudio/ide/how-to-update-existing-templates?view=vs-2019
69,621,893
69,636,868
What happens when the encryption algorithm receives an unsupported key size?
I try to build an encryption program, and I use AES (256/192/128) from realisation I took from GitHub there is an exception if the key is not of these sizes. But I want to use the key as a password, in KeePass (they also encrypt with this algorithm) we can create passwords of different sizes. What should I do? I must add some padding bytes? Or I must use a hash algorithm to create passwords of the same size?
The accepted answer is not correct, misleading, and insecure! password-based key derivation (PBKDF), a small intro Normally, the key for AES must be generated uniformly randomly. It is hard for humans to memorize random keys, so we use passwords and derive keys from them. The correct way to convert a password into a key is using PBKDFs like PBKDF2, scrypt, or better using Argon2. These key derivation functions take some parameters like info, salt, iteration count, memory size, thread amount, etc. These parameters will come from a very long line of countermeasure against password cracking methods. Salt is used to prevent the rainbow table. Iteration count is used to reduce the password search time of the attacker. Setting around 1M for PBKDF2 will slow the attacker 1M times. memory size is used to make the password hashing algorithm memory-hard so that an attacker cannot use massive GPU/ASIC to attack. thread amount is used to eliminate parallelization even in parallel CPUs. These and similar parameters can be adjusted according to your target security ( look at the documentation before use). Use a PBKDF to get the desired key size Each of these PBKDFs can output the required amount of key sizes, 128,256, or more. Even one can derive multiple keys from a single password by using different info or salt parameters. Simply Hashing with SHA256 is totally wrong, there are already rainbow tables for this, and even in hashcat can be used to massive parallel on GPUs to pawn your password. Never use, In your case, since the AES key is not random, the attackers will not go to brute-force the AES, they will look for your password, the 800K pawned list, and possibly your knowledge-based searches. Choosing a good password A good password is really important even you use a very strong PBKDF like the recent competition winner Argon2. One should use dicewire or similarly Bip39 type password. xkc936 tells this idea very well. With a good password, you can even survive a badly designed password hashing login mechanism, however, you can't do good on Facebook's openly stored password mechanism, shame on them!
69,621,960
69,622,573
Why does this nostdlib C++ code segfault when I call a function with a thread local variable? But not with a global var or when I access members?
Assembly included. This weekend I tried to get my own small library running without any C libs and the thread local stuff is giving me problems. Below you can see I created a struct called Try1 (because it's my first attempt!) If I set the thread local variable and use it, the code seems to execute fine. If I call a const method on Try1 with a global variable it seems to run fine. Now if I do both, it's not fine. It segfaults despite me being able to access members and running the function with a global variable. The code will print Hello and Hello2 but not Hello3 I suspect the problem is the address of the variable. I tried using an if statement to print the first hello. if ((s64)&t1 > (s64)buf+1024*16) It was true so it means the pointer isn't where I thought it was. Also it isn't -8 as gdb suggest (it's a signed compare and I tried 0 instead of buf) Assembly under the c++ code. First line is the first call to write //test.cpp //clang++ or g++ -std=c++20 -g -fno-rtti -fno-exceptions -fno-stack-protector -fno-asynchronous-unwind-tables -static -nostdlib test.cpp -march=native && ./a.out #include <immintrin.h> typedef unsigned long long int u64; ssize_t my_write(int fd, const void *buf, size_t size) { register int64_t rax __asm__ ("rax") = 1; register int rdi __asm__ ("rdi") = fd; register const void *rsi __asm__ ("rsi") = buf; register size_t rdx __asm__ ("rdx") = size; __asm__ __volatile__ ( "syscall" : "+r" (rax) : "r" (rdi), "r" (rsi), "r" (rdx) : "cc", "rcx", "r11", "memory" ); return rax; } void my_exit(int exit_status) { register int64_t rax __asm__ ("rax") = 60; register int rdi __asm__ ("rdi") = exit_status; __asm__ __volatile__ ( "syscall" : "+r" (rax) : "r" (rdi) : "cc", "rcx", "r11", "memory" ); } struct Try1 { u64 val; constexpr Try1() { val=0; } u64 Get() const { return val; } }; static char buf[1024*8]; //originally mmap but lets reduce code static __thread u64 sanity_check; static __thread Try1 t1; static Try1 global; extern "C" int _start() { auto tls_size = 4096*2; auto originalFS = _readfsbase_u64(); _writefsbase_u64((u64)(buf+4096)); global.val = 1; global.Get(); //Executes fine sanity_check=6; t1.val = 7; my_write(1, "Hello\n", sanity_check); my_write(1, "Hello2\n", t1.val); //Still fine my_write(1, "Hello3\n", t1.Get()); //crash! :/ my_exit(0); return 0; } Asm: 4010b4: e8 47 ff ff ff call 401000 <_Z8my_writeiPKvm> 4010b9: 64 48 8b 04 25 f8 ff mov rax,QWORD PTR fs:0xfffffffffffffff8 4010c0: ff ff 4010c2: 48 89 c2 mov rdx,rax 4010c5: 48 8d 05 3b 0f 00 00 lea rax,[rip+0xf3b] # 402007 <_ZNK4Try13GetEv+0xeef> 4010cc: 48 89 c6 mov rsi,rax 4010cf: bf 01 00 00 00 mov edi,0x1 4010d4: e8 27 ff ff ff call 401000 <_Z8my_writeiPKvm> 4010d9: 64 48 8b 04 25 00 00 mov rax,QWORD PTR fs:0x0 4010e0: 00 00 4010e2: 48 05 f8 ff ff ff add rax,0xfffffffffffffff8 4010e8: 48 89 c7 mov rdi,rax 4010eb: e8 28 00 00 00 call 401118 <_ZNK4Try13GetEv> 4010f0: 48 89 c2 mov rdx,rax 4010f3: 48 8d 05 15 0f 00 00 lea rax,[rip+0xf15] # 40200f <_ZNK4Try13GetEv+0xef7> 4010fa: 48 89 c6 mov rsi,rax 4010fd: bf 01 00 00 00 mov edi,0x1 401102: e8 f9 fe ff ff call 401000 <_Z8my_writeiPKvm> 401107: bf 00 00 00 00 mov edi,0x0 40110c: e8 12 ff ff ff call 401023 <_Z7my_exiti> 401111: b8 00 00 00 00 mov eax,0x0 401116: c9 leave 401117: c3 ret
The ABI requires that fs:0 contains a pointer with the absolute address of the thread-local storage block, i.e. the value of fsbase. The compiler needs access to this address to evaluate expressions like &t1, which here it needs in order to compute the this pointer to be passed to Try1::Get(). It's tricky to recover this address on x86-64, since the TLS base address isn't in a convenient general register, but in the hidden fsbase. It isn't feasible to execute rdfsbase every time we need it (expensive instruction that may not be available) nor worse yet to call arch_prctl, so the easiest solution is to ensure that it's available in memory at a known address. See this past answer and sections 3.4.2 and 3.4.6 of "ELF Handling for Thread-Local Storage", which is incorporated by reference into the x86-64 ABI. In your disassembly at 0x4010d9, you can see the compiler trying to load from address fs:0x0 into rax, then adding -8 (the offset of t1 in the TLS block) and moving the result into rdi as the hidden this argument to Try1::Get(). Obviously since you have zeros at fs:0 instead, the resulting pointer is invalid and you get a crash when Try1::Get() reads val, which is really this->val. I would write something like void *fsbase = buf+4096; _writefsbase_u64((u64)fsbase); *(void **)fsbase = fsbase; (Or memcpy(fsbase, &fsbase, sizeof(void *)) might be more compliant with strict aliasing.)
69,622,589
69,627,172
move semantics 2d vector in C++
I have a question on C++ move semantics in 2D vector (or a vector of vectors). It comes from a problem of dynamic programing. For simplicity, I just take a simplified version as the example. //suppose I need to maintain a 2D vector of int with size 5 for the result. vector<vector<int>> result = vector<vector<int>>(5); for(int i = 0; i < 10; i++){ vector<vector<int>> tmp = vector<vector<int>>(5); //Make some updates on tmp with the help of result 2D vector /* Do something */ //At the end of this iteration, I would like to assign the result by tmp to prepare for next iteration. // 1) The first choice is to make a copy assignment, but it might introduce some unnecessary copy // result = tmp; // or // 2) The second choice is to use move semantics, but I not sure if it is correct on a 2D vector. // I am sure it should be OK if both tmp the result are simply vector (1D). // result = move(tmp); } So, is it OK to simply use `result = move(tmp);' for the move semantics of 2D vector?
Yes, because result is not '2D' vector, it's simply 1-D vector of vectors.
69,622,953
69,623,102
CMake include header file in different directory
So I have a directory that's formatted as follows: Project: - src - a.cpp - b.cpp - c.cpp - include - h.cpp - h.hpp How would I get CMake to include h.hpp in the files in the source folder? I tried doing include_directories(include) but CMake is still unable to find the file. I also tried changing the include directive in a.cpp to #include "../include/h.hpp". However, none of these solutions have worked. EDIT: The output is: [build] Consolidate compiler generated dependencies of target a [build] Consolidate compiler generated dependencies of target c [build] Consolidate compiler generated dependencies of target b [build] [ 16%] Building CXX object CMakeFiles/b.dir/src/b.cpp.o [build] [ 33%] Building CXX object CMakeFiles/c.dir/src/c.cpp.o [build] [ 50%] Building CXX object CMakeFiles/a.dir/src/a.cpp.o [build] [ 66%] Linking CXX executable a [build] [ 83%] Linking CXX executable c [build] [100%] Linking CXX executable b [build] /usr/bin/ld: CMakeFiles/a.dir/src/a.cpp.o: in function `func(...)': [build] ../a.cpp:55: undefined reference to `func(...)' [build] /usr/bin/ld: a.cpp:58: undefined reference to `func(...)' Note that func is a function with an implementation provided in h.cpp. CMakeLists.txt: cmake_minimum_required(VERSION 3.17) set(CMAKE_TOOLCHAIN_FILE ${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file") project(proj) find_package(fmt CONFIG REQUIRED) find_package(CUDAToolkit REQUIRED) link_libraries( fmt::fmt CUDA::nvrtc CUDA::cuda_driver CUDA::cudart ) include_directories(include) add_executable(a ${CMAKE_CURRENT_SOURCE_DIR}/src/a.cpp) add_executable(b ${CMAKE_CURRENT_SOURCE_DIR}/src/b.cpp) add_executable(c ${CMAKE_CURRENT_SOURCE_DIR}/src/c.cpp)
You should add h.cpp as a source for each executable that uses functions from h.hpp: add_executable(a ${CMAKE_CURRENT_SOURCE_DIR}/src/a.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/h.cpp) add_executable(b ${CMAKE_CURRENT_SOURCE_DIR}/src/b.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/h.cpp) add_executable(c ${CMAKE_CURRENT_SOURCE_DIR}/src/c.cpp ${CMAKE_CURRENT_SOURCE_DIR}/include/h.cpp) As you have said, func is a function with an implementation provided in h.cpp so you need to add that implementation to your executables
69,623,199
69,623,227
Problem in memory allocation of char variable in C++, through visual studio debbuger
char is a type that have one byte in C++, in a way that we can use it as signed or unsigned, changing the values it can allocate. I'm new using debugger in Visual Studio and also in reading about memory. I'm using the following code: int main() { signed char a = 170; signed char* b = &a; } the range of a variable should be -128 to 127, the value of the variable is converted and -86 is settled, but when I get the value of the b variable, which is the memory alocation, to see what is there I get: 0x0019F99B aa cc cc cc cc 6d f3 ea 54 c4 f9 19 00 13 1f a0 00 01 00 00 00 60 78 76 00 d0 b5 76 00 01 00 00 00 60 78 76 00 d0 b5 76 00 20 fa 19 00 67 1d a0 00 e9 f0 ea 54 23 10 a0 00 23 10 a0 00 00 60 ªÌÌÌÌmóêTÄù.... .....`xv.еv.....`xv.еv. ú..g. .éðêT#. .#. .. but aa in hexadecimal evaluates to 170. What happened?
The 170 literal is an int represented by 0x000000AA. When you convert that into a single byte signed char, it simply truncates the bytes, so you wind up with 0xAA, which happens to be -86 in twos-complement notation.
69,623,544
69,667,431
Cmake: How to link multiple libraries?
I am using CMake to define the compilation of a C++ executable. The goal is to use 2 third-party libraries, Open3D and OpenCV. I am able to include one of the two with target_link_libraries, but including both results in OpenCV functions not being found. This is my current CMakeLists.txt minimum_required(VERSION 3.20) project(ORB_SLAM) find_package(Open3D REQUIRED) find_package(OpenCV REQUIRED) set(CMAKE_CXX_STANDARD 20) add_executable(ORB_SLAM src/main.cpp) #target_link_libraries(ORB_SLAM ${Open3D_LIBRARIES}) target_link_libraries(ORB_SLAM ${OpenCV_LIBS}) # When printed, ${Open3D_LIBRARIES} = Open3D::Open3D # ${OpenCV_LIBS} = opencv_calib3d;opencv_core;...many more..;opencv_xphoto With this CMakeList.txt, I can successfully use OpenCV functions. By using the commented out Open3D target_link_libraries, I can successfully use Open3D. When uncommenting both target_link_libraries, it fails to find OpenCV functionality, regardless of the order of the find_package and target_link_libraries. The same error even occurs if I include both in a single target_link_libraries(ORB_SLAM ${OpenCV_LIBS} ${Open3D_LIBRARIES}). The same error occurs for CMake 3.16.3 and 3.21.3. The error is as follows: /usr/bin/ld: CMakeFiles/ORB_SLAM.dir/src/main.cpp.o: in function `main': /home/m/CLionProjects/ORB_SLAM/src/main.cpp:20: undefined reference to `cv::VideoCapture::VideoCapture(std::string const&, int)' For the code #include <opencv2/opencv.hpp> #include <opencv2/videoio.hpp> //#include <open3d/Open3D.h> int main() { cv::VideoCapture cap("/home/.../scene.mp4"); //auto sphere = open3d::geometry::TriangleMesh::CreateSphere(1.0); } It seems as though Open3D::Open3D takes precedence over opencv_calib3d;opencv_core;.... What is causing this and how can I fix it? Is this perhaps due to the discrepancy in Open3D's "::" vs OpenCV's lowercase notation? Edit: Here is a dump of all CMake variables if it is of any use https://textuploader.com/t5dvl/raw Excuse my inexperience. I have searched through CMake documentation and Stackoverflow questions for a lead, but so far I have found nothing.
The problem was solved by finding this Github issue: https://github.com/isl-org/Open3D/issues/2286 By using specific build flags when building Open3D, the libraries could both be linked correctly and simultaneously with the target_link_libraries(ORB_SLAM ${OpenCV_LIBS} ${Open3D_LIBRARIES}) command. The build commands were as follows; git clone --recursive https://github.com/intel-isl/Open3D cd Open3D && source util/scripts/install-deps-ubuntu.sh mkdir build && cd build cmake -DBUILD_EIGEN3=ON -DBUILD_GLEW=ON -DBUILD_GLFW=ON -DBUILD_JSONCPP=ON -DBUILD_PNG=ON -DGLIBCXX_USE_CXX11_ABI=ON -DPYTHON_EXECUTABLE=/usr/bin/python -DBUILD_UNIT_TESTS=ON .. make -j4 sudo make install
69,623,714
69,623,794
Dynamic Array - Problem with memory management
I'm working on the dynamic array. Related part of code of the array class: #pragma once #include <iostream> template <class T> class Darray { private: T* dataArray; int a_size = 0; int a_capacity = 0; double expandFactor = 1.5; private: void memLoc(int n_capacity) { T* newArray = new T[n_capacity]; for (int i = 0; i < a_size; i++) { newArray[i] = dataArray[i]; } dataArray = newArray; delete[] newArray; //<-- **************problem occurs here************** a_capacity = n_capacity; } public: Darray() { T* dataArray = new T[a_size]; memLoc(2); } void addLast(T data) { if (a_size < a_capacity) { dataArray[a_size] = data; a_size++; } else { memLoc(a_capacity * expandFactor); dataArray[a_size] = data; a_size++; } } When I run the code without deleting the newArray I get expected result: Values Index 0: 10 Index 1: 9 Index 2: 8 Index 3: 7 Index 4: 6 Index 5: 5 Index 6: 4 Index 7: 3 Index 8: 2 Index 9: 1 Here is my problem! When I delete newArray (marked in the code) my results are far from accurate: Values Index 0: -572662307 Index 1: -572662307 Index 2: 100663302 Index 3: 31812 Index 4: 17648624 Index 5: 17649832 Index 6: -572662307 Index 7: -572662307 Index 8: -572662307 Index 9: -572662307 I have no idea why this is happening because at first glance everything seems to be correct. Any suggestion or hint would be appreciated. I hope somebody will be able to help ;)
There are a couple of mistakes in your code. In memLoc(), you are destroying the new array you just created. You need to instead destroy the old array that is being replaced. The statement dataArray = newArray; is just assigning a pointer to another pointer. dataArray is pointing at the previous array, and newArray points at the new array. When you perform dataArray = newArray;, you leak the previous array, and now both dataArray and newArray are pointing at the same array, and then delete[] newArray; destroys that array, leaving dataArray as a dangling pointer to invalid memory. In your default constructor, you are creating a new array and assigning its pointer to a local variable named dataArray, which is hiding the class data member also named dataArray. You are then calling memLoc() to create another array for the class data member dataArray to point at. The 1st array is useless and gets leaked. You should instead initialize the class data member to nullptr, and just call memLoc() to create the only array. Also, while these are not mistakes per-say, they are noteworthy: I'm assuming the rest of the code you have not shown is compliant with the Rule of 3/5/0, ie you have a destructor, copy/move constructors, and copy/move assignment operators. If not, make sure you address that, otherwise you will run into other problems later. the code in addLast() is repetitive and can be simplified. With that said, try this: #pragma once #include <iostream> #include <utility> template <class T> class Darray { private: T* dataArray = nullptr; int a_size = 0; int a_capacity = 0; static const double expandFactor = 1.5; private: void memLoc(int n_capacity) { T* newArray = new T[n_capacity]; for (int i = 0; i < a_size; ++i) { newArray[i] = dataArray[i]; } delete[] dataArray; dataArray = newArray; a_capacity = n_capacity; } public: Darray() { memLoc(2); } Darray(const Darray &src) { memLoc(src.a_capacity); for (int i = 0; i < src.a_size; ++i) { dataArray[i] = src.dataArray[i]; ++a_size; } } Darray(Darray &&src) { std::swap(dataArray, src.dataArray); std::swap(a_capacity, src.a_capacity); std::swap(a_size, src.a_size); } ~Darray() { delete[] dataArray; } Darray& operator=(Darray rhs) { std::swap(dataArray, rhs.dataArray); std::swap(a_capacity, rhs.a_capacity); std::swap(a_size, rhs.a_size); return *this; } void addLast(const T &data) { if (a_size >= a_capacity) memLoc(a_capacity * expandFactor); dataArray[a_size] = data; ++a_size; } ... };
69,624,502
69,624,536
Segmentation fault when initialize an array after create object of template class
Below is my linked list template class and i define it in "LinkedListTemplate.h": template<typename T> class Node{ T data; Node<T> *next; public : void setData(T new_data){ data = new_data; } Node<T>* &getNext(){ return next; } T getData(){ return data; } }; template<typename T> class LinkedList{ private : Node<T> **head_ref; public : LinkedList(){ (*head_ref) = NULL; } void insert(T data){ Node<T> *new_node = new Node<T>; new_node->setData(data); new_node->getNext() = (*head_ref); (*head_ref) = new_node; } void printList(){ Node<T> *current = (*head_ref); while(current != NULL){ cout << current -> getData() << " "; current = current -> getNext(); } } Node<T> *getHead() const{ return (*head_ref); } void deleteList(){ Node<T> *current = (*head_ref); Node<T> *next; while(current != NULL){ next = current -> getNext(); delete current; current = next; } (*head_ref) = NULL; } }; So i want to use this template class to create a class name Set used to manage a set of integer it have a constructor that use given array and size and i define this class in "4-5.h" header class Set{ private : LinkedList<int> l; public : Set() {} Set(int a[], int size){ for(int i = 0; i < size; i++) l.insert(a[i]); } ~Set(){ l.deleteList(); } }; So in my main when i create an object using default construct to create object it work normally but when i initialize an array of int i got segmentation fault like below : int main() { Set s1; cout << s1; // This work fine int a[] = {2,3} // When i initialize it i got segmentation fault return 0; }
template<typename T> class LinkedList{ private : Node<T> **head_ref; public : LinkedList(){ (*head_ref) = NULL; // HERE } What do you think head_ref points to in the line that I marked? You never initialize head_ref. So when you do (*head_ref) you are dereferencing a pointer that doesn't point to anything.
69,624,688
69,624,876
How do you generate subarrays of an array with specific number of elements and then store it in another array?
What I need to do is to create subarrays of an existing array and the subarray should have a given number of elements. For eg. if I have the array [1,2,3,4] and I need to generate subarrays of it with exactly three elements, I would want the a separate 2-d array to include the following arrays: [1,2,3] [1,2,4] [1,3,4] [2,3,4] and so on and so forth. Thank you in advance.
You can do it by first calculating how many combinations there are by picking 3 elements in a group of 4 and what these combinations look like. Then you can use these combinations to pick elements from your input and create output like this : #include <cassert> #include <algorithm> #include <iostream> #include <numeric> #include <vector> #include <set> // calculate numbers of ways in which we can pick number_of_elements_to_pick from // number_of_elements auto get_combinations_of_indices_to_pick(std::size_t number_of_elements_to_pick, std::size_t number_of_elements) { assert(number_of_elements > number_of_elements_to_pick); // set which element to pick to true for number_of_elements_to_pick std::vector<bool> pick_element_n(number_of_elements_to_pick, true); // and the rest to false (we will not pick out those indices) pick_element_n.insert(pick_element_n.end(), number_of_elements - number_of_elements_to_pick, 0); // the total number of combinations is the number of permutations of the bits. std::vector<std::vector<std::size_t>> combinations; do { std::vector<std::size_t> combination; for (std::size_t i = 0; i < number_of_elements; ++i) { if (pick_element_n[i]) combination.push_back(i); } combinations.push_back(combination); } while (std::prev_permutation(pick_element_n.begin(), pick_element_n.end())); return combinations; } int main() { std::vector<int> input{ 1,2,3,4 }; // get combinations of 3 indices to pick from input vector auto combinations = get_combinations_of_indices_to_pick(3, input.size()); // there will be a vector of vectors as output std::vector<std::vector<int>> outputs; outputs.reserve(combinations.size()); // loop over all combinations of indices for (const auto& combination : combinations) { std::vector<int> output; // foreach combination of indicices to pick // add input for that index to the output for this combination for (const auto index : combination) { output.push_back(input[index]); } // then add this selected subvector to the outputs outputs.push_back(output); } // show the possible output vectors for (const auto& output : outputs) { bool comma = false; for (const auto& value : output) { if (comma) std::cout << ", "; std::cout << value; comma = true; } std::cout << "\n"; } } Note : The number of possible combinations can get very big very quickly. And usually there is a faster way of solving problems then just blindly go over all the possible combinations.
69,625,197
69,625,276
Can you access the current iterator from a function used by the transform function in c++?
Can you access the current iterator from a function used by the transform function in c++ so that you can reference previous and latter values? I want to use the transform function to iterate through a vector, performing operations on the vector that rely on values before and after the current value. For example, say I have a vector with values [1,2,4,3,5,6], and I want to start at the second value, and iterate until the second to last value. On each of those elements, I want to make a new value that equals the sum of the value, and the values next to it in the original. The ending vector would look like [7,9,12,14]. auto originalsBeginIterator = originalPoints.begin(); auto originalsEndIterator = originalPoints.end(); std::advance(originalsBeginIterator, 1); std::advance(originalsEndIterator,-1); std::transform(originalsBeginIterator,originalsEndIterator,alteredValues.begin(), [](int x) x = { return {previous value} + x + {next value};} ); Is there any way to reference previous and latter values from the original array when using transform?
Clearly the tool std::transform simply doesn't give you a way to do that: it either takes a unary predicate to be applied to individual elements of of one collection, or a binary predicate to be applied to corresponding elements of two collections. But the point is that, from the functional programming perspective, what you are trying to do is simply not a transform. How can you go about it instead? You could zip that vector, let's call it v, the same vector deprived of its first element, and the same vector deprived from its second element; you would then sum the 3 elements of each pair. Range-v3 gives you a way to do this quite tersely: #include <iostream> #include <range/v3/view/drop.hpp> #include <range/v3/view/transform.hpp> #include <range/v3/view/zip_with.hpp> #include <vector> using namespace ranges::views; int main() { // input std::vector<int> v{1,2,3,4,5,6}; // to sum 3 ints auto constexpr plus = [](int x, int y, int z){ return x + y + z; }; // one-liner auto w = zip_with(plus, v, v | drop(1), v | drop(2)); // output std::cout << w << std::endl; } v | drop(1) gives you a view on the elements {2,3,4,5,6}, and v | drop(2) on {3,4,5,6}; zip_with taks a n-ary function and n ranges and combines the n-tuple of corresponding elements from the n ranges using the n-ary function. So in our case it'll go like this: v = {1, 2, 3, 4, 5, 6} + + + + v1 = v | drop(1) = {2, 3, 4, 5, 6} + + + + v2 = v | drop(2) = {3, 4, 5, 6} zip_with(plus, v, v1, v2) = {6, 9,12,15}
69,625,262
69,625,289
Loop isn't printing expected results
I'm trying to prompt the user for items and the quantity of those items respectively. But when I run the program, it correctly displays the elements in the first vector, and not the elements in the second vector. #include <iostream> #include <vector> using namespace std; int main(){ // Declaring vectors vector <string> items{}; vector <int> quantity{}; cout << "Enter name of items." << endl; // Read input to vectors for(int i{1}; i <= 3; ++i){ string item{}; cin >> item; items.push_back(item); } cout << "Enter quantity of each item." << endl; for(int i{1}; i <= 3; ++i){ int num{}; cin >> num; quantity.push_back(num); } // Display data for(auto item: items){ int i{0}; cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl; ++i; cout << "--------------------" << endl; } return 0; } output Enter name of items. meat fish milk Enter quantity of each item. 10 20 30 Item: meat - Quantity: 10 -------------------- Item: fish - Quantity: 10 -------------------- Item: milk - Quantity: 10 -------------------- I tried printing out quantity.at(1) and it correctly displays 20, I apologize in advance if I missed out on something obvious. I'm very new to the language.
You are always setting i equal to the 0th element. instead move the creation of i to be outside the loop: int i{0}; for(auto item: items){ cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl; ++i; cout << "--------------------" << endl; }
69,625,541
69,625,919
Why traversal on modified 'std::vector' more slowly than unmodified 'std::vector'?
This is the code that shows the access behavior of std::vector slows down when std::vector is sorted by std::sort(). #include <cstdio> #include <chrono> #include <random> #include <cstdlib> #include <cstring> #include <algorithm> constexpr auto NUM_KEYS(24000000); constexpr auto CLOCK_MILI(CLOCKS_PER_SEC/1000); constexpr auto CHARS("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); static int x = 0; void insert(void* obj) { std::size_t len = std::strlen((const char*)obj); for(std::size_t i=0; i<len; ++i) for(std::size_t j=0; j<len; ++j) ++x; } int main(void) { std::vector<void*> list; auto seed = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937_64 rng(seed); std::uniform_int_distribution<int> rand_ch(0, 25); std::uniform_int_distribution<std::size_t> rand_len(8, 16); // Generate random string for(std::size_t i=0; i<NUM_KEYS; ++i) { std::size_t len = rand_len(rng); char* buf = new char[len+1](); for(std::size_t j=0; j<len; ++j) buf[j] = CHARS[rand_ch(rng)]; list.push_back(buf); } // First traverse the list std::clock_t cl = std::clock(); for(auto obj : list) insert(obj); printf("Time 1 = %ld miliseconds\n", (clock()-cl)/CLOCK_MILI); // Sorting the list std::sort(list.begin(), list.end(), [](const void* a, const void* b) { return std::strcmp((const char*)a, (const char*)b)<0; }); // Second traverse the list cl = std::clock(); for(auto obj : list) insert(obj); printf("Time 2 = %ld miliseconds\n", (clock()-cl)/CLOCK_MILI); // Destroy the strings for(auto obj : list) delete[] (char*)obj; return EXIT_SUCCESS; } There are 2 iterations trying to traverse the list while calling insert(). The insert() function does not modify the data. The first iteration is done without std::sort(), and the second iteration is done after std::sort(). The result obtained at runtime executed on option -std=c++17 -O3 with GCC 11.1.0: Time 1 = 101 miliseconds Time 2 = 909 miliseconds Likewise, the result when std::sort() is omitted at run: Time 1 = 102 miliseconds Time 2 = 101 miliseconds Access to list is 9 times slower when list is modified by std::sort(). Similar results occur when std::sort() is replaced with std::random_shuffle(), or some code that modifies list. So what really happened? Why does traversal of std::vector slow down after modification?
The selection of the vector name is accidentally quite revealing. Because the vector is a vector of pointers, it behaves similarly to a list, causing data that was originally allocated in (probably) linear order to be accessed after sorting in random order. If in contrast all the data you access is contained within the vector without indirection, I would expect the runtimes being much closer in each run. The cause of this phenomenom is cache misprediction or that the data to be read next not being available in the smallest/fastest data cache. Reading data from main memory or deeper levels of cache is typically orders of magnitude slower than reading them from the top level cache and the sorting will invalidate all chances of predicting the next memory addresses to read.
69,625,589
69,625,669
Operator Overloading C++ for + operator
I am currently learning how to do operator overloading in C++, i found some codes online that works when it is run below. class Complex { private: int real, imag; public: Complex(int r = 0, int i = 0) { real = r; imag = i; } // This is automatically called when '+' is used with // between two Complex objects Complex operator+(Complex const &obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout << real << " + i" << imag << endl; } }; int main() { Complex c1(10, 5), c2(2, 4); Complex c3 = c1 + c2; // An example call to "operator+" c3.print(); } However when i tried a similar structure, i received the following error : no default constructor found and << error which i am not familiar with. class Chicken { private: int i; int k; int s; int total = 0; public: Chicken(int index, int kentucky, int sign) { i = index; k = kentucky; s = sign; } Chicken operator+(Chicken obj) { Chicken Chicky; Chicky.total = i + obj.i; return Chicky; } }; int main() { Chicken P(1, 2, 3); Chicken U(2, 2, 2); Chicken W = P + U; cout << W; } enter image description here
Below is the corrected example. First, you were getting the error because inside operator+ you were default constructing an object of Chicken type but your class doesn't have any default constructor. The solution is to add the default constructor. #include <iostream> class Chicken{ //needed for cout<<W; to work friend std::ostream& operator<<(std::ostream& os, const Chicken &rhs); private: int i = 0; int k = 0; int s = 0; int total = 0; public: //default constructor Chicken() = default; //use constructor initializer list instead of assigning inside the body Chicken(int index, int kentucky, int sign): i(index), k(kentucky), s(sign){ //i = index; //k = kentucky; //s = sign; } Chicken operator + (Chicken obj){ Chicken Chicky;//this needs/uses default constructor Chicky.total = i + obj.i; return Chicky; } }; std::ostream& operator<<(std::ostream& os, const Chicken &rhs) { os << rhs.i << rhs.k << rhs.s << rhs.total ; return os; } int main(){ Chicken P(1,2,3); //this uses parameterized constructor Chicken U(2,2,2); //this uses parameterized constructor Chicken W = P+U; //this uses overloaded operator+ std::cout << W; //this uses oveloaded operator<< } Second, you were using the statement cout<<W; but without overloading operator<<. For std::cout<< W; to work you will need to overload operator<< as i have shown in the above code. You can check out the working example here. Third, you can/should use constructor initializer list instead of assigning values inside the body of the constructor as shown above.
69,625,818
69,625,844
Question about constructors & memory leak
I was testing with constructors and destructors, and I want to see if I can pass an object to a function without declaring it first, like this example: #include<iostream> #include<stdlib.h> using namespace std; class car { public: string name; int num; public: car(string a, int n) { cout << "Constructor called" << endl; this->name = a; this->num = n; } ~car() { cout << "Deleted" << endl; } }; void display(car* p) { cout << "Name: " << p->name << endl; cout << "Num: " << p->num << endl; } int main() { display(new car("HYUNDAI", 2012)); } The display function works fine, and it did exactly what I had expected, but I was wondering: If I had declared the new keyword inside the input to display, why didn't my user-defined destructor get called, and Would that new cause a memory leak?
Would that new cause a memory leak? Yes, it is causing the memory leak. Whatever you newed should be deleteed after wards(Manual memory management). why didn't my user-defined destructor get called? Because the object has not been deleted and hence not been destructed. You should be doing void display(car* p) { if (p) // check p is valid pointer { std::cout << "Name: " << p->name << std::endl; std::cout << "Num: " << p->num << std::endl; // ...after use delete p; } } Alternative to manual memory management, you could have used the smart pointers. What is a smart pointer and when should I use one? That being said, for the case shown, you do not need the pointers(unless you want to practice with the pointers). One option is to pass it as const car& which will work for temporary objects as well. void display(const car& p) // ^^^^^^^^^^^^ { std::cout << "Name: " << p.name << std::endl; std::cout << "Num: " << p.num << std::endl; } and you can pass a car as display(car{ "HYUNDAI", 2012 }); See: What are the differences between a pointer variable and a reference variable in C++?
69,626,176
69,632,639
Creating TCanvas to measure text width
I want to measure text width of a TButton so that I can resize it when the text changes. If the button uses ParentFont, I can use the form Canvas to get the width: int GetButtonTextWidth(TForm* form, TButton* btn) { const int base = form->Canvas->TextWidth(btn->Caption); const int margin = 16; return base + margin; } If the button has different font, for example it is bold, this is not accurate. I tried to create a new TCanvas: int GetButtonTextWidth(TForm* form, TButton* btn) { std::unique_ptr<TCanvas> canvas(new TCanvas); canvas->Font = btn->Font; const int base = canvas->TextWidth(btn->Caption); const int margin = 16; return base + margin; } This gives exception: "Canvas does not allow drawing". How do I create a TCanvas that allows measuring text width and gives accurate results?
The VCL has a TControlCanvas class for associating a Canvas with a UI control. int GetButtonTextWidth(TButton* btn) { std::unique_ptr<TControlCanvas> canvas(new TControlCanvas); canvas->Control = btn; canvas->Font = btn->Font; const int base = canvas->TextWidth(btn->Caption); const int margin = 16; return base + margin; }
69,626,335
70,359,263
How to implement Cryptarithmetic using Constraint Satisfaction in C++
I'll start by explaining what a cryptarithmetic problem is, through an example: T W O + T W O F O U R We have to assign a digit [0-9] to each letter such that no two letters share the same digit and it satisfies the above equation. One solution to the above problem is: 7 6 5 + 7 6 5 1 5 3 0 There are two ways to solve this problem, one is brute force, this will work but it's not the optimal way. The other way is using constraint satisfaction. Solution using Constraint Satisfaction We know that R will always be even because its 2 * O this narrows down O's domain to {0, 2, 4, 6, 8} We also know that F can't be anything but 1, since F isn't an addition of two letters, it must be getting its value from carry generated by T + T = O This also implies that T + T > 9, only then will it be able to generate a carry for F; This tells us that T > 4 {5, 6, 7, 8, 9} And as we go on doing this, we keep on narrowing down the domain and this helps us reduce time complexity by a considerable amount. The concept seems easy, but I'm having trouble implementing it in C++. Especially the part where we generate constraints/domain for each variable. Keep in mind that there are carries involved too. EDIT: I'm looking for a way to generate a domain for each variable using the concept I stated.
Here is how I solved it using backtracking My approach here was to smartly brute force it, I recursively assign every possible value [0-9] to each letter and check if there is any contradiction. Contradictions can be one of the following: Two or more letters end up having the same value. Sum of letters don't match the value of the result letter. Sum of letters is already assigned to some letter. As soon as a contradiction occurs, the recursion for that particular combination ends. #include <bits/stdc++.h> using namespace std; vector<string> words, wordOg; string result, resultOg; bool solExists = false; void reverse(string &str){ reverse(str.begin(), str.end()); } void printProblem(){ cout<<"\n"; for(int i=0;i<words.size();i++){ for(int j=0;j<words[i].size();j++){ cout<<words[i][j]; } cout<<"\n"; } cout<<"---------\n"; for(int i=0;i<result.size();i++){ cout<<result[i]; } cout<<"\n"; } void printSolution(unordered_map<char, int> charValue){ cout<<"\n"; for(int i=0;i<words.size();i++){ for(int j=0;j<words[i].size();j++){ cout<<charValue[wordOg[i][j]]; } cout<<"\n"; } cout<<"---------\n"; for(int i=0;i<result.size();i++){ cout<<charValue[resultOg[i]]; } cout<<"\n"; } void solve(int colIdx, int idx, int carry, int sum,unordered_map<char, int> charValue, vector<int> domain){ if(colIdx<words.size()){ if(idx<words[colIdx].size()){ char ch = words[colIdx][idx]; if(charValue.find(ch)!=charValue.end()){ solve(colIdx + 1, idx, carry, sum + charValue[ch], charValue, domain); } else{ for(int i=0;i<10;i++){ if(i==0 && idx==words[colIdx].size()-1) continue; if(domain[i]==-1){ domain[i] = 0; charValue[ch] = i; solve(colIdx + 1, idx, carry, sum + i, charValue, domain); domain[i] = -1; } } } } else solve(colIdx + 1, idx, carry, sum, charValue, domain); } else{ if(charValue.find(result[idx])!=charValue.end()){ if(((sum+carry)%10)!=charValue[result[idx]]) return; } else{ if(domain[(sum + carry)%10]!=-1) return; domain[(sum + carry)%10] = 0; charValue[result[idx]] = (sum + carry)%10; } carry = (sum+carry)/10; if(idx==result.size()-1 && (charValue[result[idx]]==0 || carry == 1)) return; if(idx+1<result.size()) solve(0, idx+1, carry, 0, charValue, domain); else{ solExists = true; printSolution(charValue); } } } int main() { unordered_map<char, int> charValue; vector<int> domain(10,-1); int n; cout<<"\nEnter number of input words: "; cin>>n; cout<<"\nEnter the words: "; for(int i=0;i<n;i++){ string inp; cin>>inp; words.push_back(inp); } cout<<"\nEnter the resultant word: "; cin>>result; printProblem(); wordOg = words; resultOg = result; reverse(result); for(auto &itr: words) reverse(itr); solve(0, 0, 0, 0, charValue, domain); if(!solExists) cout<<"\nNo Solution Exists!"; return 0; }
69,626,935
69,660,384
Error building Qt6 where to find error log?
I'm trying to build Qt 6.2 from sources with VS2019 under Win10. I followed the steps described in https://doc.qt.io/qt-6/windows-building.html: > set QTDIR=C:\dev\qt6\qt-everywhere-src-6.2.0 > cd %QTDIR% > set PATH=%QTDIR%\qtbase\bin;%PATH% > set PATH=C:\dev\qt6\Python39;%PATH% > set PATH=C:\dev\qt6\perl\perl\bin;%PATH% > set PATH=C:\dev\qt6\cmake-3.21.3-windows-x86_64\bin;%PATH% > configure -debug-and-release > cmake --build . --parallel It builds form some time and then ends up showing: Remarque : inclusion du fichier : C:\dev\qt6\qt-everywhere-src-6.2.0\qtbase\include\QtCore/qsize.h Remarque : inclusion du fichier : C:\dev\qt6\qt-everywhere-src-6.2.0\qtbase\include\QtCore/qrect.h Remarque : inclusion du fichier : C:\dev\qt6\qt-everywhere-src-6.2.0\qtbase\include\QtCore/qxmlstream.h Remarque : inclusion du fichier : C:\dev\qt6\qt-everywhere-src-6.2.0\qtbase\include\QtSvg/qtsvgglobal.h Remarque : inclusion du fichier : C:\dev\qt6\qt-everywhere-src-6.2.0\qtbase\include\QtSvg\qtsvgversion.h [3721/15034] Automatic MOC for target Qml ninja: build stopped: subcommand failed. That is not very verbose....where should I lookup to get more information about the failure? What subcommand failed?
When building in parallel Ninja does not stop output just after an error, so an error description can reside far before the log end. Besides, if your console window buffer size is small, an error description can be completely re-written by a later output. So, you can: Increase console buffer Build Search (CTRL+F) for the string: FAILED: or Redirect the build output to a file Search for the string: FAILED:
69,626,953
69,630,163
Fix warning: 'Foo::fooObj1' should be initialized in the member initialization list [-Weffc++]
foo.h #ifndef FOO_H #define FOO_H class Foo { int fooObj1; bool fooObj2; public: Foo(int input1); }; #endif foo.cpp #include "foo.h" Foo::Foo(int input1) { fooObj1 = input1; // some code logic to decide the value of fooObj2 (an example) // so I can't really do member initialization list. fooObj2 = (fooObj1 % 2 == 0); } So I was following a tutorial and they told me to turn on [-Weffc++] and treat warnings as errors. But when I do that, [-Weffc++] give a warning: 'Foo::fooObj1' should be initialized in the member initialization list [-Weffc++] and 'Foo::fooObj2' should be initialized in the member initialization list [-Weffc++]. But I can't really do member initialization list in this project. So how can I reslove this warning?
Two solutions to get rid of the warning. Solution 1 Make some static method, say CalculateFooObj2InitialValue, and use it in member initialization list. Foo::Foo(int input1): fooObj1(input1), fooObj2(CalculateFooObj2InitialValue(input1)) { ... } Solution 2 Initialize fooObj2 with a default, yet not quite meaningful, value in member initialization list. And then calculate a meaningful initial value later and assign. Foo::Foo(int input1): fooObj1(input1), fooObj2{} { // some code logic to decide the value of fooObj2 (an example) // so I can't really do member initialization list. fooObj2 = (fooObj1 % 2 == 0); }
69,627,207
69,642,459
Boost.Test - How to write a test that doesn't run automatically
A project I am working on uses continuous integration (CI) system that automatically builds and runs all test suites. Auto tests are run without any command line arguments. I would like to add long running tests into existing suites and I don't want those test to be trigger by CI. What is the proper way to add tests that don't run automatically? I am thinking to use custom command line arguments. Is there more explicit way to do it?
See Enabling or disabling test unit execution. Essentially, BOOST_AUTO_TEST_CASE(test1, * boost::unit_test::disabled()) { ... } If you run without parameters, it will not execute. With --run_test=test1 or --run_test=*, it still will execute.
69,627,248
69,627,339
takes one float value and immediately ends the program in template c++
okay so I have a question where im required to take user input of two int or float and then find the maximum and minimum of those two numbers. my if loop for int works fine, but for the float , it takes one float value and immediately ends the program. can anyone help me with this error? here's my code: #include <iostream> using namespace std; template <class T> class mypair { T a; T b; public: mypair(T a=0, T b=0) { this->a=a; this->b=b; } void setFirst(T a) { this->a = a; } T getFirst() { return a; } void setSecond(T b) { this->b = b; } T getSecond() { return b; } T getmax(); T getmin(); }; template <class T> T mypair<T>::getmax() { T retval; retval = getFirst() > getSecond() ? getFirst() : getSecond(); return retval; } template <class T> T mypair<T>::getmin() { T min; min = getFirst() < getSecond() ? getFirst() : getSecond(); return min; } int main() { char opt; cout << "program to find a minimum and maximum" << endl; cout << "--------------------------------------------" << endl; cout << "Do you want to type in two integers or two floats ?"<<endl; cout << "(i for integer , f for float)"<<endl; cin >> opt; if (opt == 'i' || opt == 'I') { mypair<int> myobject; int int1, int2; cout << "Enter first INT = "; cin >> int1; myobject.setFirst(int1); cout << "Enter second INT = "; cin >> int2; myobject.setSecond(int2); cout << "---------------------------------------" << endl; int choice; cout << "Find Maximum or Minimum?" << endl; cout << "(1 for maximum ,0 for minimum)" << endl; cin >> choice; if (choice == 0) { cout << myobject.getmin(); } if (choice == 1) { cout << myobject.getmax(); } } if (opt == 'f' || opt == 'F') { mypair <float> myobject1; int fl1, fl2; cout << "Enter first FlOAT = "; cin >> fl1; myobject1.setFirst(fl1); cout << "Enter second FLOAT = "; cin >> fl2; myobject1.setSecond(fl2); cout << "---------------------------------------" << endl; int choice; cout << "Find Maximum or Minimum?" << endl; cout << "(1 for maximum ,0 for minimum)" << endl; cin >> choice; if (choice == 0) { cout << myobject1.getmin(); } if (choice == 1) { cout << myobject1.getmax(); } } return 0; }
In if (opt == 'f' || opt == 'F') you declared numbers as int, not as float.
69,627,288
69,627,407
Earliest support of __alignof__ in GCC
I need a portable way to determine alignment requirements of a structure, where portability includes legacy versions of GCC. Parts of project are stuck with embedded platforms supporting pre-C++11 standard only, as early as GCC v.3.6. There is a non-ISO __alignof__ (a macro? a function?) analog of C++11 operator alignof which I can use, but what is the earliest version of GCC compiler would support it? Were there alternatives or changes in naming?
The oldest version of GCC with documentation available online at gcc.gnu.org is 2.95.3. That version does support __alignof__ extension.
69,627,667
69,628,077
Skip function params calculation if first param less than threshold
I have a function like this: void WriteLog(int severity, ...); And it is used in a next way: WriteLog(2, "%d\n", SomeHugeCalculations()); But in case the application is configured to write logs only with severity > 2, execution of SomeHugeCalculations() is redundant. I think it can be solved by wrapping it into a macro like this: WRITE_LOG(severity, ...) if(severity <= threshold) WriteLog(severity, __VA_ARGS__) But... Are there other(modern?) approaches to solve the issue?
The approach with macro can be ported C but problematic in form you did it. Consider this code: if ( logging ) WRITE_LOG(1, "Starting program"); else printf("Hello world!"); Non-isolated if-statement in macro causes "Hello world!" being printed if logging is true and if 1 is less than threshold because else is actually related to the hidden if-statement. With C++ inlined\templated code is way to go. Much better if you would design some kind of centralized subsystem for the logger. PS. If C compatibility required, macro wrappers would look something similar to following: #define WRITENGINE /** here goes a variadic interface to logger */ // this is one of ways to isolate code within #define STATEMENT(...) do { __VA_ARGS__ } while(0) #define WRITEF(sev, fmt, ...) STATEMENT( if(sev > threshold) WRITENGINE (fmt, __VA_ARGS__); ) do { __VA_ARGS__ } while(0) would behave like a singular statement and will be optimized out while preventing compiler to generate warning about extra ; or causing issues with contained code or enclosing flow-control statements. It may wrap up several statements.
69,627,728
69,637,366
OpenSSL 3.0.0 include files difference official release conan vs github
I'm building an app for both Windows, Linux and Android in c++. As with many third party dependencies, the windows and linux binaries are to be found on conan (which I use for dep management) but Android is not. This is usually not a big issue, building one extra library from source. However for OpenSSL I have the suspicion that the 3.0.0 release on the official conan center registry differs from the official 3.0.0 source released on github. A very simple diff suffices: diff /path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl /path/to/Downloads/openssl-openssl-3.0.0/include/openssl Only in /path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl/: asn1.h Only in /path/to/Downloads/openssl-openssl-3.0.0/include/openssl/: asn1.h.inOnly in /path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl/: asn1t.h Only in /path/to/Downloads/openssl-openssl-3.0.0/include/openssl/: asn1t.h.in Only in path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl/: bio.h Only in /path/to/Downloads/openssl-openssl-3.0.0/include/openssl/: bio.h.in Only in /path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl/: cmp.h Only in /path/to/Downloads/openssl-openssl-3.0.0/include/openssl/: cmp.h.in diff /path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl/cmperr.h /path/to/Downloads/openssl-openssl-3.0.0/ds/openssl-openssl-3.0.0-beta1/openssl-openssl-3.0.0-beta1/include/openssl/cmperr.h 64d63 < # define CMP_R_MISSING_CERTID 165 105d103 < # define CMP_R_WRONG_CERTID 189 Only in /path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl/: cms.h Only in /path/to/Downloads/openssl-openssl-3.0.0/include/openssl/: cms.h.in Only in /path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl/: conf.h Only in /path/to/Downloads/openssl-openssl-3.0.0/include/openssl/: conf.h.inOnly in /path/to/.conan/data/openssl/3.0.0/_/_/package/<hash>/include/openssl/: configuration.h ... Should be equal, right? It's not. What version of OpenSSL is uploaded to conan? How do I get the matching Android version? Or do I have to go through the trouble of building for Windows and Linux as well?
For the version you are downloading it looks like it is 3.0.0-beta1, while ConanCenter packages 3.0.0. Indeed, the beta version doesn't define CMP_R_MISSING_CERTID while the released one does. Maybe it is just a version mismatch? The diff is huge https://github.com/openssl/openssl/compare/openssl-3.0.0-beta1...openssl-3.0.0 and it contains those changes your report in cmperr.h file.
69,628,131
69,628,227
-Wundef does not warn about an undefined symbol in front of #ifdef
Please consider the following code: // program.cpp #include <iostream> int main() { #ifdef LINUX std::cout << "Linux\n"; #elif MAC std::cout << "Mac\n"; #elif WINDOWS std::cout << "Windows\n"; #elif BSD std::cout << "BSD\n"; #else std::cout << "Something else\n"; #endif return 0; } If I compile it with both clang and gcc, clang++ -Wundef -DBSD -o program program.cpp # or g++ -Wundef -DBSD -o program program.cpp I will get warnings for not defining symbols MAC and WINDOWS, but no warning for the symbol LINUX: program.cpp:6:7: warning: 'MAC' is not defined, evaluates to 0 [-Wundef] #elif MAC ^ program.cpp:8:7: warning: 'WINDOWS' is not defined, evaluates to 0 [-Wundef] #elif WINDOWS ^ 2 warnings generated. According to the gcc man page: -Wundef Warn if an undefined identifier is evaluated in an "#if" directive. Such identifiers are replaced with zero. It says in an #if directive. Is it because the LINUX is not inside that structure? If that's the case, how can I tell compiler to emit warnings for the undefined symbol LINUX? clang version 12.0.1 gcc (GCC) 11.1.0 Target: x86_64-pc-linux-gnu (artixlinux)
The reason is that your preprocessor code asks if LINUX is defined. But for MAC, WINDOWS and BSD you don’t bother checking whether the symbol is defined; instead, your code assumes it is defined and asks for its value. Change your code to use #elif defined(…) instead of #elif … to fix the warning.
69,628,241
69,632,024
Where can I put my SQLite database in my QT application if I can't put it in my resources?
Recently I was trying to put a SQLite database into a QT 5 application I'm writing. I want it to be universally accessible - that is on all systems regardless of where it's installed. I put it as a resource then found out that evidently you can't put databases in resources as the string for the database path passed to setDatabaseName doesn't get translated to the resource system so the database can't be found. So where can I put it? I don't want to just put it at the root of the drive like C:\repo.db or D:\repo.db as many people hate files cluttering their root directories (like me). I was going to put it just in the source folder and access it as "repo.db" or as I tried "./resources/database/repo.db" but even QFile doesn't see that. Where can I put it and how to access it there? My settings file was going to be in my resources but I wasn't sure if I could update the file then. I need a place that is available from the moment the application is installed on any system including my own so that it can be accessed both while coding it and when it's built. I'm not asking for opinions - I want a place that is not in the root, somewhere universal like the installation directory (but how do I find that with code?) or a settings directory (but how do I set that somewhere so I can find it later??)
For such purposes Qt provides a list of QStandardPaths functions that return platform specific standard paths, such as a path to desktop, temp directory etc. For your particular case you might put your database in the directory that corresponds to the QStandardPaths::AppDataLocation key.
69,628,509
69,628,642
Initializing integer with leading zeroes gives unexpected result (C++)
Problem summary Assume that for some reason one tries to store the integer 31 as int num = 0031; If I print out num I get 25 instead. If I use cin however, the number stored is indeed 31. You can verify this by running the following code and type 0031 when prompted. Code #include <iostream> using namespace std; int main() { cout << "Version 1\n========="<< endl; { int num = 0031; cout << "Input was: " << num << endl; }cout << "=========" << endl; cout << "Version 2\n========="<< endl; { int num; cout << "Insert num: "; cin >> num; cout << "Input was: " << num << endl; }cout << "=========" << endl; return 0; } Searching for the answer, I found this one Int with leading zeroes - unexpected result Is it the same case in C++? Namely, integers with leading zeroes are stored as octal integers? And why does the second block give the expected result? Is it because when using cin the stream is stored as string and then the stoi() function is implicitly used?
For integer literals in C++ see eg here: https://en.cppreference.com/w/cpp/language/integer_literal. Yes, 0031 is an octal integer literal. To get expected output from the second version of your code you can use the std::oct io-manipulator: int num; cout << "Insert num: "; cin >> std::oct >> num; cout << "Input was: " << num << endl;
69,629,967
69,759,857
C++17 PMR:: Set number of blocks and their size in a unsynchronized_pool_resource
Is any rule for setting in the most effective way the number of blocks in a chunk (max_blocks_per_chunk) and the largest required block (largest_required_pool_block), in a unsynchronized_pool_resource? How to avoid unnecessary memory allocations? For example have a look in this demo. How to reduce the number of allocation that take place as much as possible?
Pooled allocators function on a memory waste vs upstream allocator calls trade-off. Reducing one will almost always increase the other and vice-versa. On top of that, one of the primary reason behind their use (in my experience, at least) is to limit or outright eliminate memory fragmentation for long-running processes in memory-constrained scenarios. So it is sort of assumed that "throwing more memory at the problem" is going to be counterproductive more often than not. Because of this, there is no universal one-size-fit-all rule here. What is preferable will invariably be dictated by the needs of your application. Figuring out the correct values for max_blocks_per_chunk and largest_required_pool_block is ideally based on a thorough memory usage analysis so that the achieved balance benefits the application as much as possible. However, given the wording of the question: How to avoid unnecessary memory allocations? How to reduce the number of allocation that take place as much as possible? If you want to minimize upstream allocator calls as much as possible, then it's simple: Make largest_required_pool_block the largest frequent allocation size you expect the allocator to face. Larger blocks means more allocations will qualify for pooled allocation. Make max_blocks_per_chunk as large as you dare, up to the maximum number of concurrent allocations for any given block size. More blocks per chunks means more allocations between requests to the upstream. The only limiting factor is how much memory footprint bloat you are willing to tolerate for your application.
69,630,292
69,632,567
Why is this code printing aa0 as an element in set although aa is not a substring of ab?
strong text #include <iostream> #include<set> #include <string> #include <string_view> #include <boost/algorithm/string.hpp> using std::string; using std::cout; using std::cin; using std::endl; int main() { long int t; cin>>t; while(t--) { string s1,s2,x,a,b,f; cin>>s1>>s2>>x; std::set<string> s; int n,m,A; n=s1.length(); m=s2.length(); for(int i=0;i<n;i++) { a=s1.substr(0,i+1); if(boost::algorithm::contains(x, a)); { s.insert(a+"0"); } for(int j=0;j<m;j++) { b=s2.substr(0,j+1); if(boost::algorithm::contains(x,b)) { s.insert("0"+b); } f=a+b; if(boost::algorithm::contains(x,f)) { s.insert(f); } } } cout<<(s.size())+1<<endl; for (auto it = s.begin(); it != s.end(); ++it) cout << endl << *it; /*A=boost::algorithm::contains(x,"aa0"); cout<<A;*/ } return 0; } **Given 3 strings S1, S2 and X, find the number of distinct ordered pairs of strings (P,Q) such that : String P+Q is a substring of X. String P is some prefix of S1 (possibly empty). String Q is some prefix of S2 (possibly empty). A substring of a string is a contiguous subsequence of that string. For example, "chef" is a substring of "codechef", but "def" is not. Also, an empty string is a substring of any string. A prefix of a string S is a substring of S that occurs at the beginning of S. For example, "code" is a prefix of "codechef", but "chef" is not. Also, an empty string is a prefix of any string.** **My approach-slicing the string s1 and s2 using substr function and then checking whether there are substring of x using a algorithm or boost function i have used s.insert(a+"0") it just signifies that a is a prefix of s1 string and we have taken null prefix i.e. "" from s2. Same s.insert(""+b) means null prefix from string s1 and b prefix from s2 and so on. ****Problem - It is giving wrong output for one inputset dont know why. Debug it and see the pic https://i.stack.imgur.com/zUm5O.png **
I cleaned up your main function a little and removed boost usage (since you don't really need it here). I've also removed your namespace declarations as that is a bad idea. Lastly, I replaced your boost usage with a simple string::find. You can find the live example here. The output is : 4 0b a0 ab The updated main() is below with your example set, instead of using std::cin. #include <iostream> #include <set> #include <string> int main() { long int t{1}; while(t--) { std::string s1{"aa"},s2{"bb"},x{"ab"},a{""},b{""},f{""}; std::set<std::string> s; int n,m,A; n=s1.length(); m=s2.length(); for(int i=0;i<n;i++) { a=s1.substr(0,i+1); if(x.find(a) != std::string::npos) { s.insert(a+"0"); } for(int j=0;j<m;j++) { b=s2.substr(0,j+1); if(x.find(b) != std::string::npos) { s.insert("0"+b); } f=a+b; if(x.find(f) != std::string::npos) { s.insert(f); } } } std::cout<<(s.size())+1<<std::endl; for (auto it = s.begin(); it != s.end(); ++it) std::cout << std::endl << *it; /*A=boost::algorithm::contains(x,"aa0"); cout<<A;*/ } return 0; }
69,630,735
69,630,865
Why does compiler treat class as abstract?
I tried to compile the program, but compiler treats ParameterExpr class as abstract. I did not work with multiple inheritance and I thought that it should be work (because get_type was actually implemented in Expr class) class IMetaExpression { public: virtual int get_type(void) = 0; virtual ~IMetaExpression(){} }; class IParameterExpression : public IMetaExpression { public: virtual char get_parameter(void) = 0; }; class Expr : public IMetaExpression { public: virtual int get_type(void) override { return 0; } }; class ParameterExpr : public Expr, public IParameterExpression { public: virtual char get_parameter(void) override { return 'c';} //virtual int get_type(void) override { return 0; } }; int main() { auto p = new ParameterExpr(); p->get_type(); delete p; return 0; }
I believe this is an issue called the diamond problem. https://www.geeksforgeeks.org/multiple-inheritance-in-c/ This is where two classes inherit fully or partially from a base class, which then also has a child class inheriting both of these classes. Creating a diamond shape. The solution to this is adding virtual to the inheritance of the two middle classes. Resulting in: class IParameterExpression : virtual public IMetaExpression and class Expr : virtual public IMetaExpression This allows the constructor of the base class to be called only once and sharing functionality between all inherited classes. I am not an expert on the diamond problem, so more clarification is appreciated.
69,630,902
69,631,175
Microsoft Visual Studio - Why am I getting this error?
I am so confused what is causing this error code, can anyone point out what is wrong? #include <iostream> main() { int x; std::cin >> x; std::cout << "Answer is " << x + x << '\n'; return 0; }
You missed function type specifier. It should be like this int main() { //... }
69,631,475
69,632,184
Can't get an item from tableWidget in QT
I have the function like this below, and global QVector<pid_t> pid; in the header file which elements are Linux process ids. But when I'm trying to push the button "priority" - programm unexpectedly finishes. Due to qDebugs I've realized that function interrupts after if statement. And I can not understand the matter of this problem. Function: void MainWindow::on_priority_clicked() { int curI = ui->tableWidget->currentRow(); int prio = ui->prioritySpinBox->value(); try{ if(ui->tableWidget->item(curI,1)->text().isNull()) throw curI; else { setpriority(PRIO_PROCESS, pid.at(curI),prio); QLabel *labelPrio = new QLabel(ui->tableWidget); labelPrio->setText(QString::number(getpriority(PRIO_PROCESS, pid.at(curI)))); ui->tableWidget->setCellWidget(curI, 3, labelPrio); } } catch(int x) { QMessageBox::warning(this, "Error", "Process " + QString::number(x+1) + " is not created"); } }
Not sure if this is your problem, but if ui->tableWidget->item(curI,1) doesn't exist (or is null), then calling ->text() on it will cause a crash. You might need to check if it exists first: void MainWindow::on_priority_clicked() { int curI = ui->tableWidget->currentRow(); int prio = ui->prioritySpinBox->value(); try{ if(ui->tableWidget->item(curI,1) != nullptr) ....
69,631,754
69,632,315
How to avoid bitwise operations outside the width of the data type in c++
For sake of experiment lets have a function that takes in a bitmask and offset and returns the mask shifted by offset. What would be a performance friendly way to determine if the operation will not shift any parts of the bitmask past the width of the data type? This is what I've tried so far, but maybe there is more optimal way to check this? Example program: (Note: I'm looking for a solution for all data types, not only 16 bit integers) #include <iostream> using namespace std; uint16_t TestFunc(uint16_t offset, uint16_t mask) { if (offset >= sizeof(uint16_t) * 8) throw std::exception("Offset outside bounds"); // find the index of the left-most bit in the mask int16_t maskLeftBitIndex = 0; uint16_t maskCopy = mask; while (maskCopy >>= 1) maskLeftBitIndex++; // check if the said left-most bit will be shifted past the width of uint16_t if (offset + maskLeftBitIndex >= sizeof(uint16_t) * 8) throw std::exception("Mask will end up outside bounds"); return mask << offset; } int main() { try { uint16_t test = TestFunc(15, 2); cout << "Bitmask value: " << test; } catch (std::exception& e) { cout << "Exception encountered: " << e.what(); } return 0; }
Not sure would this be faster, but you can check whether before and end value have same number of bits set uint16_t TestFunc(uint16_t offset, uint16_t mask) { if (offset >= std::numeric_limits<uint16_t>::digits) throw "Offset outside bounds (Possible Undefined Behavior)"; uint16_t result = mask << offset; if(std::popcount(mask)!=std::popcount(result)) throw "Offset outside bounds"; return result; }
69,632,040
69,642,848
My program prints the output occasionally although it is correctly compiled?
My program here is to randomly assign the variables (number1, number2, number3, number4) to a number stored in vector <int> number. I want to make sure each number will appear only 1 time Here is my code : #include <iostream> #include <vector> #include <random> #include <ctime> using namespace std; int main() { srand(time(NULL)); vector<int> number = { 5, 6, 7, 8 }; int number1, number2, number3, number4; do { number1 = number[rand() % 4]; number2 = number[rand() % 4]; number3 = number[rand() % 4]; number4 = number[rand() % 4]; if (number2 != number1) { if (number3 != number1 && number3 != number2) { if (number4 != number1 && number4 != number2 && number4 != number3) { cout << number1 << number2 << number3 << number4; } } } } while ((number1 + number2 + number3 + number4) != 26); } Sometimes it does print the right outputs to the terminal, but sometimes it just doesn't print anything and the program is terminated. I don't know why this happens, can anybody suggest me a solution ?
I want to make sure each number will appear only 1 time Rather than picking an index, you can shuffle the selection. #include <iostream> #include <vector> #include <random> int main() { std::vector<int> number = { 5, 6, 7, 8 }; std::shuffle(number.begin(), number.end(), std::random_device{}); std::cout << number[0] << " " << number[1] << " " << number[2] << " " << number[3] << std::endl; }
69,632,042
69,632,112
not getting same output via user defined function
I was trying something in Cpp, but not getting same output when I used the same thing in a user defined function CODE #include <iostream> using namespace std; int sum(int x, float y){ return (x / y); } int main(){ int a; float b, c; a = 12; b = 5; c = a / b; cout << sum(12, 5) << endl; cout << c; } OUTPUT 2 2.4 Why am I not getting 2.4 in both the cases?
The return value of sum is int. #include <iostream> using namespace std; int sum(int x, float y){ return (x / y); //<< this is an int } int main(){ int a; float b, c; a = 12; b = 5; c = a / b; << this is a float cout << sum(12, 5) << endl; //<< prints an int cout << c; //<< prints a float }