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,873,264
69,874,677
no output from function after cout another string before
to refresh my rusty c++ knowledge i have created a small program. however, a small problem occurs. I get the output of a commando into a vector. afterwards I output the content of the vector again. if i now output something before the output of the vector content, then interestingly the output of the vector no longer appears. Why is this so? #include <iostream> #include <cstdio> #include <memory> #include <stdexcept> #include <string> #include <array> #include <vector> using namespace std; const vector<string>& execv(const char* cmd); void output(const vector<string>& vec); int main() { const vector<string>& result = execv("net user %USERNAME%"); int _numlines = result.size(); // if i uncomment the following line there's no output from 'output' //cout << _numlines << " lines had been found: " << endl; output(result); return 0; } void output(const vector<string>& vec) { for(const string& line : vec) cout << line; } const vector<string>& execv(const char* cmd) { array<char, 128> buffer; vector<string> result; //string result; unique_ptr<FILE, decltype(&pclose)> pipe(_popen(cmd, "r"), _pclose); if(!pipe) { throw runtime_error("_popen() failed!"); } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result.push_back(buffer.data()); } const vector<string>& _res = result; return _res; }
Like others say, don't return reference to local variable. Live On Coliru #include <array> #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <vector> using Strings = std::vector<std::string>; Strings execv(std::string cmd); void output(const Strings& vec); int main() { auto result = execv("net user %USERNAME%"); std::cout << result.size() << " lines had been found: " << std::endl; output(result); } void output(const std::vector<std::string>& vec) { for (auto& line : vec) std::cout << line; } #include <stdexcept> Strings execv(std::string cmd) { Strings result; std::array<char, 128> buffer; //string result; std::unique_ptr<FILE, decltype(&pclose)> pipe(::popen(cmd.c_str(), "r"), ::pclose); if (!pipe) { throw std::runtime_error("popen() failed!"); } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result.push_back(buffer.data()); } return result; } Which on my Linux machine prints Invalid command: net rap user %USERNAME% 4 lines had been found: Usage: net rap user add Add specified user net rap user info List domain groups of specified user net rap user delete Remove specified user
69,873,399
69,874,630
why there is a .lib file when create dynamic .dll file?
I'm try to build a dynamic dll library on on windows using visual studio, but there are two file generated, one is dll file, another is .lib file; My knowledege of using dll library is privode it to linker, I don't know what is ther purpose of .lib file, it has the same file extension as static lib, and it definitely is not static lib; Does visual studio generate a .lib file when create dynamic dll library at all situtation? Do I need to use the .lib file in my application? How do I do use the .lib file in my application?
It has to do with the difference between "implicit" linking and "explicit" linking. The one sentence answer to your question is that that .lib file, often called a "stub lib" and officially called an "import library", is necessary when you do implicit linking but not otherwise. In implicit linking, at compile time the compiler generates external function references for calls into the DLL, then the linker needs to link those to something: it uses the import library to help it do that. The linker treats these calls as special cases; it inserts code in the executable file for finding the DLL and for calling into the DLL for specific functions. From the point-of-view of the programmer, implicit linking behaves like static linking except the DLL needs to be somewhere where the system can find it when the application is run or the system will pop up an error dialog at application startup. Explicit linking means that it is the programmer's responsibility to find and load the DLL and to know what functions are in the DLL and how to call into them. See LoadLibrary and GetProcAddress for details. Explicit linking is useful if usage of a library is conditional or for applications with plugin architectures in which the actual DLLs to be used may not even be known at compile time. In general though, if implicit linking does what you need, it is easier to just do it that way.
69,873,530
69,873,668
Check the presence of a number in an array with binary search
I have a test assessment that I need to do. There is one question that I have been having trouble with. I have an array of numbers and I need to find a way to find that number in the array, which I have partially done. The problem becomes in the next step of the project which is that it has to accommodate a million items. I believe this is binary search. How do I do a binary search or equivalent? #include <iostream> #include <sys/resource.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <algorithm> #include <vector> using namespace std; class Answer { public: static bool exists(int ints[], int size, int k) { for(int i=0; i<size; i++){ if(ints[i]<k){ return true; } } return false; } }; The images below gives an idea of what I need and my code What I need:
Why don't you just use standart lib function? static bool exists(int ints[], int size, int k) { return std::binary_search(ints, ints + size, k); }
69,873,685
69,873,716
How to randomly pick element from an array with different probabilities in C++
Suppose I have a vector<Point> p of some objects. I can pick a uniformly random by simply p[rand() % p.size()]. Now suppose I have another same-sized vector of doubles vector <double> chances. I want to randomly sample from p with each element having a probability analogous to its value in chances (which may not be summing to 1.0). How can I achieve that in C++?
You are looking for std::discrete_distribution. Forget about rand(). #include <random> #include <vector> struct Point {}; int main() { std::mt19937 gen(std::random_device{}()); std::vector<double> chances{1.0, 2.0, 3.0}; // Initialize to same length. std::vector<Point> points(chances.size()); // size_t is suitable for indexing. std::discrete_distribution<std::size_t> d{chances.begin(), chances.end()}; auto sampled_value = points[d(gen)]; } Conveniently for you, the weights do not have to sum to 1.
69,874,119
69,874,452
Build a Linux c++ application runnable on system having libc >= 2.31
I would like to build a C++ application which can be launched on all Linux systems having libc >= 2.31. On my build system (Ubuntu), I have libc 2.34. Here is my (empty) application: int main() { return 0; } I built it with g++ -o app app.cpp and according to the following result, I understand that my application requires libc >= 2.34 to run. Is my understanding correct ? $ nm -D app w __cxa_finalize@GLIBC_2.2.5 w __gmon_start__ w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable U __libc_start_main@GLIBC_2.34 How build my application for libc <= 2.31 ? I tried to add "__asm__ (".symver __libc_start_main, __libc_start_main@GLIBC_2.2.5");" (based on my understanding of this post) before my main method but it does not change anything.
Docker image ubuntu:20.04 has libc 2:31 installed. You could compile your application there: $ docker run --rm -v $PWD:/work -w /work ubuntu:20.04 bash -c 'apt-get update && apt-get -y install g++ && g++ -o app app.cpp' $ docker run --rm -v $PWD:/work -w /work ubuntu:20.04 ./app $ ./app $ nm -D app w _ITM_deregisterTMCloneTable w _ITM_registerTMCloneTable w __cxa_finalize@GLIBC_2.2.5 w __gmon_start__ U __libc_start_main@GLIBC_2.2.5 You could link your application statically, remove all dependencies on standard library. You could distribute your application with libc library together.
69,874,874
70,512,188
Correct way to use PtrUseVisitor Class in LLVM
So I found the InstVisitor class in LLVM, which was refreshing to traverse through the function and see instructions of my interest. A straightforward implementation that I was able to get it working is as follows: class MyInstVisitor : public InstVisitor <MyInstVisitor> { public: void visitLoadInst(Instruction &I) { errs() << "Load:\t" << I << "\n"; } }; Afterward, the usage case is as follows: void visitor(Function &F) { MyInstVisitor MAV; MAV.visit(F); for (auto &I : F) { errs() << I << "\n"; // this traverses a function through for loop } } After looking around further, I found a child class of InstVisitor, a PtrUseVisitor (https://llvm.org/doxygen/classllvm_1_1PtrUseVisitor.html) that I wanted to use (as I wish to visit all of the users of a pointer value after locating the llvm::LoadInst). However, I am stuck trying to find a way to use this correctly. I have tried a variety of things, to summarize: PtrUseVisitor cannot be instantiated like InstVisitor as the template looks like this: llvm::PtrUseVisitor<DerivedT> I have also tried doing something like llvm::PtrUseVisitor<Instruction>::visitPtr(), which is incorrect. I think I'm missing something regarding how to use the child class of inheritance, but examples I could find are related to elementary things (such as inheriting from class Animal, for instance) And many more... just a bit lost at the moment. My main goal is to use the following member function: PtrUseVisitor::visitPtr(). Can anyone help with providing me with an example of how to use this? I appreciate any help you can provide.
Take a look at the SROA pass, which defines a class AllocaSlices::SliceBuilder which inherits from PtrUseVisitor. If you look in that class for calls to Base:: methods, those are making using of PtrUseVisitor.
69,875,081
69,875,376
C++ garbage collection
There are a number of garbage collection libraries for C++. I am kind of confused how the pointer tracking works. In particular, suppose we have a base pointer P and a list of other pointers who are computed as offsets from P using an array. Ex, P2 = P+offset[0] How does the garbage collector know P2 is still in scope? It has no direct reference but it's still accessible. Probably the most popular C++ gc is https://en.m.wikipedia.org/wiki/Boehm_garbage_collector But following their example syntax it seems very easy to break so I must not be understanding something.
This question cannot be answered in general. There are different systems that may be regarded as garbage collection for C++; for example, Herb Sutter's deferred_ptr is basically a garbage collecting smart pointer. I've personally implemented another version of this idea, similar to Sutter's but less fancy. I can answer about Boehm, however. How the Boehm garbage collector recognizes pointers when it does its "mark" phase, is basically by scanning memory and assuming that things that look like pointers are pointers. The garbage collector knows all the areas of memory where user data is and it knows all of the pointers that it has allocated and how big those allocations were. It just looks for chains of pointers starting from "root segments" defined as below, where by "look" we mean explicitly scanning memory for 64 bit values that are the same as one of the GC allocations it has done. From here: Since it cannot generally tell where pointer variables are located, it scans the following root segments for pointers: The registers. Depending on the architecture, this may be done using assembly code, or by calling a setjmp-like function which saves register contents on the stack. The stack(s). In the case of a single-threaded application, on most platforms this is done by scanning the memory between (an approximation of) the current stack pointer and GC_stackbottom. (For Itanium, the register stack scanned separately.) The GC_stackbottom variable is set in a highly platform-specific way depending on the appropriate configuration information in gcconfig.h. Note that the currently active stack needs to be scanned carefully, since callee-save registers of client code may appear inside collector stack frames, which may change during the mark process. This is addressed by scanning some sections of the stack "eagerly", effectively capturing a snapshot at one point in time. Static data region(s). In the simplest case, this is the region between DATASTART and DATAEND, as defined in gcconfig.h. However, in most cases, this will also involve static data regions associated with dynamic libraries. These are identified by the mostly platform-specific code in dyn_load.c. The address space for 64-bit pointers is huge so false positives will be rare, but even if they occur, false positives would just be leaks, that last as long as there happens to be some other variable in the memory the mark phase scans that is exactly the same value as some 64-bit pointer that was allocated by the garbage collector.
69,875,165
69,934,612
c++ segmentation failed read in .csv file, memmove-vec-unaligned-erms.S: No such file or directory
My code should read in from ".csv" file given in the arguments, to a 2D vector table. Everytime I tried to run it it said "Segmentation fault (core dumped). I even tried to get it fiexed with gdb (g++ debugger) in console. The closest I've got to the promblem is this message: Program received signal SIGSEGV, Segmentation fault. __memmove_sse2_unaligned_erms () at ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:314 314 ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S: No such file or directory. I don't know what should I do to fix it. void Table::read_file(std::string f_str) { std::fstream file; std::string line; file.open(f_str, std::ios::in); if (!file) { incorrect_input(); } else { while (std::getline(file, line)) // first while to resize our 2d vector table { std::istringstream iss(line); std::string result; int cols = 1; while (std::getline(iss, result, sep)) { cols++; } if (getColumn() < cols) { setColumn(cols); } setRow(getRow() + 1); } file.clear(); file.seekg(0, std::ios_base::beg); int i = 0; int j = 0; while (std::getline(file, line)) // second while to get the records segmented in to our 2d vector table 'cells' { std::istringstream iss(line); std::string result; while (std::getline(iss, result, sep)) { cellcontainer[i][j] = result; j += 1; } i += 1; } } file.close(); } udpate: So the cellcontainer is a 2D vector table/matrix. It's constructed by a header file, main calls for it at the start of the code, after the ".csv" file is given through arguments. It contains the "cells" of the 2D vector table. And it looks like this in header: class Table { private: std::vector<std::vector<std::string>> cellcontainer; int row; int column; char sep = ';'; public: Table() : row(1), column(1) { cellcontainer.push_back(std::vector<std::string>()); cellcontainer[0].push_back("-"); } update_2: I rewrote this line cellcontainer[i][j] = result; To this cellcontainer.at(i).at(j) = result; And it says std::out_of_range
Thankfully for everyone but specially for Raymond Chen. solution was: At the first while() of my code I only kept the columns and rows of the class variables updated and did not even changed the size of my container of the 2D vectors (cellcontainer). Now it looks like this: while (std::getline(iss, result, sep)) { addColumn(1); // <-- addColumn() function arg is an int and it adds to our cellcontainer with resizing. cols++; } if (getColumn() < cols) { setColumn(cols); } setRow(getRow() + 1); addRow(1); // <-- addRow() function arg is an int and it adds to our cellcontainer with resizing
69,875,435
69,878,945
Probable bug in weak_ptr passed to a thread
In this code example, we pass a std::shared_ptr<int> to a thread, and expect it is weakened to a std::weak_ptr<int>. But in Visual Studio 2019, t takes a strong reference and the output of this program is "pw alive", in both debug and release builds. Same problem on linux with compiler g++ -lpthread. This toy example is motivated by the more serious case where thread t does some long computations, and then sends results through shared resources t receives as arguments. Those resources may be deleted by other threads during t's computation, in which case t becomes useless and can be terminated early. But because of this (suspected) bug, t keeps the resources alive and wastes memory and calculation time. Is this really a bug, or I am misunderstanding the relationship between weak_ptr and shared_ptr ? If this is a bug, do you know where to report it ? Probably at different places for Visual Studio and g++. #include <iostream> #include <string> #include <thread> #include <chrono> void TestWeakPtrAlive(std::weak_ptr<int> pw) { // wait for main thread to delete pw std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::shared_ptr<int> p = pw.lock(); std::cout << (p ? "pw alive" : "pw dead") << std::endl; } int main() { std::shared_ptr<int> p = std::make_shared<int>(18); std::thread t(TestWeakPtrAlive, p); p = nullptr; t.join(); return 0; }
Those implementations copy the shared_ptr. i.e. They copy the argument and tie it to the lifetime of the thread. Copying is the default for argument binding with thread creation. This wouldn't be considered a bug unless the standard said the implementation couldn't do that. As far as getting the behavior you want, I think you'd have the same problem if you used a lambda. Instead you could use a functor, or you could use some global or static variables. Here's your example converted to use a functor. The benefit is that you control the member variables. The downside is the boilerplate. #include <iostream> #include <string> #include <thread> #include <chrono> class TestWeakPtrAlive { std::weak_ptr<int> m_pw; public: TestWeakPtrAlive(std::weak_ptr<int> pw) : m_pw(std::move(pw)) {} void operator()() { // wait for main thread to delete pw std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::shared_ptr<int> p = m_pw.lock(); std::cout << (p ? "pw alive" : "pw dead") << std::endl; } }; int main() { std::shared_ptr<int> p = std::make_shared<int>(18); auto functor = TestWeakPtrAlive(p); std::thread t(std::move(functor)); p = nullptr; t.join(); return 0; } Edit: I just thought of a fairly obvious solution which would be to just create a weak_ptr and pass that to the thread constructor. #include <iostream> #include <string> #include <thread> #include <chrono> void TestWeakPtrAlive(std::weak_ptr<int> pw) { // wait for main thread to delete pw std::this_thread::sleep_for(std::chrono::milliseconds(1000)); std::shared_ptr<int> p = pw.lock(); std::cout << (p ? "pw alive" : "pw dead") << std::endl; } int main() { std::shared_ptr<int> p = std::make_shared<int>(18); std::weak_ptr<int> wp = p; std::thread t(TestWeakPtrAlive, std::move(wp)); p = nullptr; t.join(); return 0; }
69,875,512
69,876,085
Cannot assign any value greater 255 OpenCV
I tried to create a histogram but I cant assign any value greater 255, if it over example 256 it will be 0, and so on. How can I fix it? histMatrix = Mat(nChannelSource, 256, CV_16SC1); uchar* pRowHistMatrix = histMatrix.data; for (int y = 0; y < nChannelSource; y++, pRowHistMatrix += histMatrix.step[0]) { uchar* pColHistMatrix = pRowHistMatrix; for (int x = 0; x < 256; x++, pColHistMatrix += histMatrix.step[1]) { ((signed short*)pColHistMatrix)[0] = 256; } } pRowHistMatrix = histMatrix.data; for (int y = 0; y < nChannelSource; y++, pRowHistMatrix += histMatrix.step[0]) { uchar* pColHistMatrix = pRowHistMatrix; for (int x = 0; x < 256; x++, pColHistMatrix += histMatrix.step[1]) { std::cout << (int)pColHistMatrix[0] << " "; } }
I give the solution for someone have the same bug like me The error is uchar* only handle 8 bit of a variable, and when we move n byte toward we must devide for sizeof(type), here is singed short histMatrix = Mat(nChannelSource, 256, CV_16SC1); signed short* pRowHistMatrix = (signed short*)histMatrix.data; for (int y = 0; y < nChannelSource; y++, pRowHistMatrix += histMatrix.step[0] / sizeof(signed short)) { signed short* pColHistMatrix = pRowHistMatrix; for (int x = 0; x < 256; x++, pColHistMatrix += histMatrix.step[1] / sizeof(signed short)) { pColHistMatrix[0] = 256; } }
69,875,558
69,875,742
Removing a digit from a number in c++
I wanted to write a program that would remove the numbers I give it from my number For example, if I give 10200 to him and 2 to him, deliver 1000 I managed to write it with Python, but I have a question and challenge whether it can be done with C ++ or not for example: ...input:1234 3 ...output:124 How can it be done with "do while"??
Here is what you looking for: #include <bits/stdc++.h> using namespace std; int deleteNumber(int num, int n) { // Get the length of digits int d = log10(num) + 1; // Declare a variable // to form the reverse resultant number int rev_new_num = 0; // Loop with the number for (int i = 0; num != 0; i++) { int digit = num % 10; num = num / 10; // skip to add if the number is what we need to remove if (digit == n) { continue; } else { rev_new_num = (rev_new_num * 10) + digit; } } // Declare a resultant number var int new_num = 0; // Loop with the number for (int i = 0; rev_new_num != 0; i++) { new_num = (new_num * 10) + (rev_new_num % 10); rev_new_num = rev_new_num / 10; } // Return the resultant number return new_num; } // Driver code int main() { int num = 123432111; // the digit to be deleted int n = 1; // Remove the specified digit from starting cout << deleteNumber(num, n) << endl; return 0; } do while version of it would be: // C++ implementation of above approach #include <bits/stdc++.h> using namespace std; int deleteNumber(int num, int n) { // Get the length of digits int d = log10(num) + 1; // Declare a variable // to form the reverse resultant number int rev_new_num = 0; // Loop with the number do { int digit = num % 10; // skip to add if the number is what we need to remove if (digit == n) { continue; } else { rev_new_num = (rev_new_num * 10) + digit; } } while(num = num / 10); // Declare a resultant number var int new_num = 0; // Loop with the number for (int i = 0; rev_new_num != 0; i++) { new_num = (new_num * 10) + (rev_new_num % 10); rev_new_num = rev_new_num / 10; } // Return the resultant number return new_num; } // Driver code int main() { int num = 123432111; // the digit to be deleted int n = 3; // Remove the specified digit from starting cout << deleteNumber(num, n) << endl; return 0; }
69,875,599
70,036,712
Is there any way force to pass an argument as reference?
As the question above, I want to make the code below working. Several types of string arguments should be passed to a function. // declaration, maybe in .h file int matches(std::string& s1, std::string& s2, std::string& s3); inline int matches(std::string s1, std::string s2, std::string s3) { return matches((std::string&) s1, (std::string&) s2, (std::string&) s3); // here i can't figure out } // implementation int matches(std::string& s1, std::string& s2, std::string& s3) { ... } int main() { std::string foo("foo"), bar("bar"), baz("baz"); matches("foo", "bar", "baz" ); matches( foo, bar, "baz" ); matches( foo, "bar", "baz" ); ... matches("foo", bar, "baz" ); matches( foo, bar, baz ); return 0; } I've googled minutes, but couldn't find solution. Do I need to give up this problem? Any suggestion or reply would be appreciated.
Thanks to @RuslanTushov, I've found solution. I post my own answer here for anyone with the same problem. // implementation int matches(const std::string& s1, const std::string& s2, const std::string& s3) { ... } int main() { std::string foo("foo"), bar("bar"), baz("baz"); matches("foo", "bar", "baz" ); matches( foo, bar, "baz" ); matches( foo, "bar", "baz" ); ... matches("foo", bar, "baz" ); matches( foo, bar, baz ); return 0; }
69,875,629
69,875,822
pattern search in text strings in c++
I just want look for a pattern in a string. for example for this "abaxavabaabcabbc" string the app should print "abc" and "abbc". So, the pattern should have "abc" but the numbers of "b" are changing. pattern => "abc" => the numbers of "b" are changeable. And the programm should be in c++.
Using regex_search instead of the iterator: Live On Coliru #include <regex> #include <string> #include <iostream> int main() { std::regex const pattern("ab+c"); for (std::string const text : { "abaxavabaabcabbc", }) // { std::smatch match; for (auto it = text.cbegin(), e = text.cend(); std::regex_search(it, e, match, pattern); it = match[0].second) { std::cout << "Match: " << match.str() << "\n"; } } } Prints Match: abc Match: abbc
69,875,808
69,876,658
How to center the screen after using a distortion with fragment shader?
I'm trying to add some drunk effects by using fragment shader. But I still get some trouble with coords on top right corner as you can see on the picture... Here's the fragment shader : /* Render of the screen */ uniform sampler2D uSampler; /* Texture of the distortion*/ uniform sampler2D uDeformation; /* Texture for the intensity */ uniform sampler2D uIntensity; /* The time (u_time) */ uniform float uTime; /* Scale of Deformation */ uniform float uScale; /* Coords of fragment */ varying vec2 vTextureCoord; void main (void) { vec4 intensityVec = texture2D(uIntensity, vTextureCoord)*(uTime,0.5); // Intensité qu'on met aux corrdonnées (uTime,0.5) vec2 mod_texcoord = vec2(0,vTextureCoord.y*sin(uTime))+intensityVec.xy; // Calcul des coordonnées de la deformation à appliquer en fonction du sinus gl_FragColor = texture2D(uSampler, vTextureCoord+uScale*texture2D(uDeformation, mod_texcoord).rg); // On assemble l'intensité, la deformation et le rendu } Does someone have a idea of what I'm supposed to do ? I tried to rescale it, but it seems to do nothing and I'm out of ideas...
How about you mix the original texture coordinates with the distorted one based on the distance from the edge of the screen so that the deformation fades out towards the edge? Something like this: float tc_mix_fact = 1.0 - distance(vTextureCoord, vec2(0.5))); vec2 final_tc = mix(vTextureCoord, uScale*texture2D(uDeformation, mod_texcoord).rg, tc_mix_fact); gl_FragColor = texture2D(uSampler, final_tc); You most likely want to tweak the function to blend the texture coordinates but this should be a decent starting point. Note: the distance function for tc_mix_fact is going to be slow so you could also just create a look up gradient/vignetting texture to speed this up. Note2: Alternatively to applying the mix factor to the texture coordinates, it might look better to apply it to the uScale factor instead to fade out the distortion towards the screen edge.
69,876,513
69,876,541
Prober type for type "char text [100]" in class
I have the following but I can't figure out what I am doing wrong. I obviously have the wrong types in the argument definition but I can't figure out what the correct syntax would be. dto.h ... class Dto { public: struct msg { int id; byte type; char text[100]; }; char* getText(); void setText(char* text); private: Dto::msg message; ... dto.cpp ... char* Dto::getText() { return Dto::message.text; } void Dto::setText(char* text) { Dto::message.text = text; } ... When I compile I get: Dto.cpp:85:30: error: incompatible types in assignment of 'char*' to 'char [100]' Dto::message.text = text;
You can't assign to an array. To copy a C-string to a char array, you need strcpy: strcpy(Dto::message.text, text); Better yet, use strncpy to ensure you don't overflow the buffer: strncpy(Dto::message.text, text, sizeof(Dto::message.text)); Dto::message.text[sizeof(Dto::message.text)-1] = 0; Note that you need to manually add a null byte at the end if the source string is too big, since strncpy won't null terminate in that case.
69,876,792
69,878,850
How to delete a line from a txt file in Qt?
My txt file (CopyBook.txt) contains for example 10 lines. I want to delete the third one. I have this code: QString fname = "C://Users//Tomahawk//Desktop//copy//CopyBook.txt"; QFile file(fname); if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) { QTextStream edit(&file); QString line; int reachForLine = 0; int neededLine = 3; while (reachForPage != pageCounter) { line = edit.readLine(); reachForPage++; } } So you can see I use "while" to reach for the line i want to delete. But I haven't found any method in Qt that allows me to do it. In future I want to use the ability of deleting lines to replace them with another ones. So how do I delete it?
One way to do it would be to read all of the lines into a QStringList, modify the QStringList, and then turn around and write its contents back to the file again, like this: int main(int argc, char ** argv) { const QString fname = "C:/Users/Tomahawk/Desktop/copy/CopyBook.txt"; QStringList lines; // Read lines of text from the file into the QStringList { QFile inputFile(fname); if (inputFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream edit(&inputFile); while (!edit.atEnd()) lines.push_back(edit.readLine()); } inputFile.close(); } // Delete the third line from the QStringList if (lines.length() > 2) lines.removeAt(2); // 0==first line, 1==second line, etc // Write the text in the QStringList back to the file { QFile outputFile(fname); if (outputFile.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream edit(&outputFile); for (int i=0; i<lines.size(); i++) edit << lines[i] << Qt::endl; } outputFile.close(); } return 0; } You could also perform any replacements/insertions you want to make on the QStringList object, before writing it back to the file. Note that this approach does use up RAM proportional to the size of the file, so for very large files (e.g. gigabytes long) you would probably want to use the create-a-second-file-and-then-rename approach proposed by @TedLyngmo in his comment, instead. For small files, OTOH, buffering in RAM is somewhat easier and less error-prone.
69,876,822
69,878,263
initializing 2d std::array in a class works in release build but not in debug
I'm trying to create a 2d Array class for different use cases where I know the size at compile time and that it won't change during runtime. IE setting up a grid for a battleships game. current implementation works in both debug and release when using balanced 2d arrays such as 2 by 2, however when using unbalanced 2d arrays like 2 by 3 it will work in release but not in debug. I get expression: array subscript out of range when debugging im using visual studio 2022 RC with std 20 enabled header file template <class T,unsigned int colSize,unsigned int rowSize> class TwoDArray{ public: TwoDArray(){ for (int i = 0; i < colSize; ++i) { for (int j = 0; j < rowSize; ++j) { matrix[i][j] = j; std::cout << matrix[i][j] << " "; } std::cout << " " << i << std::endl; } } private: std::array<std::array<T, colSize>, rowSize> matrix; } in main int main(){ auto p = TwoDArray<int,2 ,3>{}; return 0; } releaseBuild for creating 2d array in class .png debugBuild for creating 2d array in class
Mixing up the colSize and rowSize in the for loops was the problem. Good to know about what the release build allows you to do.
69,877,152
69,877,389
How do I correct c++ memory leaks with my binary search tree pointers?
I'm applying some operations to some data structures on C++. I read the operations from a CSV file, calculate CPU time, and write it to another CSV file. I'm doing this for hundreds of sets of operations, however, after several applications of make_experiment(), I get the following error: terminate called after throwing an instance of 'St9bad_alloc' what(): std::bad_alloc Apparently it may be because for some reason I ran out of memory. What could be going wrong? ABB is a BST. Here's the code: #include <iostream> #include <string> #include <fstream> using namespace std; typedef unsigned int uint; string PATH_IN = "ops/"; struct node{ uint data; node* left; node* right; }; class ABB{ private: node* root; node* insert(uint x, node* t); int find(node* t, uint x); public: ABB(); void insert(uint x); int search(uint x); }; node* ABB::insert(uint x, node* t){ if (t == NULL){ t = new node; t->data = x; t->left = t->right = NULL; } else if(x < t->data) t->left = insert(x, t->left); else if(x > t->data) t->right = insert(x, t->right); return t; } int ABB::find(node* t, uint x){ if(t == NULL) return 0; else if(x < t->data) return find(t->left, x); else if(x > t->data) return find(t->right, x); else return 1; } ABB::ABB() { root = NULL; } void ABB::insert(uint x) { root = insert(x, root); } int ABB::search(uint x) { return find(root, x); } void make_experiment(string tree_type, string exp_type, int n){ // Declaration of variables ABB abb; ifstream file_in; ofstream file_out; string line; string op; string sval; uint val; int found; // Opening input and output files if(exp_type == "r"){ file_in.open(PATH_IN + "random/random_" + to_string(n+1) + ".csv"); } file_out.open(tree_type + "_" + exp_type + "_" + to_string(n+1) + ".csv"); // Dealing with headers getline(file_in, line); file_out << "op,time_ms" << endl; // Applying operations and writing elapsed time to output CSV while(getline(file_in, op, ',')) { file_out << op << ","; getline(file_in, sval); val = (uint)stoul(sval); if(op == "i"){ if(tree_type == "abb"){ abb.insert(val); } } else if(op == "be"){ if(tree_type == "abb"){ found = abb.search(val); } } else{ if(tree_type == "abb"){ found = abb.search(val); } } file_out << "time_elapsed" << endl; } file_in.close(); file_out.close(); } int main(){ for(int i=0; i<1000; i++){ make_experiment("abb", "r", i); cout << "ww" << endl; } return 0; } Input CSV files look like this, with a million rows: operation,value i,771383893 be,4071986422 i,2493790208 bi,297183474 Usually it works until i≈250, correctly creating the corresponding output files, and then the error comes.
The most probable cause is that fact that you create and allocate a raw pointer in your private insert function: node* ABB::insert(uint x, node* t){ if (t == NULL){ t = new node; //< new pointer created //... } //... } then pass it to your root data member in your public version of insert: void ABB::insert(uint x) { root = insert(x, root); } but then don't ever destroy/deallocate the root member pointer when you're done (i.e. when an ABB object is destroyed). The easiest way to correct this is to delete the root pointer in ABB's destructor (which you would explicitly declare and define): ABB::~ABB(){ delete root; } Similarly, you need a destructor for node, so that every node's left and right pointer gets recursively freed, otherwise all the BST leaves will still have memory leaks (note that there's multiple ways to implement this, mine is a very basic example implementation; you should look into an implementation that suits your needs the best): node::~node() { delete left; delete right; } You can use std::couts or your debugger to visually see how these destructors work I would also look into completely reworking the design (specifically the private insert function and maybe even the private find function) to not have to allocate and pass raw pointers in a separate function, because, though unlikely, memory can leak if something like an exception occurs while root is still being assigned: node* ABB::insert(uint x, node* t){ if (t == NULL){ t = new node; t->data = x; t->left = t->right = NULL; } else if(x < t->data) t->left = insert(x, t->left); else if(x > t->data) t->right = insert(x, t->right); return t; //< exception occurs somewhere in the function before this line } void ABB::insert(uint x) { root = insert(x, root); //< root is never assigned; t is still allocated but not freed } More importantly, if you somehow end up using the private insert function somewhere else in your program, you may forget to delete that specific pointer and have the same problem all over again. This won't be a problem if your insert doesn't return a raw pointer. An even better solution (if you have C++11 or newer) is to rework the design to use smart pointers such as std::unique_ptr instead of raw pointers, since smart pointers have built in RAII and will manage the pointer de-allocation for you: struct node{ uint data; std::unqiue_ptr<node> left; std::unqiue_ptr<node> right; //Destructor no longer needed in this minimal example }; class ABB{ private: std::unqiue_ptr<node> root; std::unqiue_ptr<node> insert(uint x, node& t); int find(node& t, uint x); public: //No destructor or contructor needed in the minimal example void insert(uint x); int search(uint x); };
69,877,297
69,877,419
Heap array allocates 4 extra bytes if class has destructor
I'm new to C++ and I've been playing around with memory allocation lately. I have found out that when you declare a class with a destructor, like so: class B { public: ~B() { } }; And then create a heap array of it like so: B* arr = new B[8]; The allocator allocates 12 bytes but when I remove the destructor, it only allocates 8 bytes. This is how I'm measuring the allocation: size_t allocated = 0; void* operator new(size_t size) { allocated += size; return malloc(size); } void deallocate(B* array, size_t size) { delete[] array; allocated -= size * sizeof(B); } Of course I have to call deallocate manually while the new operator is called automatically. I have found this problem while working with an std::string* and I realised that the deallocator worked fine with an int* but not with the former. Does anyone know why that happens and more importantly: How to detect these programmatically at runtime? Thanks in advance.
You are looking at an implementation detail of how your compiler treats new[] and delete[], so there isn't a definitive answer for the extra space being allocated since the answer will be specific to an implementation -- though I can provide a likely reason below. Since this is implementation-defined, you cannot reliably detect this at runtime. More importantly, there shouldn't be any real reason to do this. Especially if you're new to C++, this fact is more of an interesting/esoteric thing to know of, but there should be no real benefit detecting this at runtime. It's important to also be aware that this only happens with array-allocations, and not with object allocations. For example, the following will print expected numbers: struct A { ~A(){} }; struct B { }; auto operator new(std::size_t n) -> void* { std::cout << "Allocated: " << n << std::endl; return std::malloc(n); } auto operator delete(void* p, std::size_t n) -> void { std::free(p); } auto main() -> int { auto* a = new A{}; delete a; auto* b = new B{}; delete b; } Output: Allocated: 1 Allocated: 1 Live Example The extra storage only gets allocated for types with non-trivial destructors: auto* a = new A[10]; delete[] a; auto* b = new B[10]; delete[] b; Outputs: Allocated: 18 Allocated: 10 Live Example The most likely reason why this happens is that extra bookkeeping of a single size_t is being kept at the beginning of allocated arrays containing non-trivial destructors. This would be done so that when delete is called, the language can know how many objects require their destructors invoked. For non-trivial destructors, its able to rely on the underlying delete mechanics of their deallocation functions. This hypothesis is also supported by the fact that for the GNU ABI, the extra storage is sizeof(size_t) bytes. Building for x86_64 yields 18 for an allocation of A[10] (8 bytes for size_t). Building for x86 yields 14 for that same allocation (4 bytes for size_t). Edit I don't recommend doing this in practice, but you can actually view this extra data from arrays. The allocated pointer from new[] gets adjusted before being returned to the caller (which you can test by printing the address from the new[] operator). If you read this data into a std::size_t, you can see that this data -- at least for the GNU ABI -- contains the exact count for the number of objects allocated. Again, I do not recommend doing this in practice since this exploits implementation-defined behavior. But just for fun: auto* a = new A[10]; const auto* bytes = reinterpret_cast<const std::byte*>(a); std::size_t count; std::memcpy(&count, bytes - sizeof(std::size_t), sizeof(std::size_t)); std::cout << "Count " << count << std::endl; delete[] a; The output: Count 10 Live Example
69,877,468
69,880,497
run cmake with a txt file
When I run my C++ program I need it to open a text file stored in my root directory. How can I make CMake to execute the program I have written with the text file? When I build my program with Makefile alone, I use the command ./"executable" src/"txt file"
Honestly, by far the simplest would be to just modify your main function. As it stands you main function must be grabbing the filename from the command line arguments. Something like this: #include <iostream> int main(int argc, char *argv[]) { const auto filename = argv[1]; // Do stuff with filename std::cout << filename; return 0; } What you probably should do is to just modify that file to use some default filename when no argument is provided: #include <iostream> int main(int argc, char *argv[]) { const auto filename = argc < 2 ? "/root/something.txt" : argv[1]; // Do stuff with filename std::cout << filename; return 0; } Depending on how complicated you want to get, you could also let that filename be specified in your CMakeLists. Just add a definition like set(DEFAULT_FILENAME "/root/something.txt") target_compile_definitions(my_target PRIVATE "DEFAULT_FILENAME=\"${DEFAULT_FILENAME}\"") and then take the filename like a macro in your main function: #include <iostream> int main(int argc, char *argv[]) { const auto filename = argc < 2 ? DEFAULT_FILENAME : argv[1]; // Do stuff with filename std::cout << filename; return 0; } To summarize... It sounds like you want to have one executable to be built with the filename into it. The aforementioned approaches will accomplish that. However, there is a much simpler solution... just create a script that runs the file you want. For example, just throw your code ./"executable" src/"txt file" into a script run.sh Then make that script runnable (assuming Linux) with chmod +x run.sh and just run that script: ./run.sh
69,877,819
69,879,743
How do I get a specific number from an input in c++?
Having a list of N ordered pairs of the form (A,B) Example input: (200,500) (300,100) (300,100) (450,150) (520,480) I want to get only the numbers from the input, so that I can use them within my Point structure, and use them to represent the location on a coordinate plane. Here is my code: #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <fstream> using namespace std; struct Punto { double x,y; double distancia; double zona; }; int main() { int n=4; Punto arr[n]; int x, y; for(int i=0; i<n; i++){ cin.ignore(); //( std::cin >> x; arr[i].x = x; std::cout << "Punto " << i << " x " << x << '\n'; cin.ignore(); //, std::cin >> y; arr[i].y = y; std::cout << "Punto " << i << " y " << y << '\n'; cin.ignore(); //) } return 0; } The problem is that this only works with the first entry but not with the following ones.
ignore will discard a new line delimiter in addition to the characters you want to ignore, this means that in the second iteration of your loop cin.ignore() will ignore a new line character leaving the opening ( still in the stream and causing std::cin >> x to then fail. A more reliable approach is to read the delimiters and check their values, this will help detect errors in the file format or bugs in your code and has the added bonus that reading the characters will automatically skip whitespace including new lines. boll readDelim(char expected) { char ch; std::cin >> ch; return ch == expected; } int main() { const int n=4; Punto arr[n]; int x, y; for(int i=0; i<n; i++){ if (!readDelim('(')) break; std::cin >> x; arr[i].x = x; std::cout << "Punto " << i << " x " << x << '\n'; if (!readDelim(',')) break; std::cin >> y; arr[i].y = y; std::cout << "Punto " << i << " y " << y << '\n'; if (!readDelim(')')) break; } return 0; }
69,877,963
69,878,019
How to create a static library (not executable) in CMake?
I'm new to cmake and I was wondering how to create a static library. In gcc, it can be done by: ar rsv Well, how do you do it using CMake? add_library(mylib STATIC file1.cpp file2.cpp) add_executable(myexe main.cpp) target_link_libraries(myexe mylib) This generates a static library (.a file) but how do you compile it without adding an executable? if I remove add_executable(myexe main.cpp), it gives me an error. I only want this file: mylib.a and NOT myexe.exe mylib.a
add_library can be used by itself, without using add_executable at all. Simply remove line 2 to get rid of the executable. The error is most likely caused by line 3, which needs myexe to function. Line 3 should also be removed, because you are only building the library and not linking it.
69,878,367
69,878,464
Behavior of back and forth shift of small types(char and short)
Suppose i want to set the first i bits of a variable c to zero. One of the ways to do it is to shift left i bits and then shift right the same amount. Here is a simple program that does this: #include <iostream> int main() { using type = unsigned int; type c, i; std::cin >> c >> i; c = (c << i) >> i; std::cout << c << "\n"; return 0; } But when the type is unsigned short or unsigned char, this does not work, and c stays unchanged. From one side, it is totally expectable since we know that registers are at least 32 bits wide and shifting one or two bytes back and forth won't set leftmost bits to zero. But the question is: how does such behavior comply with the standard and the definition of operator<<? What is the reason for c = (c << i) >> i; not behaving same as c <<= i; c >>= i; from the point of the language? Is it even defined behavior, and if yes, are there other examples presenting different behavior between semantically equivalent code?(Or why aren't this two lines equivalent?) I also looked at the generated assembly, and with -O2 it looks more or less like this for any type: sall %cl, %esi shrl %cl, %esi But if we make i constant, then g++ masks ints with 2^(n_bits - i) - 1, BUT never bothers generating any instructions for shorts and chars and prints them right after getting from cin. So, it definetely knows how it works and hence this behavior should be documented somewhere, even though i couldn't find anything. P.S. Of course there are more reliable ways to set required bits to zero, e.g the one gcc uses when knows i, but this question is more about rules of behavior rather than setting bitfields.
how does such behavior comply with the standard and the definition of operator<<? The behaviour that you observe conforms to the standard. Is it even defined behavior Yes, it is defined (assuming i isn't too great so as to cause overflow; You won't be able to set all bits to zero using this method). why aren't this two lines equivalent? Because there are no arithmetic operations for integer types of lower rank than int in C++, and all arithmetic operands of smaller types are implicitly converted to signed int. Such implicit conversion is called a promotion. The behaviour of signed right shift and unsigned right shift are different. Signed right shift extends the left most bit such that the sign remains the same, while unsigned right shift pads the left most bits with zero. The second version behaves differently because the the intermediate result has the smaller unsigned type while the intermediate result in the first version is the promoted signed int (on systems where short and char are smaller than int).
69,878,503
69,878,583
value store in vector changed when I use pointer to set the value
I was trying to write a n-ary tree,each node contains 4 elements,1 vecter<Node*>,3 variable. When I try to assign the value by pointer,I found the value will be covered by the after value. I think may be because the pointer point to each value,so all the value will be the same.So I try to set the pointer to NULL,but it still didn't work. #include <string.h> #include <vector> #include <iostream> using namespace std; struct Node{ vector<Node*> subNodes; bool isFile=0; bool isDir=0; int value=0; }; int main() { Node* rootNode_ptr; Node rootNode; rootNode_ptr =&rootNode; rootNode_ptr->value=99; for(int i=0;i<5;i++){ Node* subNode_ptr; Node subNode; subNode_ptr=NULL; subNode_ptr = &subNode; subNode_ptr->value=i; rootNode_ptr->subNodes.push_back(subNode_ptr); cout<<"0 : "<<rootNode_ptr->subNodes[0]->value<<endl; cout<<rootNode_ptr->subNodes[i]->value<<endl; } return 0; } the subNodes[0].value keeps changing
The variables declared in a for loop are on the stack. The moment they go out of scope (such as, say, your loop repeats, or the loop terminates) then the variables are destroyed. Storing pointers to destroyed objects causes undefined behavior when you read from them. You need the objects to persist longer. The most obvious way is to allocate them on the heap (perhaps by using the "new" operation, or std::make_unique()), and they won't go away until you delete them (or the unique_ptr goes out of scope.) Setting a pointer to null before assigning to it is not going to help. So instead of this: Node* subNode_ptr; Node subNode; subNode_ptr=NULL; subNode_ptr = &subNode; subNode_ptr->value=i; Try this: Node subNode_ptr = new Node; subNode_ptr->value = i; And be sure to clean it up later. Your node's destructor needs to iterate the vector and delete each element. Also, you also need to worry about copying and assigning one Node to another, because the vector of pointers needs to do a deep copy. (Since the nodes "think" they own the pointed-to objects, if two both point to the same object and one is later destroyed it will delete the object. Then the remaining copy will try to use it and UB happens.)
69,878,908
69,878,971
How to sleep all running threads C++?
Problem I want to stop the entire program process on a special event from GUI (Qt 5.15.2), except the GUI thread, and show an error message dialog and terminate the program. 1) Problem With Getting All Running Threads I need to put all other running threads in sleep before they cause some problems like Segmentation Fault. With POSIX Thread APIs and MS-Windows APIs, we have a proper API for getting a list of all running threads. But I don't find a similar one from STL. Is there any cross-platform API (even from third-party libraries like Qt or Boost)? Or I must implement using platform-specific APIs? 2) Problem With Putting All Running Threads In Sleep After getting the running threads, how could I put them to sleep while they are in the middle of some sort of blocking operations? It's possible?
In general what you are asking for is not possible, at least not without keeping your own list of active threads and co-operating with them to achieve that result. For example, if your main/GUI thread keeps its own list of active threads (which it appends to whenever it spawns a thread, and removes from whenever it joins an exited thread), it could also maintain a list of QMutex objects (one per thread), and to "pause all threads" it could acquire every QMutex in the list. That, by itself, wouldn't affect the threads at all, but if you had added code to each thread to periodically acquire and then immediately release its QMutex, then the next time the thread tried to acquire the QMutex it would block inside the acquire function until the main thread decided to release the QMutex again. That said, I don't think that sleeping all running threads is the proper solution to your problem anyway. If your problem is that threads are occasionally crashing when you try to exit your program, the proper solution to that problem is to perform a controlled shutdown: have your main thread ask all of the child threads to go away (via std::atomic<bool> or pipe() or socketpair() or condition-variable or whatever other mechanism is convenient) and then call join() on each of the child threads before exiting. That way, when the main thread finally does exit, it is guaranteed that no child threads are running anymore, and thus there is no race condition possible between the main thread's cleaning up of resources and child threads trying to still use them. If your child threads are stuck inside blocking calls, that can be a problem, since the child threads can't exit until after their blocking calls have returned, and the main thread can't complete all of its calls to join() until all of the child threads have exited. One way to deal with that problem would be to put timeouts on the blocking calls, so that the child threads will periodically be able to unblock and see if they need to exit; that's a bit ugly, though, so in my programs I try to use only non-blocking I/O instead (e.g. have the child threads only block inside select() or poll(), and when the main thread wants them to go away, it sends a byte on a pipe() that the child thread is selecting-for-read-ready on, to notify the child thread that it is time to exit ASAP)
69,879,976
69,880,008
What's the meaning of ipv6 :: address?
In my code, I found that my initial client and server configurations has the ipv6 address: :: (equivalent to 0:0:0:0:0:0:0:0?). struct SslConfigurations { std::string clientIp{"::"}; std::string serverIp{"::"}; UInt16 clientPort{0U}; UInt16 serverPort{0U}; ssl::SocketType type{}; ssl::SSLReturnCodes errorCode{}; }; What's the meaning of this address? Can I use this address if I don't change it?
It is just a shortcut for the groups of four-zeroes (0000) appearing in the middle, that can be omitted. It's more visible on the example: The address 2001:0db8:0000:0000:0000:8a2e:0370:7334 becomes 2001:db8::8a2e:370:7334. The :: means 0000:0000:0000:0000:0000:0000:0000:0000. The :: address has the same meaning as 0 or 0.0.0.0 in the IPv4 world: It represents all networks.
69,880,337
69,880,834
C++ Inheritance with templates undefined reference error
I want to implement a base class with multiple children. Base Class template <typename T> class Trigger { protected: T threshold; Trigger(T a_threshold) : threshold(std::pow(10, a_threshold / 20)){}; public: void setThreshold(T a_threshold) { threshold = std::pow(10, a_threshold / 20); } virtual bool operator()(const T &first, const T &second) const; virtual ~Trigger() = default; }; Derived Class template <typename T> class ZeroCrossingRisingTrigger : public Trigger<T> { public: ZeroCrossingRisingTrigger(void) : Trigger<T>(0.){}; bool operator()(const T &first, const T &second) const override { return (first <= 0) & (second > 0); } }; Usage in the main file #include "Trigger.hpp" int main([[maybe_unused]] int argc, [[maybe_unused]] char const *argv[]) { Trigger::ZeroCrossingRisingTrigger<double> trig; return 0; } But on I get the following error when I try to compile it: (...): undefined reference to `Trigger::Trigger::operator()(double const&, double const&) const' I don't understand why I get this error because I implemented the operator exactly as written in the error message.
You have not defined an implementation for operator() for Trigger<T>. An option would be to make Trigger an abstract base class by making the operator member function a pure virtual function: virtual bool operator()(const T &first, const T &second) const = 0; Alternatively, you can provide an empty implementation. On a side-note, in the constructor of ZeroCrossingRisingTrigger you pass 0.0 as an argument for the base class constructor. This sort of hints there is no need for ZeroCrossingRisingTrigger to be templated itself, unless you want to control the type of the 0.0 literal from the outside.
69,880,784
69,881,171
Why isn't the copy assingnment operator called when the copy construcotr is not available in C++?
Why when let's say I have an object declared like this: Obj o1; which is initialized by the default constructor (not very important here, how was o1 initialized, the point is it was initialized) and I create another object in this manner: Obj o2 = o1; the copy constructor is implicitly called, but if I delete the copy constructor, then, I get a compile error. Why the object o1 is not assigned/copied to o2, like here: Obj o1; Obj o2; o2 = o1;? Why the compiler tries to call a constructor in any instance? Is the = operator within Obj o2 = o1; overloaded?
As mentioned in comments, this Obj o2 = o1; has nothing to do with assignment. It is a little unfortunate, often confusing, use of = for initialization when otherwise = means assignment. Also mentioned in comments, the operator= has to assume that the left operator already exists. Consider this somewhat contrived example: #include <vector> struct my_vect { my_vect() : data(2) {} my_vect(const my_vect& other) : data(other.data) {} my_vect& operator=(my_vect& other) { // this has already been constructed, // hence data.size() is 2 already data[0] = other.data[0]; data[1] = other.data[1]; return *this; } private: std::vector<int> data; }; It is a structure that contains a std::vector whose size is always 2. The vector is initialized upon constructing a my_vect. When assigning one my_vect to another, then data needs not be initialized. Only the values must be copied. Because operator= assumes that the left hand side operator is already properly constructed (it merely copies to data[0] and data[1]) it cannot possibly be used to construct an object (in the example, accessing data[0] or data[1] would be out of bounds). TL;DR: Constructors construct objects. Assignment assigns to an already existing object. Thats two fundamentally different things.
69,880,831
69,880,972
get multiple lines of strings from input in c++
I just wrote a programme for something and I have to get several lines of string from user but I could not handle it. for example: the inputs are "ajflskahnlkanjf" and "jhsagfalifsbk" in two lines and my code should find some pattern in them. the pattern part is handled but I can not get strings in several lines. By the way the user should first give me the lines of strings and then my code should start processing. using namespace std; int main() { string str; getline(cin, str); std::regex const pattern("ab+c"); for (std::string const text : { str, }) // { std::smatch match; for (auto it = text.cbegin(), e = text.cend(); std::regex_search(it, e, match, pattern); it = match[0].second) { std::cout << "Match: " << match.str() << "\n"; } } }
If I understood you correctly, the problem is that you read only one line of the input, when there might be an unknown number of them. The idiomatic way to read lines until the EOF signal is received is std::string line; while (std::getline(std::cin, line)) { // The code for processing the line goes here } However, if you know exactly the number of the lines you need to read, you can do int nlines = 2; // For example std::vector<std::string> lines; lines.reserve(2); // A small optimization while (nlines--) { std::string line; std::getline(std::cin, line); lines.push_back(std::move(line)); // Move to avoid copying. The line becomes // invalid from here, remove the move if you will // plan to do something else with it } // Process the lines in the vector outside the loop
69,880,997
69,881,099
access violation when i use my index buffer to draw objects
I am learning OpenGL and I am trying to abstract it to make it convenient for me to use it. but I am getting access violations when I use my IndexBuffer class while rendering. this is my code for IndexBuffer.h class IndexBuffer { public: IndexBuffer(void* data, int count); IndexBuffer(int count); IndexBuffer Bind(); IndexBuffer UnBind(); void AddData(void* data); ~IndexBuffer(); private: int count; size_t size; unsigned int id; }; and this is my code for IndexBuffer.cpp #include "IndexBuffer.h" #include "glew/glew.h" IndexBuffer::IndexBuffer( void* data, int count): id(0), count(count), size(sizeof(unsigned int)* count) { glGenBuffers(1, &id); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * count, data, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } IndexBuffer::IndexBuffer( int count) : id(0), count(count), size(sizeof(unsigned int)* count) { glGenBuffers(1, &id); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * count, nullptr, GL_DYNAMIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } IndexBuffer IndexBuffer::Bind() { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); return *this; } IndexBuffer IndexBuffer::UnBind() { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); return *this; } void IndexBuffer::AddData(void* data) { Bind(); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeof(unsigned int) * count, data); UnBind(); } IndexBuffer::~IndexBuffer() { glDeleteBuffers(1, &id); } I wrote my VertexBuffer in the same way and it works fine, But my index buffer just doesn't work. this is my main.cpp #include <iostream> #include "glew/glew.h" #include "glfw/glfw3.h" #include "VertexBuffer.h" #include "IndexBuffer.h" struct Vertex { float aPos[2]; }; int main() { GLFWwindow* window; if (glfwInit() == GLFW_FALSE) { return -1; } //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); window = glfwCreateWindow(600, 600, "Hello world", nullptr, nullptr); glfwMakeContextCurrent(window); if (glewInit() != GLEW_OK) { return -2; } unsigned int index[3] = { 0, 1, 2 }; Vertex data[] = { Vertex({-0.5f, -0.5f}), Vertex({ 0.5f, -0.5f}), Vertex({ 0.0f, 0.5f}) }; unsigned int VertexArrayObject; glGenVertexArrays(1, &VertexArrayObject); VertexBuffer buffer = VertexBuffer(sizeof(Vertex) * 3); IndexBuffer Ibuffer = IndexBuffer( 3); buffer.Bind(); //glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6, data, GL_STATIC_DRAW); buffer.AddData(data); glBindVertexArray(VertexArrayObject); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void*)offsetof(Vertex, aPos)); //glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); buffer.UnBind(); Ibuffer.Bind(); Ibuffer.AddData(index); Ibuffer.UnBind(); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); buffer.Bind(); Ibuffer.Bind(); glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, nullptr); glfwSwapBuffers(window); glfwPollEvents(); } glDeleteVertexArrays(1, &VertexArrayObject); glfwDestroyWindow(window); return 0; } can anybody help me out?
In short you have undefined behaviour. Your classes doesn't support deep copy. When Bind function returns object (i.e itself) by value, like: IndexBuffer IndexBuffer::Bind() destructor of IndexBuffer is called, which deletes previously allocated buffer, so buffer's id is dangled. All Bind should return reference to instances: IndexBuffer& IndexBuffer::Bind()
69,881,097
69,882,533
libuv signal handling in multithreaded programs
In a multithreaded C++ program where the main thread is executing a libuv event loop, is it guaranteed that this event loop thread is executing signal handlers registered using uv_signal_start? Background information: From http://docs.libuv.org/en/v1.x/design.html The I/O (or event) loop is [...] meant to be tied to a single thread. But as we are in a multithreaded program, signal handlers can be executed by other threads According to POSIX.1, a process-directed signal (sent using kill(2), for example) should be handled by a single, arbitrarily selected thread within the process. So my question is basically whether libuv signal handling works as advertised Signal handles implement Unix style signal handling on a per-event loop bases. even in multithreaded programs.
TLDR: Yes, should work as advertised. From my understanding of libuv's source code unix/signal.c there is a generic signal handler static void uv__signal_handler(int signum) { uv__signal_msg_t msg; uv_signal_t* handle; int saved_errno; saved_errno = errno; memset(&msg, 0, sizeof msg); if (uv__signal_lock()) { errno = saved_errno; return; } for (handle = uv__signal_first_handle(signum); handle != NULL && handle->signum == signum; handle = RB_NEXT(uv__signal_tree_s, &uv__signal_tree, handle)) { int r; msg.signum = signum; msg.handle = handle; /* write() should be atomic for small data chunks, so the entire message * should be written at once. In theory the pipe could become full, in * which case the user is out of luck. */ do { r = write(handle->loop->signal_pipefd[1], &msg, sizeof msg); } while (r == -1 && errno == EINTR); assert(r == sizeof msg || (r == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))); if (r != -1) handle->caught_signals++; } uv__signal_unlock(); errno = saved_errno; } in which a pipe handle->loop->signal_pipefd[1] is used to tell the handle's associated loop abount the incoming signal. Indeed, this generic signal handler can be called from any thread, however the libuv thread will then call the user's specific signal handler registered with uv_signal_start in the event loop thread (main thread in my setting) when it reads the signal_pipefd[1] in the next loop iteration. This was for the unix source code and the windows win/signal.c source has a similar mechanism. So the answer should be yes, it should also work as advertised in a multithreaded setting, i.e. the registered handler will be executed by the loop thread.
69,881,138
69,881,563
how to use std::num_put for custom pointer output formatting?
TLDR; Default output of pointers with c++ iostream is of the form 0xdeadbeef. What I want is pointers to be output in the form #xdeadbeef. Problem For testing purposes I output internal data of some c++ program in form of s-expressions, so I can have in the future the option to use Common Lisp to reason about the output. Now, hex numbers are written in the form #xdeadbeef and iostream default is using the C/C++ typical 0x... syntax. So, after a bit of reading, I think I am close to finding a solution... only, at least on cppreference.com, there is not enough (demo code or explanations) to allow me to understand, how I am exactly supposed to solve this. #include <iostream> #include <locale> #include <sstream> #include <string> struct lispy_num_put : std::num_put<char> { iter_type do_put(iter_type s, std::ios_base& f, char_type fill, const void* p) { std::ostringstream oss; oss << p; std::string zwoggle{oss.str()}; if (zwoggle.length() > 2 && zwoggle.starts_with("0x")) { zwoggle[0] = '#'; } // ... NOW WHAT TO DO??? I.e how to send the string along? } }; // ... As you can see, I now have the string representation of how I want to see the pointer in the output. Only it is unclear to me, how to send that string now into the output stream. Later, I will have to use some imbue() thingy to make this struct used by my output stream. I think, that part I can figure out myself.
Use your iter_type s parameter to output characters. *s++ = '#'; // outputs a hash while (...) *s++ = ...; // outputs digits return s;
69,881,344
69,909,819
Chars are not read properly
So I wanted to work a bit with lexers to imporve my work with chars and strings but as it turns out I am a complete failure understanding them. I have made two VERY simple functions to recoginze specific chars and return true or false. //Not the source code THIS IS ONLY AN EXAMPLE but it works this way: bool is_char(char c) { switch(c) { case 'a': return true; break; . . . default: return false; break; } } Now I made another function called is_token to see if I have a non alphabetical character and it works partly. bool is_token(char c) { switch (c) { case '\0': return false; break; case '{': return true; break; case '}': return true; break; case '=': return true; break; case ';': return true; break; default: return false; } } It works exactly one time by the first ';' and then it is a total failure. No detection what so ever. This is the code I try to lex: int a; int main() { return a; } This is how the code works: ifstream file; //argv is the path file.open(argv[1]); vector<char*> words; string line, code, word; while(getline(file, line)) { //I was just lazy and reused this loop code += line; } for(int i = 0; i < code.size(); i++) { if(is_char(code[i])) { word += code[i]; }else{ words.push_back(word); word = ""; if(is_token(code[i])){ //Just so I know that i registered a Token words.push_back("Token"); } } } for(int i = ; i < words.size(); i++) { cout << words[i] << endl; } The alphabertical characters are no problem but suddenly the same algorithm breaks down with new characters. Am I overseeing something here? Or does it not work how I think it does?
So as it turned out I had just increased the wrong value and it had nothing to do with the code I showed here :D But thanks to all the people that answered me and tried to help! Next time I should look at my values more properly :D
69,881,419
69,881,457
How to interpret data types obtained from <typeinfo> library?
Q1 - Since both begin(arr) & &arr will return hexadecimal pointer location of starting of the arr, wondering what is the difference between the outputs of data types printed by the following script? #include <iostream> #include <typeinfo> #include <string> using namespace std; int main() { int arr[] = {10, 20, 30, 40, 50, 60, 77}; cout << typeid(begin(arr)).name() << " , " << typeid(&arr).name() << endl; cout << begin(arr) << " , " << &arr << endl; return 0; } OUTPUT Pi , PA7_i 0x7ffc79a99500 , 0x7ffc79a99500 Q2 - how can we get decimal representation of hex pointer location?
For Q1: Note that begin(arr) and &arr are different things (with different types). begin(arr) gives the pointer to the 1st element of arr with type int*, &arr gives the pointer to the array arr with type int (*)[7].
69,881,508
69,881,544
using namespace in c++
I have come to understand why using namespace std; is considered bad practice in c++ but let's consider for example 2 ( hypothetical ) libraries "std" and "sfd" , both of them contain a function "run()". would the following be okay or is it still a problem : ( if i want to call "run()" from "std" ) using namespace std; using namespace sfd; int main(){ std::run(); } ( if i want to call "run()" from "sfd" ) using namespace std; using namespace sfd; int main(){ sfd::run(); }
There is no problem because you are using qualified names in the function calls. A program would be ill-formed if you used the unqualified function name in its call like run(); In this case there would be ambiguity.
69,881,509
69,881,613
Surprising c-style cast
I am refactoring our code-base, where I have the following code (simplified): template <typename T> class TVector3; template <typename T> class TVector4; template <typename T> struct TVector4 { TVector3<T>& V3() { return (TVector3<T> &) *this; } const TVector3<T>& V3() const { return (const TVector3<T> &) *this; } }; template <typename T> struct TVector3 { template <typename U> constexpr TVector3(const TVector4<U>& v) noexcept { } }; typedef TVector3<float> Vec3f; typedef TVector4<float> Vec4f; struct RGBA { Vec4f rgba; operator Vec3f() const { return rgba.V3(); } }; clang warns me about returning reference to local temporary object (https://godbolt.org/z/ccxbjv771). Apparently (const TVector3<T> &) *this results in calling TVector3(const TVector4<U>& ), but why ? Intuitively, I would have expected (const TVector3<T> &) to behave like reinterpret cast, or if at least the cast would have looked like (const TVector3<T>) *this (without &) it would kind of make sense to me that the compiler picked that constructor call for conversion. Another simpler example: #include <iostream> struct A { }; struct B { B(const A& ) { std::cout << "B(const A&)" << std::endl; } }; int main() { A a; (const B&) a; return 0; } It prints B(const A&) (https://godbolt.org/z/ocWjh1eb3), but why ? I am converting to const B& and not to B.
It prints B(const A&), but why ? I am converting to const B& and not to B. The type of a is A, it can't be bound to const B& directly. It needs to be converted to B via B::B(const A& ) firstly; then the converted temporary B is bound to const B&. (Lvalue-reference to const could bind to temporaries.)
69,881,718
70,076,066
Undefined symbols for architecture arm64: m1 mac
"__ZNSi6ignoreEv", referenced from: __Z2q2v in cc5SDSPY.o "__ZNSi7getlineEPcl", referenced from: __Z2q2v in cc5SDSPY.o "__ZNSirsERd", referenced from: __Z2q3v in cc5SDSPY.o "__ZNSirsERi", referenced from: __Z2q2v in cc5SDSPY.o __Z2q3v in cc5SDSPY.o "__ZNSolsEPFRSoS_E", referenced from: __Z2q1v in cc5SDSPY.o __Z2q3v in cc5SDSPY.o "__ZNSolsEd", referenced from: __Z2q3v in cc5SDSPY.o "__ZNSolsEi", referenced from: __Z2q1v in cc5SDSPY.o __Z2q2v in cc5SDSPY.o "__ZNSt8ios_base4InitC1Ev", referenced from: __Z41__static_initialization_and_destruction_0ii in cc5SDSPY.o "__ZNSt8ios_base4InitD1Ev", referenced from: __Z41__static_initialization_and_destruction_0ii in cc5SDSPY.o "__ZNSt9basic_iosIcSt11char_traitsIcEE8setstateESt12_Ios_Iostate", referenced from: __ZStrsIcSt11char_traitsIcEERSt13basic_istreamIT_T0_ES6_PS3_ in cc5SDSPY.o "__ZSt17__istream_extractRSiPcl", referenced from: __ZStrsIcSt11char_traitsIcEERSt13basic_istreamIT_T0_ES6_PS3_ in cc5SDSPY.o "__ZSt3cin", referenced from: __Z2q1v in cc5SDSPY.o __Z2q2v in cc5SDSPY.o __Z2q3v in cc5SDSPY.o "__ZSt4cout", referenced from: __Z2q1v in cc5SDSPY.o __Z2q2v in cc5SDSPY.o __Z2q3v in cc5SDSPY.o "__ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_", referenced from: __Z2q1v in cc5SDSPY.o __Z2q3v in cc5SDSPY.o "__ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc", referenced from: __Z2q1v in cc5SDSPY.o __Z2q2v in cc5SDSPY.o __Z2q3v in cc5SDSPY.o "__ZdaPv", referenced from: __Z2q2v in cc5SDSPY.o __Z2q3v in cc5SDSPY.o "__ZdlPvm", referenced from: __Z2q1v in cc5SDSPY.o "__Znam", referenced from: __Z2q1v in cc5SDSPY.o __Z2q2v in cc5SDSPY.o __Z2q3v in cc5SDSPY.o "___cxa_throw_bad_array_new_length", referenced from: __Z2q3v in cc5SDSPY.o ld: symbol(s) not found for architecture arm64 collect2: error: ld returned 1 exit status Getting this error. I tried to install 'oh my zsh' and in the process, lost even the basic compiling setup.
Whoever is facing this error, this happens because of the Big Sur to Monterey update of the Mac os. Just set the code path again. Edit the JSON files and your vs code will again start working like a charm!
69,882,344
69,883,363
UWidget::SynchronizeProperties() is not being called on in editor property change
I have to change the children list every time the enum variable property is changed from widget editor. None of the functions I've tried so far seem to have worked (virtual void OnEndEditByDesigner(); virtual void PostEditChangeProperty(struct FPropertyChangedEvent & PropertyChangedEvent)). SynchronizeProperties docs state that It can also be called by the editor to update modified state, so ensure all initialization to a widgets properties are performed here, or the property and visual state may become unsynced. So I'm not entirely sure that it is the right function to use/overwrite (as it only "can" be called by the editor to update modified state, not will be called on property editor edit) Here is some sample code to show an example of what I've been trying to do so far. Sample code: SampleButton.h /* Includes */ #include "CoreMinimal.h" #include "UObject/Object.h" #include "Components/Button.h" #include "Components/Image.h" #include "Components/CanvasPanel.h" #include "Components/ButtonSlot.h" #include "Widgets/SOverlay.h" #include "Components/Overlay.h" #include "Components/TextBlock.h" #include "Styling/SlateBrush.h" #include "UUIW_MasterButton.generated.h" // UENUM(BlueprintType) enum class EContentType : uint8 { WithIcon, WithText, } class SAMPLE_API SampleButton : public UButton { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintSetter=SetType, meta = (MakeEditWidget = "")) EContentType ContentType = EContentType::WithIcon; UPROPERTY(meta = (EditCondition = "ContentType == EContentType::WithIcon || ContentType == EContentType::WithTextAndIcon", EditConditionHides)) UImage* Icon; UPROPERTY(meta = (EditCondition = "ContentType == EContentType::WithText || ContentType == EContentType::WithTextAndIcon", EditConditionHides)) UTextBlock* TextBlock; protected: virtual TSharedRef<SWidget> RebuildWidget() override; UOverlay* Overlay; virtual void SynchronizeProperties(); } SampleButton.cpp #include "UI/SampleButton.h" TSharedRef<SWidget> SampleButton::RebuildWidget() { Overlay = NewObject<UOverlay>(); auto ButtonRef = Super::RebuildWidget(); AddChild(Overlay); Icon = NewObject<UImage>(); Icon->SetDisplayLabel(TEXT("Icon")); TextBlock = NewObject<UTextBlock>(); TextBlock->SetDisplayLabel(TEXT("Text")); switch (ContentType) { case EContentType::WithIcon: Overlay->AddChild(Icon); break; case EContentType::WithText: Overlay->AddChild(TextBlock); break; case EContentType::WithTextAndIcon: Overlay->AddChild(Icon); Overlay->AddChild(TextBlock); break; } if ( GetChildrenCount() > 0 ) { Cast<UButtonSlot>(GetContentSlot())->BuildSlot(MyButton.ToSharedRef()); } return ButtonRef; } void UUUIW_MasterButton::SynchronizeProperties() { Super::SynchronizeProperties(); Overlay->ClearChildren(); switch (ContentType) { case EContentType::WithIcon: Overlay->AddChild(Icon); break; case EContentType::WithText: Overlay->AddChild(TextBlock); break; case EContentType::WithTextAndIcon: Overlay->AddChild(Icon); Overlay->AddChild(TextBlock); break; } }
Kinda already found the solution. PostEditChangeProperty(struct FPropertyChangedEvent & PropertyChangedEvent) worked, apparently. But rather than being called on value change, it is called on blueprint compilation after that (which is why I thought that it didn't work before)
69,882,795
69,883,141
What is a difference between iterator_category vs iterator_category() in std::iterator_traits
Why in one case I must write iterator_category without parentheses: template<typename Iterator> void my_advance(Iterator &iter, int n) { if constexpr(std::is_same_v< typename std::iterator_traits<Iterator>::iterator_category, std::random_access_iterator_tag>) iter += n; else for(int i = 0; i<n; ++i, ++iter); } and in enother case with parentheses: template<typename Iterator, typename IterCategory> void my_advance_helper(Iterator &iter, int n, IterCategory){ for(int i = 0; i < n; ++i, ++iter); } template<typename Iterator> void my_advance_helper(Iterator &iter, int n, std::random_access_iterator_tag){ iter += n; } template<typename Iterator> void my_advance(Iterator &iter, int n) { my_advance_helper(iter, n, typename std::iterator_traits<Iterator>::iterator_category()); } If as i understand, iterator_traits::iterator_category is just a typedef. What do parentheses do in last case? Do they return actual value of iterator_category in this way? Seems pretty obvious, but I need some confirmation. Sorry for possibly stupidity of question =)
If as i understand, iterator_traits::iterator_category is just a typedef Correct. What do parentheses do in last case? That's syntax for value initialisation of a temporary object.
69,883,459
69,883,689
int a=3; int *p=&a; decltype (a) k1; decltype (*p) k2; k1 is int type and k2 is int& type why?
Code #include <iostream> int main() { int a=3; int *p=&a; decltype (a) k1; decltype (*p) k2; return 0; } Output Declaration of reference variable 'k2' requires an initializer Explanation given to such phenomena is " decltype returns a reference type for expression that yield objects that can stand on the LHS of the assignment" see what *p yields value of of the object it points means 3 and what a yields value of itself which is 3. Now we talk manipulatively that *p refers to object a then a also refers to a itself. So I am not digesting the explanation given for such phenomena.
a is an unparenthesised id expression. *p is not an id expression. It is an indirection operation. decltype behaves differently when the operand is an unparenthesised id expression than when the operand is not an unparenthesised id expression. decltype of an unparenthesised id expression doesn't yield a reference type but rather the type of the entity named by the id expression. The type of the entity named by a is int. decltype of a non-unparenthesised-id-expression may yield either an lvalue reference or an rvalue reference or a non-reference depending on the value category of the expression. *p is an lvalue expression, so decltype (*p) yields an lvalue reference i.e. int&. see what *p yields value of of the object it points means 3 and what a yields value of itself which is 3. There is no difference between the expressions a and *p in regards to what the expressions themselves yield. They are both lvalue expressions of the same type and name the same object. The distinction is that one is an unparenthesised id-expression and thus applies for the exceptional case of decltype while the other is not.
69,883,538
69,883,627
I want to add a label in new widget using the Qt framework
This is my code : void maquette::on_btn_edit_clicked() { QWidget* wdg = new QWidget; wdg->resize(320, 340); wdg->setWindowTitle("Modiffier"); QLabel label1("matricule", wdg); label1.setGeometry(100, 100, 100, 100); wdg->show(); } the window shows up but the label didn't show
void maquette::on_btn_edit_clicked() { QWidget *wdg = new QWidget; wdg->resize(320,340); wdg->setWindowTitle("Modiffier"); QLabel *label1 = new QLabel("matricule",wdg); label1->setGeometry(100, 100, 100, 100); wdg->show(); }
69,884,158
69,884,201
std::regex, [:print:] graphical characters
I am trying to remove the non-printable characters using std::regex and [:print:] character class. The input string could be like this "\nTesting\t regex and \n\n\t printable characters \a\b set \0\f" Here \n, \t, \a, \b, \0, \f are non printable characters. I want to remove non-printable except \n and \t. std::regex nonprintable_regex("(^[[:print:]]+)"); std::smatch sm; if (std::regex_search(str, sm, nonprintable_regex)) { str = std::regex_replace(str, nonprintable_regex, ""); } But I am not getting the expected result. "\nTesting\t regex and \n\n\t printable characters set " I know I have to add something for \n and \t, but no idea how to add that condition. Any pointers/help, Thanks
You needn't test for a regex first, regex_search call here is redundant. The ^ anchor only matches at the start of string, so you are trying to match any one or more printable chars at the start of the string, which is not what you want. To match any non-printable char you need to use [^[:print:]], a negated bracket expression that matches any char but a printable char. You can use std::regex nonprintable_regex("(?![\n\t])[^[:print:]]"); // Or std::regex nonprintable_regex("[^[:print:]\n\t]+"); See the C++ demo: std::string str( "\nTesting\t regex and \n\n\t printable characters \a\b set \0\f" ); std::regex nonprintable_regex("(?![\n\t])[^[:print:]]"); str = std::regex_replace(str, nonprintable_regex, ""); std::cout << str << std::endl; The (?![\t\n]) negative lookahead restricts what [^[:print:]] can match, namely, it can no longer match tabs and newlines. Another way is to include \n and \t into the negated bracket expression itself to make it even faster, [^[:print:]\n\t]+.
69,884,650
69,884,844
Passing external data to std::set Compare functor
This is a contrived example, I know it doesn't make sense in this context. In my real case, v contains a larger class, and I can't refactor v due to other dependencies in the code base. Also, in the real case I'm not using std::set but it simplifies the example. Here are two example classes A and B that I know don't work, and I do understand why, but hopefully will illustrate what I'm trying to do: #include <set> #include <vector> using namespace std; struct A { A(initializer_list<float> init) : v(init) { for(size_t i = 0; i < init.size(); ++i) { s.insert(i); } } struct Less { Less(const vector<float>& v) : v(v) {}; bool operator()(size_t i, size_t j) { return v[i] < v[j]; } const vector<float>& v; }; vector<float> v; set<size_t, Less> s; }; struct B { B(initializer_list<float> init) : v(init) { for(size_t i = 0; i < init.size(); ++i) { s.insert(i); } } template<const vector<float>& v> struct Less { bool operator()(size_t i, size_t j) { return v[i] < v[j]; } }; vector<float> v; set<size_t, Less<v>> s; }; int main() { A a = {1., 2., 3.}; B b = {1., 2., 3.}; } In both cases s contains indicies that refer to elements in v, and Less is trying to compare the values in v using those indices. Is there a way to do this that I'm not seeing?
Your A approach is almost correct. It just needs 2 fixes: bool operator()(size_t i, size_t j) should be const. s must have a configured functor passed to it during construction. struct A { A(initializer_list<float> init) : v(init), s(v) { for(size_t i = 0; i < init.size(); ++i) { s.insert(i); } } // These must be manually defined if you need them, the default // ones won't be correct. A(const A&) = delete; A& operator=(const A&) = delete; struct MyLess { MyLess(const vector<float>& v) : v(v) {}; bool operator()(size_t i, size_t j) const { return v[i] < v[j]; } const vector<float>& v; }; vector<float> v; set<size_t, MyLess> s; }; I'm using unordered_map so maybe your idea will still work? Yes, the same principle applies to std::unordered_set. You just have to pass in both hash and key_equal during construction. Check out the documentation to identify the correct constructor to invoke.
69,884,782
69,884,848
Which overload does an operator use in C++?
Everybody knows that you can't concatenate 2 string literals using the + operator. #include <iostream> int main() { std::cout << "hello " + "world"; } // Error What's happening here is that you are trying to add 2 char* which is an error. You can however add a string literal to a std::string. #include <iostream> int main() { std::string s = "hello "; std::cout << s + "world"; } // Fine, prints hello world But what I found is that the below code is also valid. #include <iostream> int main() { std::string s = "world"; std::cout << "hello " + s; } // Fine, prints hello world I would imagine in the above example that you are trying to add a std::string to a char* but it works fine. I think it may just be using the std::string overload of the + operator. My question is what exactly is happening here and how does the operator decide which overload to use in a situation such as with 2 different classes with perfectly valid overloads being added together.
What's happening here is that you are trying to add 2 char* which is an error. To be a bit more correct, you're trying to add two arrays, each of which decay to const char*. My question is what exactly is happening here You're using these overloads: std::string operator+(const std::string& lhs, const char* rhs); std::string operator+(const char* lhs, const std::string& rhs); how does the operator decide which overload to use It uses the same overload resolution as normal functions do. The complete and precise description won't fit within this answer since overload resolution is quite complex. In short: There is a list of all functions by the same name. This is the overload set. If all arguments (operands in case of operator overload) can be converted to the formal parameters of the function, then that function is a viable candidate for the overload resolution. The candidates are ranked by a set of rules. Candidate requiring "less" conversion is ranked higher. If one candidate is unambiguously the most highly ranked candidate, then that overload will be called; otherwise there is an error.
69,885,122
69,885,234
What is the latest C++ standard to target Windows XP with Visual Studio?
Visual Studio 2019 seems to have good support for C++17. Unfortunately, it seems binaries built with it require the Universal CRT to be installed on the target machine, and the minimum supported OS for the UCRT is Vista. So, if I want to build a binary to target Windows XP, must I use a VS C++ compiler preceding the UCRT? Is that VS 2013, which has some support for C++11?
The latest toolset that has Windows XP support is v141_xp, that is the XP toolset from Visual Studio 2017. It has full C++14 support, and partial C++17 support. It comes with Visual Studio 2019, too: Unfortunately, it does not have full C++17 and C++20 support. The latest update of VS2019 has almost complete C++20 support in v142 toolset, and there is an update expected to make it complete, but it is without XP support. VS2022 drops Vista and support some C++23 in its v143 toolset. It still ships with v141_xp toolset as optional [deprecated] component. The v141_xp toolset still has the support of C++14, and partial C++17. It mostly corresponds to the Conformance table where they mention VS 2017. (Say, you will have std::any or terse static_assert, but won't be able to use shared_mutex, as it relies on Vista SRWLOCK) See also: How to install build tools for v141_xp for VC 2017?
69,885,600
69,887,857
SWIG doesn't work on Windows with MinGW-w64 when binding C++ and Python: DLL load failed while importing: The specified module could not be found
I am trying to bind C++ with Python on Windows using SWIG and MinGW-w64 g++. So far I got a factorial calculator function in C++: // factorial.cpp long fact(long num) { if (num <= 1) return 1; return num * fact(num - 1); } This is my factorial.i: %module factorial %{ extern long fact(long num); %} extern long fact(long num); I then use Command Prompt to build these: swig -python -c++ factorial.i This generates factorial_wrap.cxx and factorial.py. I then use MinGW-w64 g++ to build these: g++ -c factorial.cpp g++ -c -fpic factorial_wrap.cxx -IC:\Users\kritomas\AppData\Local\Programs\Python\Python38\include g++ factorial.o factorial_wrap.o -LC:\Users\kritomas\AppData\Local\Programs\Python\Python38\libs -shared -lpython38 -o _factorial.pyd So far no problem. The problem occurs when I then open up Python in Command Prompt and try to import these: C:\Users\kritomas\Desktop>python Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import factorial Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\kritomas\Desktop\factorial.py", line 15, in <module> import _factorial ImportError: DLL load failed while importing _factorial: The specified module could not be found. >>> Here's the error, as you can see above. I already tried Dependency Walker, that gave me 2 missing DLLs. After putting both of them into System32, it still happens. I already tried using extern "C" instead of extern: %module factorial %{ extern "C" long fact(long num); %} extern "C" long fact(long num); It just straight up removes fact(): C:\Users\kritomas\Desktop>g++ factorial.o factorial_wrap.o -LC:\Users\kritomas\AppData\Local\Programs\Python\Python38\libs -shared -lpython38 -o _factorial.pyd factorial_wrap.o:factorial_wrap.cxx:(.text+0x38d7): undefined reference to `fact' collect2.exe: error: ld returned 1 exit status I have the same issue with Python 3.9.7, the only reason why I downgraded to 3.8.10 is because it runs perfectly on my Linux Mint VM (which has Python 3.8.10), if instead of running: g++ -c -fpic factorial_wrap.cxx -IC:\Users\kritomas\AppData\Local\Programs\Python\Python38\include g++ factorial.o factorial_wrap.o -LC:\Users\kritomas\AppData\Local\Programs\Python\Python38\libs -shared -lpython38 -o _factorial.pyd I run: g++ -c -fpic factorial_wrap.cxx -I/usr/include/python3.8 g++ factorial.o factorial_wrap.o -shared -o _factorial.so It works perfectly: kritomas@kritomas-virtual-machine:~/Desktop$ python Python 3.8.10 (default, Sep 28 2021, 16:10:42) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import factorial >>> factorial.fact(5) 120 What am I doing wrong? Is there anything I am missing here? Please help me. Thanks in advance ;)
I met exactly the same problem after upgraded python to 3.9 on windows . After struggling for hours, I managed to solve it by manually copying some dlls from ***/mingw/bin/ where mingw32-g++ is found to where my ***.pyd is located. I'm sure that ***/mingw/bin/ has been appended to %PATH%, but don't know why python3.9 couldn't find it.
69,885,856
69,886,137
Custom equality compartor in unordered_map with initialization parameters
I am using std::unordered_map with a custom equality comparator class like so: class KeyCompare { private: HelperClass* helper; public: KeyCompare(HelperClass* helper): helper(helper) {} bool operator()(const Key& key1, const Key& key2) const { return helper->doStuff(key1, key2); } } At some point in my code I initialize my map like this: HelperClass helper; std::unordered_map<Key, Value, Hasher, KeyCompare> map; I would like to pass helper to the map such that KeyCompare objects are created with this helper. Is such a thing possible? I can use some global variable if absolutely necessary, but I would really like to avoid that.
Since your KeyCompare needs a helper it isn't default constructible. You must therefore supply an instance to the unordered_map when you construct it. Example: HelperClass helper; std::unordered_map<Key, Value, Hasher, KeyCompare> map{ 1, // bucket count Hasher{}, // hasher instance KeyCompare{&helper} // your KeyCompare with the helper }; Demo
69,886,437
69,886,752
Would it be sufficient for constexpr, consteval, and constinit to be definitions instead of keywords?
It seems that the rules for the compile-time keywords: constexpr, consteval and constinit are defined well enough for compilers to warn if you misapply the label. It would make sense that (much like inline) the compiler can, in all places, apply rules to determine if, in fact, code could have one of the compile-time keywords applied and, be forced, per language specification, to compile as much as possible as if the compile-time keywords had been applied. Or, at a minimum, if a compile-time keyword is applied to a function and the code would have qualified with had the correct compile-time keywords been applied. Compile that function, as if all the functions called had the correct compile-time keywords. Here is a simple example: #include <tuple> consteval std::tuple<int, int> init1(int x, int y) { return {x,y}; } std::tuple<int, int>& foo1() { static constinit std::tuple<int, int> x=init1(1,2); return x; } std::tuple<int, int> init2(int x, int y) { return {x,y}; } std::tuple<int, int>& foo2() { static std::tuple<int, int> x=init2(1,2); return x; } static std::tuple<int, int> x3=init2(1,2); std::tuple<int, int>& foo3() { return x3; } see it here: https://godbolt.org/z/KrzGfnEo7 Note that init1/foo1 are fully specified with compile-time keywords and there is no need for a guard variable, since it is initialized completely (not just 0 filled). The question is about why the compiler doesn't do the same in the cases of init2/foo2 or x3/foo3? Or more precisely why the compiler is allowed NOT to initialize fully at compile time. EDIT (as per comment) see (Why do we need to mark functions as constexpr?) constexpr would be required. I am concerned more with cases of consteval and constinit. Could the specification be modified to require trying to resolve code at compile-time and not failing because of the absence of constexpr? This would allow interface contracts to just use constexpr as per the related question.
Or, at a minimum, if a compile-time keyword is applied to a function and the code would have qualified with had the correct compile-time keywords been applied. The basis of your question is the assumption that these keywords are just variations on a theme, that a function which could have some of them ought to have a specific one based on the properties within the function alone. That's not reasonable. For functions, any function which could be constexpr could also be consteval. The difference is that one can be called during constant expression evaluation, and the other must be called only during constant expression evaluation. This is not an intrinsic property of the function definition; it is about how the function is to be used. The compiler should not override the decision of a programmer to be able to use a function at runtime just because the function definition just so happens to also be legit for consteval. It should also be noted that there is the requirements of a function definition for a consteval function are the same as for a constexpr function. It is also not possible to know if a function definition ought to be constexpr or not. Remember: while a constexpr function explicitly forbids certain constructs from appearing in the definition, it also permits you to have certain constructs in the definition that aren't allowed to be evaluated during constant evaluation... so long as you never actually allow those code paths to be evaluated during constant evaluation. So there are many function definitions that just so happen to be valid for constexpr even if the programmer didn't intend for them to be evaluated at compile-time. Lambdas get implicit constexpr definitions only because space in a lambda expression is at a premium. For variables, implicit constexpr makes even less sense. A variable ought to be constexpr if you intend to use it in a constant expression later on. This requires it to have an initializer that is a constant expression. Implicit constexpr is a problem because you might start relying on the implicit constexpr rule, then change the initializer to no longer be a constant expression and get a strange error in the place where you used its constexpr properties. It's better to make the user be explicit up-front than to misjudge what the user was trying to do and make a user think something is supposed to be valid when it wasn't intended. And constinit is solely about ensuring that a user never accidentally uses a non-constant expression to initialize the variable. Making it implicit would make absolutely no sense, as changing the expression to no longer be a constant expression wouldn't cause compilation to fail. Compilers are smart enough to know when a variable is initialized with a constant expression and can decide how to handle that on its own.
69,886,470
69,886,518
C++ How to store object in arrays without them deleted
I want to seek help on this issue I encountered when learning C++. I tried to store objects into an array directly, but realize the objects gets deconstructed right away. I could not figure out why exactly is this so. #include <iostream> class Thing{ public: ~Thing(){ std::cout<<"Thing destructing"; } }; int main(){ Thing arr[1]; arr[0] = Thing(); int x; std::cin>>x; };
In this statement arr[0] = Thing(); there is used the default copy assignment operator that assigns the temporary object created by this expression Thing() to the element of the array. After the assignment the temporary object is destroyed. To make it more clear run this demonstration program. #include <iostream> class Thing { public: ~Thing() { std::cout<<"Thing " << i << " destructing\n"; } Thing & operator =( const Thing & ) { std::cout << "Thing " << i << " assigning\n"; return *this; } Thing() : i( ++n ) { std::cout << "Thing " << i << " constructing\n"; } private: size_t i; static size_t n; }; size_t Thing::n = 0; int main() { { Thing arr[1]; arr[0] = Thing(); } std::cin.get(); return 0; } Its output is Thing 1 constructing Thing 2 constructing Thing 1 assigning Thing 2 destructing Thing 1 destructing
69,886,814
69,886,989
Reference to initializer_list in noexcept specifier of std::optional
I have a question about this code: explicit constexpr optional(in_place_t, initializer_list<_Up> __il, _Args&&... __args) noexcept(is_nothrow_constructible_v<_Tp, initializer_list<_Up>&, _Args...>) : _Base(std::in_place, __il, std::forward<_Args>(__args)...) { } Why is the reference used here? Initializer list is passed to std::optional as value. I guess it might be related with the fact that it is a named argument in this context, but I am not sure.
When you use is_nothrow_constructible and various other type traits, there is a convention that an lvalue reference type T& means "lvalue of type T" whereas a non-reference type T means "rvalue of type T". In this case, a test is being done to see whether _Tp is nothrow constructible given that the first argument will be an lvalue of type initializer_list<_Up>.
69,887,033
69,887,138
How to get a lvalue reference to a bit in std::bitset
I was trying to do the following: std::bitset<2000> a_bit_set{}; auto& a_bit = a_bit_set[5]; if (complicated_predicate(a_bit, other_params)) { a_bit.flip(); } but clang complains: non-const lvalue reference to type 'std::bitset<2000>::reference' cannot bind to a temporary of type 'std::bitset<2000>::reference' I am suspecting this is because the operator[] is returning a rvalue rather than a lvalue here. But according to cppreference, there is a special class std::bitset<>::reference that should allow me to reference a particular bit in a bitset. My question is: Can I get a lvalue reference to a particular bit in a bitset (akastd::bitset<>::reference)?
How to get a lvalue reference to a bit in std::bitset You don't. std::bitset doesn't contain any objects that represent an individual bit, and thus you cannot have a reference to such object. aka std::bitset<>::reference std::bitset<>::reference isn't an lvalue reference. It is an object - a reference wrapper. The subscript operator returns that object as a prvalue. You can simply use a copy of that reference wrapper like this: auto a_bit = a_bit_set[5]; Or you can use an rvalue reference which extends the lifetime of the prvalue: auto&& a_bit = a_bit_set[5]; I wouldn't use the latter in this example since it introduces unnecessary complexity. But it can potentially be useful in some other cases that involve templates with a reference alias that may be either a true reference or a reference wrapper depending on template arguments.
69,887,050
69,887,353
error: const method that returns an array of pointers by reference
class Board{ private: Shape shapes[100]; Tile* tiles[16]; public: const Shape (&getShapes() const)[100]{return shapes;}; // (1) const Tile* (&getTiles() const)[16]{return tiles;}; // (2) }; I made this class called Board that has two methods returning an array by reference. Method (2) reports an error: qualifiers dropped in binding reference of type "const Tile *(&)[16]" to initializer of type "Tile *const [16]" I fixed this error by writing const to the return type in method (1), but it doesn't work for method (2). Why is this error occurring?
The element type of this array Tile* tiles[16] is Tile *. As the member function is a constant member function then the function should return the array by reference with constant elements. That is it should be declared like Tile* const (&getTiles() const)[16]{return tiles;} That is you may not assign new values to the pointers stored in the array.
69,887,776
69,888,002
Custom Types' Names Even For Templates With Variadic Arguments
first of all we need a little introduction, so here we go. I'd like to write a functional struct that'll be able to retrieve name of a certain type, including templates. It'll return type's name from type_info or own defined custom name. Here's a tiny logger which will need the name of a struct. #define LOG(x) FunctionLog(#x, x) template<typename _Ty> void FunctionLog(const char* name, const _Ty& value) { // TypeName'll be introduced later. std::cout << name << ": " << static_cast<const char*>(TypeName<_Ty>::c_Name) << " = " << value << '\n'; } // Simple const char* wrapper, to easily concanate them with an operator|(). // I decided to use const char* instead of std::string due to memory. struct CString { const char* Content; explicit CString(const char* content) : Content(content) {} CString operator|(const CString& other) { return CString{ strcat(_strdup(Content), _strdup(other.Content)) }; } operator const char*() const { return Content; } }; template<typename _Ty> struct TypeName { static inline const CString c_Name = CString{ typeid(_Ty).name() }; } // example of implementing that struct for std::vector<_Ty> template<typename _Ty> struct TypeName<std::vector<_Ty>> { static inline const CString c_Name = CString{ "std::vector<" } | TypeName<_Ty>::c_Name | CString{ ">" }; }; And my problem is, how to make it work for std::tuples as I don't know how to do that, because the tuple has a various number of template arguments. And I would like it to look like so: std::tuple<int, int> -> std::tuple<int, int>, std::tuple<std::vector<int>, int> -> std::tuple<std::vector< int>, int>. So every argument of that tuple template should call corresponding TypeName<_Ty>. If something is unclear, please ask as I could miss something.
It seems you want something like (C++17): template<typename ... Ts> struct TypeName<std::tuple<Ts...>> { static inline const CString c_Name = (CString{ "std::tuple<" } | ... | TypeName<Ts>::c_Name) | CString{ ">" }; };
69,888,746
69,888,793
No such file 'main.o' error when execute make
I have the following files all in the same directory. . ├── Makefile ├── lexer.cpp ├── lexer.h ├── parser.cpp ├── parser.h ├── main.cpp main.cpp depends on parser.h and lexer.h. lexer.cpp depends on lexer.h parser.cpp depends on parser.h which in turn depends on lexer.h. I have a Makefile to compile the files and link them as follows. all: main main: main.o lexer.o parser.o $(CXX) $(CFLAGS) -o $@ mccomp.o lexer.o parser.o main.o: main.cpp lexer.h parser.h $(CXX) $(CFLAGS) -c lexer.h parser.h lexer.o: lexer.cpp lexer.h $(CXX) $(CFLAGS) -c lexer.h parser.o: parser.cpp parser.h lexer.h $(CXX) $(CFLAGS) -c parser.h lexer.h clean: rm -rf main When I execute make I get the following error. clang-11: error: no such file or directory: 'main.o' clang-11: error: no such file or directory: 'lexer.o' clang-11: error: no such file or directory: 'parser.o' I don't know why this is happening given that the %.o rules should have generated these files. How do I fix this?
None of the rules for generating .o files actually mention the cpp file they're supposed to compile. Add the .cpp file (or the magic variable $<) to the recipe instead of all the header files: main.o: main.cpp lexer.h parser.h $(CXX) $(CFLAGS) -c main.cpp -o $@ or main.o: main.cpp lexer.h parser.h $(CXX) $(CFLAGS) -c $< -o $@ Also note that there is a built-in rule for compiling .cpp files, so it suffices to state the dependencies: main.o: main.cpp lexer.h parser.h lexer.o: lexer.cpp lexer.h parser.o: parser.cpp parser.h lexer.h Make will then recompile the .o files if one of the input files changes. Note that it uses CXXFLAGS instead of CFLAGS.
69,888,811
69,888,983
Consistently parse various date and time formats with Howard Hinnant's date library
I need to be able to parse and store various dates, times, or both according to a subset of the ISO-8601 standard. The dates are in the formats: YYYY YYYY-mm YYYY-mm-dd The times are in the formats: HH:MM:SS HH:MM:SS.ffffff If a date and time are both defined, then a timezone must also be defined, like so: YYYY-mm-ddTHH:MM:SS.ffffff+ZZ:ZZ For example: 2012-03-04T05:06:07.123456+07:00 I tried to use Howard Hinnant's date library, the same one in the C++20 standard. It seems I need to use specific types to parse different formats which is slightly annoying. I would rather be able to parse and store any format within the same type. To illustrate the problem: sys_time<microseconds> sys_us; microseconds us; year_month ym; year y; std::istringstream iss; iss.str("2012-03-04T05:06:07.123456+07:00"); iss >> date::parse("%FT%T%Ez", sys_us); // Only works with this type. (The others can't parse this much info.) assert(!iss.fail()); iss.str("2012-03-04"); iss >> date::parse("%F", sys_us); // If the date has the full year, month, and day, this works. assert(!iss.fail()); iss.str("2012-03"); // iss >> date::parse("%Y-%m", sys_us); // This fails; day is missing. iss >> date::parse("%Y-%m", ym); // Works. assert(!iss.fail()); iss.str("2012"); // iss >> date::parse("%Y", sys_us); // This fails. // iss >> date::parse("%Y", ym); // Also fails; month is missing. iss >> date::parse("%Y", y); // Works. assert(!iss.fail()); iss.str("05:06:07.123456"); // iss >> date::parse("%T", sys_us); // Also fails; unhappy with missing date. iss >> date::parse("%T", us); // Must use duration type for time instead. assert(!iss.fail()); It would be much nicer if I could date::parse(format, obj) where obj didn't need to change types. Is that possible?
The only way to store them all in the same type is to pick the one with the most information (sys_time<microseconds>), then do the parse in the partial types as you've shown and add defaults for those values not parsed. For example: iss.str("05:06:07.123456"); iss >> date::parse("%T", us); // Must use duration type for time sys_us = sys_days{year{0}/1/1} + us; // Add defaulted date
69,888,911
69,888,945
Passing a function to another function via "pass by value"
Code void printA() { cout << "A\n"; } void print1( void (*func_ptr)(void) ) { func_ptr(); } void print2( void func(void)) { func(); } int main() { //Method 1a (passing function pointer) print1(&printA); //Method 1b (why does it work even though I didn't pass a reference or a pointer?) print1(printA); //Method 2 (passing the whole function ?) print2(printA); return 0; } Method 1a makes sense: print1 was expecting a reference or pointer. Question 1: Method 1b does not make sense: Why doesn't the compiler throw an error. Why does it work, even though I didn't pass the reference or the pointer of printA() to print1()? Question 2: Method 2a implies a new copy of the function printA() is made and passed to function print2(). In other words, is the function printA() is passed to function print2() by value? Question 3: Are identifiers of functions references? (this might help) Much appreciated thanks.
The parameter of this function declaration void print2( void func(void)); is adjusted by the compiler to pointer to the function type that is to void print2( void ( *func )(void)); The both above declarations declare the same one function and may be both present in the same compilation unit though the compiler can issue a message that there are redundant function declarations. On the other hand, a function designator used as an argument for such a function shown above is implicitly converted to a pointer to the function. You may even write for example print2(**********printA); Thus as for this your question Method 2a implies a new copy of the function printA() is made and passed to function print2(). In other words, is the function printA() is passed to function print2() by value? then neither copy of the function is passed. It is a pointer to the function that is passed.
69,889,110
69,889,340
I need a Function to read a key press in C++
I'm trying to create a program who check if a specific key in keyboard is pressed and return a boolean value into a while loop something like this: int main(int argc, char** argv){ std::cout << "Press the spacebar to exit loop"; while (true){ if (IsKeyPressed("space")){ break; } } return 0; } I use Linux if this matters.
The C++ standard alone does not have any functionality for reading input. You have to use an external library if you want to read input. Any game development library will have features for this, such as SFML. With SFML: #include <SFML/Window.hpp> int main(int argc, char** argv){ std::cout << "Press the spacebar to exit loop"; while (true){ if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){ break; } } return 0; }
69,889,807
69,889,884
Why are my member functions/class variables outputting the wrong numbers?
I am learning how to use classes in c++. Right now I'm working on a small program which should display the miles per gallon of a vehicle based on the given number of miles and gallons. The assignment says to call member functions within the main function in order to set the member variables within the Auto class. Here is my code: #include <iostream> using namespace std; class Auto { public: string model; int milesDriven; double gallonsOfGas; double calculateMilesPerGallon(int milesDriven, double gallonsOfGas) { return milesDriven / gallonsOfGas; } void setModel(string newModel){ model = newModel; } void setMilesDriven(int newMiles){ milesDriven = newMiles; } void setGallonsOfGas(double newGallons){ gallonsOfGas = newGallons; } void output(){ cout << "A " << model << " was driven " << milesDriven << " miles, and used " << gallonsOfGas << endl; cout << "This car gets " << calculateMilesPerGallon(milesDriven, gallonsOfGas) << "mpg."; } }; int main() { Auto modelFunction; Auto milesFunction; Auto gasFunction; Auto outputFunction; string carModel = "Toyota Camry"; int carMiles = 100; double carGallons = 10; modelFunction.setModel(carModel); milesFunction.setMilesDriven(carMiles); gasFunction.setGallonsOfGas(carGallons); outputFunction.output(); return 0; } It's supposed to display something like "A Toyota Camry was driven 100, and used 10 gallons of gas, and gets 10 mpg." Instead, my output shows "A was driven -1538932792 miles, and used 4.66265e-310 This car gets -infmpg." What am I doing that is causing the output to be like this? I just started using classes so I don't have much experience with them. Thanks for the advice.
The error you're encountering is because you're creating four different Auto objects, each of which will have their own member variables. If you change your main function to the following, it will work: int main() { Auto car; string carModel = "Toyota Camry"; int carMiles = 100; double carGallons = 10; car.setModel(carModel); car.setMilesDriven(carMiles); car.setGallonsOfGas(carGallons); car.output(); return 0; } Note that there is now only one 'Auto' object entitled 'car'.
69,889,858
69,916,351
How can reordering the linked libraries fix multiple definitions error?
I faced a situation where different order of linking librdkafka and the Pulsar C++ client does matter, because both of them include their version of LZ4 compression. The linking fails because of multiple definitions of LZ4 functions (both librdkafka and Pulsar have the same names for those functions). I checked the static libraries, but I couldn't find anything suspicious, why it works in one order and doesn't in the another. Because it is hard to provide a minimal working example with those big libraries, I tried to reproduce the same situation, and I was able to do so. I created a small project where the linking order matters. libA.hpp: #pragma once void NotClashingFunctionA(); void ClashingFunction(); libA.cpp: #include "libB.hpp" #include <iostream> void NotClashingFunctionA() { std::cout << "Not clashing function A\n"; } void ClashingFunction() { std::cout << "Clashing function A\n"; } libB.hpp: #pragma once void NotClashingFunctionB(); libB.cpp: #include "libB.hpp" #include <iostream> void NotClashingFunctionB() { std::cout << "Not clashing function B\n"; } libBSub.hpp: #pragma once void ClashingFunction(); libBSub.cpp: #include "libBSub.hpp" #include <iostream> void ClashingFunction() { std::cout << "Clashing function B\n"; } main.cpp: #include "libA.hpp" #include "libB.hpp" #include "libBSub.hpp" int main() { NotClashingFunctionA(); NotClashingFunctionB(); ClashingFunction(); return 0; } CMakeLists.txt: project(clashing) add_library(A STATIC libA.cpp) add_library(B STATIC libB.cpp libBSub.cpp) add_executable(working main.cpp) target_link_libraries(working A B) add_executable(failing main.cpp) target_link_libraries(failing B A) From the logs I can clearly see that working just links fine: clang++ -g -rdynamic CMakeFiles/working.dir/main.cpp.o -o working libA.a libB.a make[3]: Leaving directory 'build' [100%] Built target working But failing fails to link: clang++ -g -rdynamic CMakeFiles/failing.dir/main.cpp.o -o failing libB.a libA.a ld: libA.a(libA.cpp.o): in function `ClashingFunction()': libA.cpp:9: multiple definition of `ClashingFunction()'; libB.a(libBSub.cpp.o):libBSub.cpp:5: first defined here clang-12: error: linker command failed with exit code 1 (use -v to see invocation) I removed the common prefixes to make the logs more readable. As you can see the only difference between the two is the linking order A and B. I don't know why it works in A B order, and not B A order. If you cannot explain it in details, helping keywords are also very appreciated, because I have absolutely no idea why it is happening.
To understand why, read this (earlier) post or this (nicer) one. To make a concrete example: suppose main.o defines main(), fn(), and references a() and b(). libA.a contains a.o which defines a() libB.a contains b.o which defines b(), and also a1.o which defines a() and fn(). Now, if you link with gcc main.o -lA -lB, the link will succeed (a.o from libA.a and b.o from libB.a will be selected into the link, and no symbol conflicts will arise. Notably, a1.o from libB.a will not be selected into the link). But if you link with gcc main.o -lB -lA, then fn() will be multiply defined (because both a1.o and b.o from libB.a will be selected into the link, but the definition of fn() in a1.o will be in conflict with the definition of fn() in main.o).
69,890,022
69,890,834
fstream not working properly with russian text?
I work with russian a lot and I've been trying to get data from a file with an input stream. Here's the code, it's supposed to output only the words that contain no more than 5 characters. #include <iostream> #include <fstream> #include <string> #include <Windows.h> using namespace std; int main() { setlocale(LC_ALL, "ru_ru.utf8"); ifstream input{ "in_text.txt" }; if (!input) { cerr << "Ошибка при открытии файла" << endl; return 1; } cout << "Вывод содержимого файла: " << "\n\n"; string line{}; while (input >> line) { if (line.size() <= 5) cout << line << endl; } cout << endl; input.close(); return 0; } Here's the problem: I noticed the output didn't pick up all of the words that were actually containing less than 5 characters. So I did a simple test with the word "Test" in english and the translation "тест" in russian, the same number of characters. So my text file would look like this: Test тест I used to debugger to see how the program would run and it printed out the english word and left the russian. I can't understand why this is happening. P.S. When I changed the code to if (line.size() <= 8) it printed out both of them. Very odd I think I messed up my system locale somehow I don't know. I did one time try to use std::locale without really understanding it, maybe that did something to my PC I'm not really sure. Please help
I'm very unsure about this but using codecvt_utf8 and wstring_convert seems to work: #include <codecvt> // codecvt_utf8 #include <string> #include <iostream> #include <locale> // std::wstring_convert int main() { // ... while (input >> line) { // convert the utf8 encoded `line` to utf32 encoding: std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> u8_to_u32; std::u32string u32s = u8_to_u32.from_bytes(line); if (u32s.size() <= 5) // check the utf32 length std::cout << line << '\n'; // but print the utf8 encoded string } // ... } Demo
69,890,232
69,890,275
Converting Python Script to C++
I have a Python script that runs properly. But I need to implement this script to a root macro in C++. As I am not really familiar with python syntax, I am having a hard time. ATOMIC_MASS = 931.4940954e6 class ReducedMomentum: def __init__(self, mass): self.mass = mass def __call__(self, kinetic_energy): return math.sqrt(kinetic_energy * (kinetic_energy + 2 * self.mass)) / self.mass class MassFraction: def __init__(self, tritium_mass, electron_mass): self.tritium_mass = tritium_mass self.electron_mass = electron_mass def __call__(self, spectator_mass): return spectator_mass / (spectator_mass + self.tritium_mass + 2 * self.electron_mass) class Ktilde: def __init__(self, alpha_1, tritium_mass, electron_mass_eV): self.alpha_1 = alpha_1 self.mass_fraction = MassFraction(tritium_mass, electron_mass_eV / ATOMIC_MASS) self.reduced_momentum = ReducedMomentum(electron_mass_eV) def __call__(self, spectator_mass, electron_kinetic_energy): return self.alpha_1 * self.mass_fraction(spectator_mass) * self.reduced_momentum(electron_kinetic_energy) I have understood the first few lines but the main problem is the following part: self.mass_fraction = MassFraction(tritium_mass, electron_mass_eV / ATOMIC_MASS) ant the line below this. How can I convert these lines to C++? What do they exactly mean mathematically? The familiar line comes again a few times as: ktilde = Ktilde(alpha_1, spectator_masses, electron_mass) mass_spectator = parse_spectator_mass(args, parser) ktilde_value = ktilde(mass_spectator, args.energy) print('{:.4f}'.format(ktilde_value)) This is probably rather trivial but I couldn't find any solution on Google. Thanks a lot!
When the class calls itself like that it's the __call__ method in the class that it is calling, like operator(). __init__ is like a constructor and is called when the class is instantiated, so everything in init is available by the time the class gets to __call__. class ReducedMomentum: # here is where an instance of the object calls itself def __call__(self, kinetic_energy): """Example reduced_momentum = ReducedMomentum(5) reduction = reduced_momentum(5) """ return math.sqrt(kinetic_energy * (kinetic_energy + 2 * self.mass)) / self.mass So for your Ktilde class, for example class Ktilde: def __init__(self, alpha_1, tritium_mass, electron_mass_eV): """Constructor needing above arguments alpha_1: float? tritium_mass: float? electron_mass_eV: float? Example: k_tilde = Ktilde(1., 1., 1.) # initialize with params some_spectator_mass = 2. # some other relevant numbers some_electron_KE = 302.1 calculation = k_tilde(some_spectator_mass, some_electron_KE) # uses the __call__ method in this class """ self.alpha_1 = alpha_1 self.mass_fraction = MassFraction(tritium_mass, electron_mass_eV / ATOMIC_MASS) self.reduced_momentum = ReducedMomentum(electron_mass_eV) def __call__(self, spectator_mass, electron_kinetic_energy): return self.alpha_1 * self.mass_fraction(spectator_mass) * self.reduced_momentum(electron_kinetic_energy) So this does ktilde = Ktilde(alpha_1, spectator_masses, electron_mass) # ktilde instance mass_spectator = parse_spectator_mass(args, parser) # some function to get mass of spectator ktilde_value = ktilde(mass_spectator, args.energy) # uses __call__ method of KTilde, args is some object (maybe from argparser) that has an energy attribute print('{:.4f}'.format(ktilde_value))
69,890,248
69,891,912
How to inject an event like button press programmatically in gtkmm C++?
I am very new to C++ gtkmm (Linux) programming. I developing a program where I need a button to be clicked in the callback function of another button on the gui. I have tried button.activate() But it only animates the button click but the callback function is not called. When I click the button manually, the callback function is called. Please explain how to inject event into the gtkmm C++ coding. Events may include button press, key press etc.
Here is an example that works with Gtkmm 3.24 for a button click: #include <iostream> #include <gtkmm.h> class MainWindow : public Gtk::ApplicationWindow { public: MainWindow(); private: Gtk::Grid m_layout; Gtk::Label m_label; Gtk::Button m_buttonA; Gtk::Button m_buttonB; }; MainWindow::MainWindow() : m_buttonA{"A"} , m_buttonB{"B"} { m_label.set_text("Click a button..."); m_buttonA.signal_clicked().connect( [this](){ std::cout << "Button A clicked!" << std::endl; // Emits "clicked" on button B, just like when // a user clicks it: m_buttonB.clicked(); m_buttonB.activate_action("clicked"); } ); m_buttonB.signal_clicked().connect( [this](){ std::cout << "Button B clicked!" << std::endl; } ); m_layout.attach(m_buttonA, 0, 0, 1, 1); m_layout.attach(m_buttonB, 1, 0, 1, 1); add(m_layout); } int main(int argc, char *argv[]) { std::cout << "Gtkmm version : " << gtk_get_major_version() << "." << gtk_get_minor_version() << "." << gtk_get_micro_version() << std::endl; auto app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.base"); MainWindow window; window.show_all(); return app->run(window); } With Gtkmm 4 however, the clicked() method seems to have been removed from Gtk::Button's interface. By looking at the new interface, there is a activate_action method (inherited from Gtk::Widget) that, maybe, could work. However, I don't have Gtkmm 4 here, so I could not try it.
69,890,284
69,890,285
QSlider in QT misbehaves in new MacOS Monterey (v12.0.1) . Any workaround?
As reported here (https://bugreports.qt.io/browse/QTBUG-98093), QSlider component in QT is not working well in the new MacOS update. If I add two or more horizontal sliders in the same window, dragging the grip in one slider affects the other ones. It may cause all of them to move together or may make the next one jump to an unexpected position. This code below can reproduce the issues: #include <QApplication> #include <QDialog> #include <QVBoxLayout> #include <QSlider> class Dialog: public QDialog { QSlider* brokenSlider; public: explicit Dialog(QWidget *parent = nullptr):QDialog(parent){ auto mainLayout = new QVBoxLayout; brokenSlider = new QSlider(Qt::Horizontal, this); mainLayout->addWidget(brokenSlider); connect(brokenSlider, &QSlider::valueChanged, [&](){this->update();}); mainLayout->addWidget(new QSlider(Qt::Horizontal, this)); mainLayout->addWidget(new QSlider(Qt::Horizontal, this)); setLayout(mainLayout); } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); Dialog g; g.exec(); } I'm looking for a workaround for this Apple/QT bug.
I was able to fix the issue applying a custom stylesheet to the slider. However, doing that also creates a problem with the ticks that are not displayed. The solution I found was to extend QSlider and paint then manually: myslider.h: #pragma once #include <QStylePainter> #include <QStyleOptionSlider> #include <QStyleOptionComplex> #include <QSlider> #include <QColor> #include "math.h" class MySlider:public QSlider { public: explicit MySlider(Qt::Orientation orientation, QWidget *parent = nullptr):QSlider(orientation, parent){}; explicit MySlider(QWidget *parent = nullptr):QSlider(parent){ this->setStyleSheet("\ QSlider::groove:horizontal {\ height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */ \ background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #B1B1B1, stop:1 #c4c4c4);\ margin: 2px 0;\ }\ \ QSlider::handle:horizontal {\ background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);\ border: 1px solid #5c5c5c;\ width: 18px;\ margin: -2px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */ \ border-radius: 3px;\ }\ "); }; protected: virtual void paintEvent(QPaintEvent *ev) { QStylePainter p(this); QStyleOptionSlider opt; initStyleOption(&opt); QRect handle = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); // draw tick marks // do this manually because they are very badly behaved with style sheets int interval = tickInterval(); if (interval == 0) { interval = pageStep(); } if (tickPosition() != NoTicks) { for (int i = minimum(); i <= maximum(); i += interval) { int x = std::round((double)((double)((double)(i - this->minimum()) / (double)(this->maximum() - this->minimum())) * (double)(this->width() - handle.width()) + (double)(handle.width() / 2.0))) - 1; int h = 4; p.setPen(QColor("#a5a294")); if (tickPosition() == TicksBothSides || tickPosition() == TicksAbove) { int y = this->rect().top(); p.drawLine(x, y, x, y + h); } if (tickPosition() == TicksBothSides || tickPosition() == TicksBelow) { int y = this->rect().bottom(); p.drawLine(x, y, x, y - h); } } } QSlider::paintEvent(ev); } }; In QT Creator, if using forms, the file above needs to be added to the promoted widgets list and then each QSlider needs to be promoted to use this class. Partial credits to: https://stackoverflow.com/a/27535264/6050364 Update (Dec 2021): QT fixed this issue in QT 6.2.3
69,890,534
69,893,486
Why need to forward constructor parameters when inheriting from variadic arguments?
I know the title makes exactly 0 sense, I am challenging you to edit it according to the question. I have the following wrapper that wraps lambda expressions (inherits from them) and uses their operator()'s for overloading. #include <iostream> template<typename... F> struct OverloadSet : public F... { OverloadSet(F&&... f) : F(std::forward<F>(f))...{} using F::operator() ...; }; template<typename... T> auto overloads(T...t) { return OverloadSet<T...>(std::forward<T>(t)...); } auto s = overloads( [](int s) {std::cout << typeid(s).name() << " " << s << std::endl; }, [](double d) {std::cout << typeid(d).name() << " " << d << std::endl; } ); int main() { auto s = overloads( [](int s) {std::cout<<typeid(s).name()<<" " << s << std::endl; }, [](double d) {std::cout << typeid(d).name() << " "<< d << std::endl; } ); s(3); s(3.2); } The code is copied from C++ design patterns book (highly recommend) And I have made my observation that the constructor params are redundant as we only need operator()'s of base classes. So I made the exact example but with more modest constructor: OverloadSet(F&&... f) {} From this point I have problems to understand whether this program is ill formed or not because have different reaction from different compilers: GCC 11.2 Output of x86-64 gcc 11.2 (Compiler #1) In instantiation of 'OverloadSet<F>::OverloadSet(F&& ...) [with F = {<lambda(int)>, <lambda(double)>}]': required from 'auto overloads(T ...) [with T = {<lambda(int)>, <lambda(double)>}]' required from here error: use of deleted function '<lambda(int)>::<lambda>()' Clang (latest) error: constructor for 'OverloadSet<(lambda at <source>:16:2), (lambda at <source>:17:2)>' must explicitly initialize the base class '(lambda at <source>:16:2)' which does not have a default constructor OverloadSet(F&&... f) {}// F(std::forward<F>(f))...{} MSVC2019 (with C++20 enabled) Compiles and prints: int 3 double 3.2 So the questions are: Whether the program is well formed? If not, why do we need to forward arguments if we only use operator()'s of base classes?
The lambda does not have a default constructor, I guess. It is more like this: class A { public: A(int a) {} }; class B { public: B(double b) {} }; class C : public A, public B { public: C() {} // error };
69,890,646
69,890,707
Can compiler make some function constexpr on its own?
Can compiler evaluate a function that is not marked as constexpr at a compiler time, or all function without constexpr that are not inline will only be evaluated at a runtime?
A compiler is allowed to evaluate some functions at compile time even if not marked as constexpr, yes. For example: int foo() { int result = 0; for (int i = 1; i <= 100; i++) result += i; return result; } const int s = foo(); The compiler can optimize the initialization of s by simply giving it the value 5050. However, the compiler cannot allow you to use the result of foo() as a template argument (as if you had simply written 5050), because it's not a valid constant expression. It must issue a diagnostic. In other words, constexpr does not control whether a function may be evaluated at compile time. It controls whether a function is allowed to be called in a context that requires a constant expression.
69,890,737
69,893,183
Printing a list of numbers from a vector in C++
I'm trying to write a program that asks the user for integers and places them in a vector until the integer given by the user is 0. Then it should print the integers in the vector. Here is my code: #include <iostream> #include <vector> using namespace std; template <typename A> void print_numbers(const vector<A> &V){ cout << "The numbers in the vector are: " << endl; for(int i=0; i < V.size(); i++) cout << V[i] << " "; } int main() { vector<int> numbers; int input; cout << "Please type your numbers" << endl; cin >> input; while ((cin >> input) && input != 0) numbers.push_back(input); print_numbers(numbers); return 0; } It prints everything except the first integer. Any ideas?
Your first input is not stored into the numbers vector. You have cin >> input; and then directly afterward while ((cin >> input) && input != 0) numbers.push_back(input); This means that you stored the first number into input, but then wrote over it directly afterwards by doing cin >> input in the while loop without calling the push_back function on the first input.
69,890,807
69,926,774
Understanding C++ visibility support
-- as described at the GCC Wiki - Visibility. I have exercised How to use the attribute((visibility("default")))? and Simple C++ Symbol Visibility Demo but still do not understand some parts of the GCC Wiki - Visibility article. At its Step-by-step_guide you find For every non-templated non-static function definition in your library (both headers and source files), decide if it is publicly used or internally used In the other examples I found that it is sufficient to only decorate the declarations in the header files. Why also decorate the definitions in the source files? If it is publicly used, mark with FOX_API like this: extern FOX_API PublicFunc() I haven't seen this extern keyword in the other examples and I have never used it for public functions. Why do I have to use it here? The given macro starts with #ifdef FOX_DLL // defined if FOX is compiled as a DLL If using CMake where or how is FOX_DLL defined?
In the other examples I found that it is sufficient to only decorate the declarations in the header files. Why also decorate the definitions in the source files? If global function is declared in a header and that header is included in source file where function is defined, annotation in header will suffice (compiler will indeed pick up the attribute from the header). Otherwise you'll need to annotate it in source code. I haven't seen this extern keyword in the other examples and I have never used it for public functions. Why do I have to use it here? The extern keyword is optional in function declarations but it's often used for clarity.
69,891,024
69,891,371
Taking the address of a temporary object of type 'z3::expr'
I want to access the address of a z3::expr inside a z3::expr_vector. z3::context ctx; z3::expr_vector x(c); // populate x with some push_backs ... // access the address of the first element: z3::expr* t1 = &x[0]; // -Waddress-of-temporary: Taking the address of a temporary object // of type 'z3::expr' I took a look at this question, but that only talks about the z3::expr's constructor. If I use a std::vector<z3_expr> instead it works: std::vector<z3::expr> x2; ... z3::expr* t2 = &x2[0]; // This works Is this intended, i.e. is the address not available to the user? Should I maintain an std::vector<z3::expr> instead? Additionally, if I want to create a z3::expr* conditionally, how does go about it? z3::expr* e; if (some condition) { e = &(ctx.bv_const("s", 1)); // this gives the same compiler warning. } else { e = &(ctx.bv_const("s", 1)); // as does this. } // use e Some pointers regarding the correct usage would be really helpful.
z3::expr_vector is a typedef for z3::ast_vector_tpl, whose operator[] returns elements by value, ie a temporary copy. So your z3::expr_vector example fails, because it is illegal to take the memory address of a temporary. AFAICS, ast_vector_tpl does not have any methods that return access to its elements by reference/pointer, only by value. Neither does its iterator (so, something like z3::expr* t1 = &*(x.begin()); would not work, either). std::vector, on the other hand, has an operator[] (and an iterator with an operator*) that returns access to its elements by reference instead, which is why your std::vector example works.
69,891,361
69,891,644
How is 0xe+foo parsed?
How is 0xe+foo parsed? I know that it is parsed as a whole preprocessing number, but i dont get why, because, how can the operator "+" be a pp-number? pp-number : digit . digit pp-number digit pp-number identifier-nondigit pp-number ’ digit pp-number ’ nondigit pp-number e sign pp-number E sign pp-number p sign pp-number P sign pp-number . Here is no "+", so thats why i thought it is parsed as: 0xe + foo What am I missing? I know the rule of maximum match, but how is the "+" sign a pp-number? If I would have x+++++y it is parsed as x ++ ++ + y, which makes sense, but how is then 0xe+foo not parsed as 0xe + foo?
+ matches sign in the production you quoted.
69,891,734
69,891,803
Difficulties getting a constexpr property from a constexpr array
I'm having this issue where I can't seem to, at compile time, check if all elements in an std::array are equal. It seems so simple and I'm not new to C++ by any means, but I can't figure it out! (I would just use <algorithm> but sadly those aren't marked constexpr in C++17, and I'm stuck with C++17 because CUDA.) Here's an example (that doesn't compile). #include <array> int main() { constexpr std::array<int, 3> a {0, 0, 0}; constexpr bool equal = [=](){ for (int i = 1; i < 3; i++) { if constexpr (a[0] != a[i]) return false; } return true; }(); } Why does a[0] != a[i] not qualify as constexpr? (This is the error GCC and Clang give me.) How do I get the result I need?
Since your i is not a compile-time constant, you cannot use if constexpr. A simple if is enough which still can check your array at compile-time. #include <array> int main() { constexpr std::array<int, 3> a {0, 0, 0}; constexpr bool equal = [=](){ for (int i = 1; i < 3; i++) { if (a[0] != a[i]) //^^ return false; } return true; }(); }
69,891,999
71,467,219
How do you push_back a shared_ptr variable to a vector of shared_ptrs in C++?
I’m a C++ beginner with a background in Python, Java, and JS, so I’m still learning the ropes when it comes to pointers. I have a vector of shared pointers. Inside of a different function, I assign a shared pointer to a variable and add it to the vector. If I try to access the added element after that function exits, a segmentation fault happens: class Bar { private: std::vector<std::shared_ptr<Foo>> fooVector; } void Bar::addToFoo() { std::shared_ptr<Foo> foo (new Foo(…)); fooVector.push_back(foo); } void Bar::otherMethod() { // this method gets called sometime after addToFoo gets called … fooVector[anIndex]->baz(); // segfaults … } But, if push_back a shared pointer and not a variable, it works. // this works: fooVector.push_back(std::shared_ptr<Foo>(new Foo(…))); // this segfaults: std::shared_ptr<Foo> foo (new Foo(…)); fooVector.push_back(foo); I believe it happens because the foo variable gets deleted when the addToFoo function exits (correct me if I’m wrong). How do you push_back a shared_ptr variable to a vector of shared_ptrs in C++? Why Use A Variable Though pushing shared_ptrs to vectors directly without variables works, I prefer to use variables in order to do this: std::shared_ptr<Rider> rider; switch (iProcessorModesParam) { case PEAKS_MODE: rider = std::shared_ptr<Rider>(new PeaksRider(…)); break; case RMS_MODE: rider = std::shared_ptr<Rider>(new RMSrider(…)); break; } volumeRiders.push_back(rider); PeaksRider and RMSrider are subclasses of Rider. I want to store all subtypes of Rider in the same vector of Riders. I learned that adding subtypes of Rider to a vector of Riders doesn’t work and pointers are needed in order to achieve this kind of polymorphism: std::vector<Rider> // doesn’t work with subtypes std::vector<*Rider> std::vector<std::shared_ptr<Rider>> Having the std::shared_ptr<Rider> rider; variable avoids repeating the .push_back(…) code for each type of Rider.
Instead of assigning shared pointer, user reset method. rider.reset(new PeaksRider(…)); other that this, your code snippets seems to okay to me. segfault may have caused because of the index variable ( which may be out of range). i suggest you to use .at(index) for accessing pointer from vector and wrap that part of code in a try..catch block and see what is the real error. And regarding... I believe it happens because the foo variable gets deleted when the addToFoo function exits (correct me if I’m wrong). This is not true, share_ptrs use a local counter for #of references. as soon as you pushed the pointer to vector the counter gets incremented to 2 and event after control exits the function the counter is decremented to 1. so, your object is not destroyed yet.
69,892,070
69,892,689
Templated class operator overload specialization with templated argument
I have a templated class where I'm overloading the addition and output operators and I have a particular specialization that is also templated. I haven't found any examples of how to do this and I end up with a linking error, so I'm left wondering if it's even possible. // Point.hpp namespace crypto { // Forward declarations for template specialization template<class T> class FieldElement; template<class T> class Point; template<class T> std::ostream& operator<<(std::ostream& out, const Point<T>& point); template<class T> std::ostream& operator<<(std::ostream& out, const Point<FieldElement<T>>& point); template<class T> Point<T> operator+(const Point<T>& lhs, const Point<T>& rhs); template<class T> Point<FieldElement<T>> operator+(const Point<FieldElement<T>>& lhs, const Point<FieldElement<T>>& rhs); template<class T> class Point { public: Point(std::optional<T> x, std::optional<T> y, T a, T b); ~Point() = default; template<class U> friend Point operator+(const Point& lhs, const Point& rhs); template<class U> friend std::ostream& operator<<(std::ostream& os, const Point<U>& element); std::optional<T> X; std::optional<T> Y; T A; T B; }; template<class T> Point<T> operator+(const Point<T>& lhs, const Point<T>& rhs) { ... } template<class T> std::ostream& operator<<(std::ostream& os, const Point<T>& point) { // Write Point to stream if (!point.X) os << "Point(infinity)"; else os << "Point(" << point.X.value() << "," << point.Y.value() << ")_" << point.A << "_" << point.B; return os; } } And the specializations: // Point.cpp namespace crypto { template<class T> Point<FieldElement<T>> operator+(const Point<FieldElement<T>>& lhs, const Point<FieldElement<T>>& rhs) { ... } template<class T> std::ostream& operator<<(std::ostream& os, const Point<FieldElement<T>>& point) { if (!point.X) os << "Point(infinity)"; else { os << "Point(" << point.X.value().Number << "," << point.Y.value().Number << ")_" << point.A.Number << "_" << point.B.Number << " FieldElement(" << point.X.value().Prime << ")"; } return os; } } The calling code: // Test.cpp TEST(IntegrationTests, PointAdditionTests) { auto prime = 223; auto a = FieldElement(0, prime); auto b = FieldElement(7, prime); auto x1 = FieldElement(192, prime); auto y1 = FieldElement(105, prime); auto x2 = FieldElement(17, prime); auto y2 = FieldElement(56, prime); auto p1 = Point<FieldElement<int>>(x1, y1, a, b); auto p2 = Point<FieldElement<int>>(x2, y2, a, b); std::cout << p1 + p2 << std::endl; } And finally my linking error: clang++ -o buil d/bitcoin/crypto/CryptoLibTests -pthread build/bitcoin/crypto/tests/CryptoIntegrationTests.o build/bitcoin/crypto/tests/FieldElementTests.o build/bitcoin/crypto/tests/PointTests.o -Lbuild/lib -lpthread -lBtcCrypto -lgtest -lgtest_main Undefined symbols for architecture x86_64: "std::__1::basic_ostream<char, std::__1::char_traits<char> >& crypto::operator<<<int>(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, crypto::Point<crypto::FieldElement<int> > const&)", referenced from: IntegrationTests_PointAdditionTests_Test::TestBody() in CryptoIntegrationTests.o "crypto::Point<crypto::FieldElement<int> > crypto::operator+<int>(crypto::Point<crypto::FieldElement<int> > const&, crypto::Point<crypto::FieldElement<int> > const&)", referenced from: IntegrationTests_PointAdditionTests_Test::TestBody() in CryptoIntegrationTests.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) scons: *** [build/bitcoin/crypto/CryptoLibTests] Error 1 scons: building terminated because of errors.
Thanks to @paddy, the answer was to move the specialization into the header file. The above implementation works then
69,892,443
69,892,983
Error "stack smashing detected" while prepending line numbers in a string
I'm taking a string as input for the function, and I'm trying to prepend line numbers to every new line in the string. I'm also returning a string but it keeps giving me this error: stack smashing detected. Here's the code: string prepend(string code) { string arr; int i = 0; int j = 0; int count = 100; while (code[i] != '\0') { if (j == 0) { arr[j] = count; arr[j + 3] = ' '; j = j + 4; } if (code[i] == '\n') { arr[j + 1] = count; arr[j + 3] = ' '; j = j + 4; } arr[j] = code[i]; i++; j++; count++; } return arr; }
There are several errors in your code, you should convert int to string using to_string() you should iterate string using its size() ... #include <iostream> #include <string> using namespace std; string prepend(string code) { string arr; int count = 1; arr += to_string(count++) + " "; for (size_t i = 0; i < code.size(); ++i) { arr += code[i]; if (code[i] == '\n') { arr += to_string(count++) + " "; } } return arr; } int main(int argc, char **argv) { string code = "a\nbc\nd ef g\n\n"; cout << prepend(code); return 0; }
69,892,559
69,893,045
Saving a struct array to an external file in c++
I have an assignment where I need to: save the list that the user inputs to an external file. load the info from the file previously saved. I managed to write in the code for the 1st task, but since I have errors, I couldn't continue to the 2nd task. Please take a look and let me know what your thoughts are.
First Error: When you create an array, the name of the array is a pointer to the beginning of where the array is in memory. In line 42, you cannot compare an int with a pointer like that. Instead, I assume you want to do this: for (int i = 0; i < size; ++i) { Second Error: In line 43, you are trying to input an std::ofstream object into a function. In order to do this, std::ofstream must be copy-able. ofstream has a deleted copy constructor, meaning that it cannot be copied and thus cannot be passed as an input to a function. Instead, you could simply create the ofstream object and open the file within your pet::save function. Also, make sure you close the ofstream. As an example: void pet::save() { ofstream file; out.open("animal.txt"); if (!out.is_open()) cout << "Unable of open file." << endl; file << pet_info << endl; file.close(); } You could also use a pointer to the ofstream as an input to your save function, since pointers can be copied (then use out->operator<<(pet_info) to input to the file). This would make it run faster, but this situation does not seem to prompt such optimization. The function prototype would look like void pet::save(ofstream* file); and you would pass &out as the input to the function. Third Error: You are trying to use the array called animal within your pet class. Since animal is an array of pets that is created outside of your pet class, the pet class does not have access to it (so animal was not declared in the scope of pet). I am guessing your pet class stores a string which contains a pet's information (which I call pet_info). Given that is true, you can call the above save function that I wrote for all of your pets in the animal array to save them to a file. Fourth Error: On line 109 of pet.cpp, it appears you are missing a semicolon. That could be why the bracket error is there, or you are just missing a bracket.
69,892,695
69,892,917
preventing data races in shared hash table
I'm sorry if this is a duplicate, but as much as I search I only find solutions that don't apply: so I have a hash table, and I want multiple threads to be simultaneously reading and writing to the table. But how do I prevent data races when: threads writing to the same hash as another threads writing to a hash being read edit: if possible, because this hash needs to be extremely fast as it's accessed extremely frequently, is there a way to lock two racing threads only if they are accessing the same index of the hash table?
I have answered variations of this question before. Please read my previous answer regarding this topic. Many people have tried to implement thread safe collection classes (lists, hash tables, maps, sets, queues, etc... ) and failed. Or worse, failed, didn't know it, but shipped it anyway. A naive way to build a thread-safe hash table is to start with an existing hash table implementation and add a mutex to all public methods. You could imagine a hypothetical implementation is this: // **THIS IS BAD** template<typename K, typename V> class ThreadSafeMap { private: std::map<K,V> _map; std::mutex _mutex; public: void insert(const K& k, const V& v) { std::lock_guard lck(_mutex); _map[k] = v; } const V& at(const K& key) { std::lock_guard lck(_mutex); return _map.at(k); } // other methods not shown - but are essentially a repeat of locking a mutex // before accessing the underlying data structure }; In the the above example, std::lock_guard locks mutex when the lck variable is instantiated, and lock_guard's destructor will release the mutex when the lck variable goes out of scope And to a certain extent, it is thread safe. But then you start to use the above data structure in a complex ways, it breaks down. Transactions on hash tables are often multi-step operations. For example, an entire application transaction on the table might be to lookup a record and upon successfully returning it, change some member on what the record points to. So imagine we had used the above class across different threads like the following: ThreadSafeMap g_map<std::string, Item>; // thread 1 Item& item = g_map.at(key); item.value++; // thread 2 Item& item = g_map.at(key); item.value--; // thread 3 g_map.erase(key); g_map[key] = newItem; It's easy to think the above operations are thread safe because the hash table itself is thread safe. But they are not. Thread 1 and thread 2 are both trying to access the same item outside of the lock. Thread 3 is even trying to replace that record that might be referenced by the other two threads. There's a lot of undefined behavior here. The solution? Stick with a single threaded hash table implementation and use the mutex at the application/transaction level. Better: std::unordered_map<std::string, Item> g_map; std::mutex g_mutex; // thread 1 { std::lock_guard lck(g_mutex); Item& item = g_map.at(key); item.value++; } // thread 2 { std::lock_guard lck(g_mutex); Item& item = g_map.at(key); item.value--; } // thread 3 { std::lock_guard lck(g_mutex); g_map.erase(key); g_map[key] = newItem; } Bottom line. Don't just stick mutexes and locks on your low-level data structures and proclaim it to be thread safe. Use mutexes and locks at the level the caller expects to do its set of operations on the hash table itself.
69,893,984
69,894,082
Are static constinit member variables identical to non-type template parameters?
I have a class template for an N-dimensional array: template<typename T, std::size_t... Shape> class ndarray { ... }; One consequence of this template design is that there is an additional 'implicit' template parameter if you will: std::size_t Size, the product of all arguments in Shape. I have been using a C++17 fold expression ((1 * ... * Shape)) where I would typically use Size if it weren't dependent on Shape, but I'm wondering if adding the following 'alias' would result in any subtle differences in the compiled assembly: template<typename T, std::size_t... Shape> class ndarray { static constinit std::size_t Size = (1 * ... * Shape); ... }; Interestingly, the ISO C++20 standard doesn't state whether or not constinit implies inline as it does for constexpr and consteval. I think the semantics of constinit (especially in relation to constexpr variables) only really makes sense if the variable were also inline, but its omission from the standard makes me wary of this conclusion.
constinit has exactly and only one semantic: the expression used to initialize the variable must be a constant expression. That's it. That's all it does: it causes a compile error if the initializing expression isn't a valid constant expression. In every other way, such a variable is identical to not having constinit there. Indeed, the early versions of the proposal had constinit as an attribute rather than a keyword, since it didn't really do anything. It only gave a compile error for invalid initialization of the variable. For this case, there is no reason not to make the variable constexpr. You clearly don't intend to change the variable, so there's no point in making the variable modifiable.
69,894,706
69,894,795
template specialization define in c++
I declared a template specialization template <> class Component<NullType, NullType, NullType, NullType>, and defined it. My question is when I reduce the NullType in Component, p->Initialize() will always success and is called. What is this feature? Another question is why I cannot define both bool Component<NullType, NullType, NullType>::Initialize() and bool Component<NullType, NullType, NullType, NullType>::Initialize() at the same time? #include <iostream> using namespace std; class NullType {}; template <typename M0 = NullType, typename M1 = NullType, typename M2 = NullType, typename M3 = NullType> class Component { public: bool Initialize(); }; template <> class Component<NullType, NullType, NullType, NullType> { public: bool Initialize(); }; bool Component<NullType, NullType, NullType>::Initialize() { cout<<"Hello World3"; return true; } // bool Component<NullType, NullType, NullType, NullType>::Initialize() { // cout<<"Hello World4"; // return true; // } int main() { auto p = new Component<>(); p->Initialize(); return 0; }
My question is when I reduce the NullType in Component Then the default argument specified in primary template, i.e. NullType will be used. As the effect, bool Component<NullType, NullType, NullType>::Initialize() { is just same as: bool Component<NullType, NullType, NullType, NullType>::Initialize() { Another question is why I cannot define both bool Component<NullType, NullType, NullType>::Initialize() and bool Component<NullType, NullType, NullType, NullType>::Initialize() at the same time? As explained above, they're considered as the same and you'll get a redefinition error.
69,895,444
69,908,323
VS2019 debug chromium black screen
This is my compile option:gn gen --ide=vs --filters=//chrome out\x86_debug --args="is_component_build = true is_debug = true enable_nacl = false target_cpu = "x86"" Then finished compile, run chromium its black screen. Can somebody tell me what's going on? Thanks
Add this option --disable-gpu its running good
69,895,732
69,896,184
Is the AST, abstract syntax tree, defined by the language or by the frontend?
In the last few weeks I have been experimenting with ASTs and Clang, in particular clang-tidy. Clang offers some classes and way to interact with the ASTs, but what I don't understand is if the clang::VarDecl I am using so often is something named and created by the creators of Clang, or by the creators of the language. Who decided that was to be called VarDecl? I mean, is the AST (and all its elements) something that came from the mind of the inventor of the language and the various frontends just creates classes named after a document written by him/her or every frontend potentially creates its AST of a given source code and so Clang's and GCC's are different?
Is the AST, abstract syntax tree, defined by the language Not fully. Each definition in the C++ language standard comes with a short syntax notation and there is a informative annex with grammar summary. But the annex notes https://eel.is/c++draft/gram : This summary of C++ grammar is intended to be an aid to comprehension. It is not an exact statement of the language. In particular, the grammar described here accepts a superset of valid C++ constructs. [...] There is no VarDecl in that grammar from standard, variable declaration just one interpretation of simple-declaration. or by the frontend? Internals of the compiler, if it has a frontend, or it hasn't, it has 3 or 1000 stages, are part of the compiler implementation. From the point of the language, the compiler can be implemented in any way it wants, as long as it translates valid programs correctly. Let's say generally, language specifies what should happen when, not how. So to answer the question, AST (if used at all in any form) is defined by the compiler. Who decided that was to be called VarDecl? I most probably suspect Chris Lattner at https://github.com/llvm/llvm-project/commit/a11999d83a8ed1a2661feb858f0af786f2b829ad . that came from the mind of the inventor of the language and the various frontends just creates classes named after a document written by him/her or every frontend potentially creates its AST of a given source code and so Clang's and GCC's are different? Surely they are influenced by what is in the standard, but every compiler has its own internals. Well, in short, Clang VarDecl and GCC VAR_DECL are different, and they are also different conceptually - let's say GCC uses switch(...) case VAR_DECL: and Clang uses classes clang::VarDecl.
69,895,839
69,896,122
Problem with assigning values to complex variables using real() and imag()
I want to assign a value (here 0.0f) to a complex variable which I defined first using std::complex<float>. The real and imaginary part of the variable should be then assigned using real(...)=0.0f and imag(...)=0.0f. But by compiling I get the error "lvalue required as left operand of assignment". I tried g++ 7.5 and also 6.5 and I got this error from both. temp = new float[ nfft ]; tempComplex = new std::complex< float >[ nf ]; if ( processing->getComponentNSToProc() ) { for ( int i = 0; i < sampNum; i++ ) { temp[ i ] = srcData[ iSrc ].rcvData[ iRcv ].dataNS[ i ]; qDebug() << "before: temp[" << i << "] =" << temp[ i ] << "; ....dataNS[" << i << "] =" << srcData[ iSrc ].rcvData[ iRcv ].dataNS[ i ] << ";"; } for ( int i = sampNum; i < nfft; i++ ) { temp[ i ] = 0.0f; qDebug() << "before: temp[" << i << "] =" << temp[ i ] << ";"; } for ( int i = 0; i < nf; i++ ) { real( tempComplex[ i ] ) = 0.0f; imag( tempComplex[ i ] ) = 0.0f;
For using a non-static member function of a class we need to use(call) it through an object of that class. So you can change your code to look like: int main() { std::complex<float> *tempComplex = new std::complex< float >[ 3]; for ( int i = 0; i < 3; i++ ) { tempComplex[i].real(0.0f); tempComplex[i].imag(0.0f); std::cout<<tempComplex[i]<<std::endl; } } The above code now works because tempComplex[i] is an object and we access the non-static member function named real and imag of the class std::complext<float>through this(tempComplex[i]) object. Also after everything(at appropriate point) don't forget to use delete.
69,896,163
69,896,315
Why do gcc/clang complain about the base class having a protected destructor, but not about the derived class?
The following code compiles with Visual Studio 2019, but not with gcc and clang. Defining the variable b causes an error with the latter two compilers. #include <iostream> class base { public: constexpr base(int i) : m_i(i) {} constexpr int i() const { return m_i; } protected: ~base() = default; // Forbid polymorphic deletion private: const int m_i; }; class derived final : public base { public: constexpr derived() : base(42) {} }; // Defining b compiles with Visual Studio 2019, // but does not with gcc and clang. // gcc 11.2: error: 'base::~base()' is protected within this context // clang 13.0: error: variable of type 'const base' has protected destructor constexpr base b(41); // Defining d compiles with all 3 compilers. constexpr derived d; int main() { std::cout << b.i() << std::endl; std::cout << d.i() << std::endl; } Which of the compilers are right? Microsoft, which compiles the program, or gcc and clang, which do not? And if gcc and clang are right, why does the error show up for b, but not for d? Update: FWIW, if I change base as below, Visual Studio 2019 does not compile the program either: class base { public: constexpr base(int i) : m_i(i) {} constexpr int i() const { return m_i; } protected: //~base() = default; // Forbid polymorphic deletion // This does not compile with Visual Studio 2019 either. ~base() {} private: const int m_i; }; But as I understand, there shouldn't be a difference between the defaulted and the manually implemented destructor, so yes, a bug in the MS compiler it is then, I guess.
A destructor is a member-function, so it cannot be called in context where you would not be able to call other member functions. The context of the call is the context of the construction of the object (see below), so in your case you cannot call ~base() outside of base (or a class derived from base), which is why you get the error with gcc and clang (which are correct). [class.dtor#15] [...] In each case, the context of the invocation is the context of the construction of the object. [...] The error shows up for b and not for d because the implicitly declared destructor of derived is public: [class.dtor#2] If a class has no user-declared prospective destructor, a prospective destructor is implicitly declared as defaulted ([dcl.fct.def]). An implicitly-declared prospective destructor is an inline public member of its class. Making the destructor of base protected or private does not make the destructor of child classes protected or private by default, you simply get the implicitly defined destructor, which is public.
69,896,273
69,899,400
inherit from a POD struct
I am trying to find the best design for several classes that store data. For all I know I could do something with inheritance: struct Data { int a; int b; int c; }; struct DerivedData : public Data { int d; }; struct AnotherDerivedData : public Data { int e; }; Or with composition: struct ComposedData { Data data; int d; }; struct AnotherComposedData { Data data; int e; }; I am leaning towards inheritance because there is a relationship between Data and DerivedData. But I was wondering if it was good design since there are absolutely no functions to be inherited ? Moreover, Data should not be used on its own, so I was wondering if I could make it abstract and if it was worth it ? I've read that to do that, you should make a pure virtual destructor or preferably a protected constructor: struct Data { int a; int b; int c; protected: Data() = default; }; But what I don't like here is that it introduces a bit of complexity in an otherwise simple struct. It is not even a POD (if I understood what PODs are correctly). Any advice on what would be the best implementation ? Are there any other ways to do it ? Edit: I realize I was not clear enough about what is mainly bothering me: There is a "is-a" relationship between DerivedData and Data. But for some reason, I am feeling like inheritance is a bit "excessive" because there are no functions to be overriden (and even no function at all). But maybe this is a misconception on my part and that inheritance is totally appropriate here ?
API AFAIU Data is supposed to be "private" for clients. However, the approach with composition makes them know about it - they type ComposedData{}.data.a instead of ComposedData{}.a for the inheritance case. Safety and performance Data should not be used on its own, so I was wondering if I could make it abstract and if it was worth it ? I've read that to do that, you should make a pure virtual destructor or preferably a protected constructor Virtual destructors dispatch through a virtual table, in the described case it gives you nothing but overhead. To disallow using raw Data, instead just hide its destructor from non-derivers: class Data { protected: ~Data() = default; public: int a, b, c; }; struct ComposedData: public Data { int d; }; // has access to the protected ~Data() int main() { Data raw; // doesn't compile: raw.~Data() is inaccessible ComposedData composed; // OK (~ComposedData() is public) } Moreover, protected destructors, unlike protected constructors, prevent mistakes like this one: struct NonTrivialData: public Data { std::string non_trivial_dtor; }; std::unique_ptr<Data> type_erased{new NonTrivialData{1, 2, 3, "i won't be deallocated"}}; // ...because ~Data() knows nothing about NonTrivialData::non_trivial_dtor (I didn't use the usual make_unique because it cannot perform aggregate initialization.) A protected destructor disallows calling ~Data() from the outside => the code doesn't compile. A virtual destructor dispatches ~Data() as ~NonTrivialData() at runtime => the destruction is done properly. However, as far as using raw Data isn't preferable, preventing the mistake at compile-time and introducing no virtual tables provide better semantics and performance. Feeling right about it for some reason, I am feeling like inheritance is a bit "excessive" because there are no functions to be overriden That's OK. E.g. in some meta code it could even be reasonable to inherit from a class like template<typename ValueType> struct AliasHelper { using value_type = ValueType; using reference = ValueType&; using pointer = ValueType*; using const_reference = ValueType const&; using const_pointer = ValueType const*; }; class Foo: public AliasHelper<int> {}; class Bar: public AliasHelper<short> {}; class Baz: public AliasHelper<long> {}; which doesn't even have fields! However, it greatly reduces boilerplate.
69,896,357
69,896,643
Notifying wxSizer of dynamic layout changes
I have the following hierarchy for layout: wxMDIChildFrame -> wxNotebook -> wxScrolledWindow -> wxBoxSizer -> wxStyledTextCtrl GOAL: The wxStyledTextCtrl (CScriptWnd) resizes itself when user adds or deletes a line or presses Shift+Enter to add another CScriptWnd to the wxScrolledWindow. The following code is when a line is added: void CScriptWnd::OnNewLineAdded(wxStyledTextEvent& event) { long col, line; PositionToXY(GetInsertionPoint(), &col, &line); auto ClientSize = GetClientSize(); int Height = ClientSize.GetHeight(); Height += TextHeight(line); SetClientSize(ClientSize.GetWidth(), Height); SetMinSize(wxSize(ClientSize.GetWidth(), Height)); Refresh(); //m_ParentWindow->FitInside(); //CScriptWnd gets smaller rather than larger //m_ParentWindow->Layout(); //CScriptWnd gets smaller rather than larger //m_ParentWindow->GetGrandParent()->Layout(); //No effect event.Skip(); } Most work well such as the CScriptWnd resizes itself, the new script window added to wxScrolledWindow etc... The problem is that the update to user interface only properly happens when the wxMDIChildFrame is resized using the mouse. For example, if there are two CScriptWnd and the top one resizes itself, it overlaps with the bottom one until the wxMDIChildFrame is resized using the mouse. Similar happens for the visibility of scrollbars such that when CScriptWnd client size gets larger the scrollbars only become visible when top-level window resized using the mouse. Not sure what I am missing.
You probably need SetMinSize(GetSize()); GetParent()->Layout();
69,896,487
69,897,066
How to declare a pointer to a nested C++ class in C
I have a nested class in C++ that I want C code to be able to use. Because it is nested I cannot forward declare it to C, so instead we have code like this in a shared header file: #ifdef __cplusplus class Mgr { public: class Obj { public: int x; }; }; typedef Mgr::Obj * PObj; #else typedef void* PObj; #endif This results in C and C++ each seeing a different definitions of PObj which I fear violates the one definition rule. However it is "just" a pointer, so I'm not sure if this can go wrong or not. C does nothing with the pointer besides pass it along to C++ functions which are wrappers for methods. For instance we'll have this in the combined header: #ifdef __cplusplus extern "C" { #endif int obj_GetX(PObj pObj); #ifdef __cplusplus } #endif /* __cplusplus */ With this as the implementation in the C++ file: int obj_GetX(PObj pObj) { return pObj->x; } So: Is this really a problem? If so, what is the best way to share this pointer between C and C++
It's not a problem per-se, but you might violate the strict aliasing rule if and when you cast that void * back to Mgr::Obj * in your C++ code. There's no good solution to this - it is (to me) a glaring omission in the standard. The best you can do is to compile any code which does such casts with the -fno-strict-aliasing flag. I do this extensively and have never had a problem performing casts in this manner.
69,896,557
69,896,644
why string prints junk value,if we give it size?
#include <iostream> using namespace std; int main() { string a("Hello World",20); cout<<a<<endl; return 0; } I get output as "Hello WorldP". Why? Usually we initialise string only with a data.But here i gave size.But it takes junkees. So do i prefer not giving size?
Generally this is called garbage in, garbage out. From cppreference: Constructs the string with the first count characters of character string pointed to by s. s can contain null characters. The length of the string is count. The behavior is undefined if [s, s + count) is not a valid range. The behavior of your program is undefined because "Hello World" is a const char[12] and trying to access characters up to index 20 via the const char* (resulting from the array decaying to pointer to its first element) is out of bounds. The actual use case for that constructor is to create a std::string from a substring of some C-string, for example: std::string s("Hello World",5); // s == "Hello" Or to create a std::string from a C-string that contains \0 in the middle, for example: std::string s("\0 Hello",5); // s.size() == 5 (not 0)
69,897,017
69,897,081
Segmentation fault while accessing vector elements
I am learning how to make a reference variable in C++ and I am having some trouble when using int &res = f[k] to make res a variable that refers to a given component of vector f. In this code F(k) should return the fibonacci number of integer input k computed by memorizing the previous calls F(0), F(1),... F(k-2) and F(k-1) in vector f but I get a Segmentation Fault which makes me think I fail to refer res as a component of vector f. Here's my code: #include <iostream> #include <vector> using namespace std; const int UNDEF = -1; vector<int> f; int F(int k) { int &res = f[k]; // I get "res: 0x0000000000000004 and &res: ??" when debugging if (res != UNDEF) return res; // EXC_BAD_ACCESS (code=1, address=0x4) if (k <= 1) return 1; return res = F(k-1) + F(k-2); } int main() { int k; cin >> k; vector<int> f(k+1, UNDEF); cout << F(k) << endl; } I could really use some help over here! Thanks a lot:) Àlex
The global vector variable f has no elements. And when you write: int &res = f[k]; You're trying to access it's kth element which doesn't exist which is why you get segmentation fault at that point. Note in your program you have two vector variable with the same name f. One of them is a local variable while the other one is a global variable. When you write int &res = f[k]; The vector f that is chosen is the global variable and since the global vector f has size 0(empty vector), when you try to access its kth element it gives you segmentation fault(undefined behavior) as can be seen here.
69,897,839
69,907,015
Simulate Multithreading with semaphores in a single thread
I want to simulate the firmware (C++) of an embedded device on a Windows machine (C++). The firmware runs on a microcontroller (nRF5340) and runs Zephyr as an operating systes. Within the real firmware there are multiple tasks. The challenge is now: I want to be able to create multiple instances of one virtual device, but each device should only run in one single thread. Semaphores are used for multi-threading (in the firmware), which are blocked or released. Is there a way I can use semaphores in a single thread and implement a kind of context switch? So that, for example, a function is called that runs through to a semaphore. When the semaphore is reached, a new function can be called which releases the previous semaphore so that the original function can continue (but all in one single thread).
This can be done with coroutines. A coroutine is like a function, but at some point in the body the programmer calls yield. This saves the state of the coroutine. It can be resumed later at the point where it yielded. Coroutines were added to C++20. However, they didn't yet add specification for a task-management library. It would be a significant amount of work to implement yourself. You can find 3rd party ones. Boost also has 3 coroutine libraries that predate C++20 (1 old, 1 current, and 1 specifically for Asio). Using a 3rd party task-management library is probably the superior approach, but you will have to use C++20 and learn a new library that might go obsolete pretty quickly. Alternatively you could make a work-around if you allowed each virtual device to spawn an actual thread for each of its simulated threads, then programmed some kind of synchronization so only 1 thread per virtual device runs at any given time. You're essentially taking advantage of the fact that a real thread has context switching built in. I would use this approach, as it avoids a lot of development on things tangential to your project, and I already know how to use threading tools. Lastly, you could create a "stack" for each simulated thread and do the context switch yourself. You'd lose portability. Basically you're writing your own coroutine library, but it's tailored to your use case so it would be easier to use. However, the dev time would probably balance out with just learning how to use an existing library. Going back to the middle approach (a real thread for each simulated thread)... your yielding function could look something like: Each simulated thread has its own semaphore (so you can specify which to call): void switch_to(T& other) { other.up() me.down(); } Or all simulated threads on a virtual device share a semaphore: void switch() { sem.up(); sem.down(); } (This approach only works if the semaphore implements fairness.) Both ways, you init the semaphore with 0 passes and have each thread call down() on the semaphore as its first action (this inits each thread in a blocking state). C++ doesn't have a standard semaphore, but you can implement one with condition variables.
69,898,742
69,899,166
C++, overloding functions, templates
I want to ask is it possible to write overloaded function for arithmetic's type which returns double and for containers (array, vector, valarray, etc...) which returns valarray. Simple example template<typename T> double foo(T x) { return x; } template<typename T> std::valarray<double> foo(T const &arr) { std::valarray<double> valarr(1,1); return valarr; } In result I get expected message: call to 'foo' is ambiguous. Is there any possibility to write such a functions? I would really appreciate all comments.
You can use std::enable_if to do what you want as follows: #include <iostream> #include <string> #include <valarray> //overload for arthemtic types template<typename T> std::enable_if_t<std::is_arithmetic_v<T>, double> foo(T x) { std::cout<<"arithmetic version"<<std::endl; return x; } //overload for array template<typename T, std::size_t N> std::valarray<double> foo(T const (&arr)[N]) { std::valarray<double> valarr(2,5); std::cout<<"array version"<<std::endl; return valarr; } //overload for non-arthemtic types template<typename T> std::enable_if_t<!std::is_arithmetic_v<T>, T> foo(T x) //note the "!" in this version { std::cout<<"non-arithmetic version"<<std::endl; return x; } int main() { int arr[3] = {1,2,3}; foo(arr);//uses array version foo(5); //uses arithmetic version int p= 0, *c = &p; foo("string");//uses array version foo(p);//uses arithmetic version foo(c); //uses non-arithmetic version } The output of the above program can be seen here.
69,898,756
69,898,868
Is there any special C++ function to get XOR of all element of array?
I have an array like this [1, 0, 1, 1, 0, 0, ...]. How can i get result of this expression: 1 XOR 0 XOR 1 XOR 1 XOR... without loop?
In C++14: std::accumulate(arr.begin(), arr.end(), 0, std::bit_xor<void>())
69,898,876
69,911,771
Keep Android Qt apps running in background
I've created a doorbell system (server, client) for my home which works via MQTT publish/subscriptions to know when someone rang the doorbell. It works quite well, however in my client, the MQTT connection keeps closing, even after setting _client->setAutoKeepAlive(true). Moreover, I want to know if anyone can give me a hint on how to set the app to keep running in the background. What I found out so far is that I can set the persistence attribute in my AndroidManifest.xml, but is that all I can do to have my application run in background all the time, even if it gets closed accidentally? My questions: How can I prevent QMqttClient from automatically disconnecting - or: how can I automatically reconnect if the connection gets lost? How do I prevent Qt Android apps from being killed?
You can use the service to avoid program destruction as much as possible. A Service is an application component that can perform long-running operations in the background. It does not provide a user interface. Once started, a service might continue running for some time, even after the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background. The Android system stops a service only when memory is low and it must recover system resources for the activity that has user focus. If the service is bound to an activity that has user focus, it's less likely to be killed; if the service is declared to run in the foreground, it's rarely killed. If the service is started and is long-running, the system lowers its position in the list of background tasks over time, and the service becomes highly susceptible to killing—if your service is started, you must design it to gracefully handle restarts by the system. https://developer.android.com/guide/components/services
69,898,955
70,213,704
Processing standalone source files in a complex CMake structure with clang LibTooling
I wrote my own clang tool following https://clang.llvm.org/docs/LibASTMatchersTutorial.html The purpose of the tool is to generate diagrams based on specific source files. Until now as a prototype I worked with some basic cpp code which didn't have any dependencies. However the target project is large and uses CMake, leading to include errors when I run the tool (as expected). I found this question with a similar problem: clang tool : include path, however due to the scale of the project I think supplying the include paths one by one like that is not really viable. Is it possible to somehow reuse the CMake structure to feed in include paths, or recursively look for headers inside the root folder?
The correct way to achieve this is indeed by creating the compile_commands.json file by setting the cmake option CMAKE_EXPORT_COMPILE_COMMANDS=ON. To parse it to your clang tool, you need to use the command line parameter -p <BUILD_PATH> where <BUILD_PATH> is the path to the compile_commands.json file. And as a hint: do not provide a double dash -- as a command line option to your tool since then the tool will not use the compilation database in the compile_commands.json but is instead expecting extra arguments for the compiler after the --.
69,899,357
69,919,488
How to find the Creation time of a .wav file using C++
I am currently working on reading a RIff fmt .wav file using c++. How could I find the date and time the file was created. The only time included in the header is the TimeStamp which represents Seconds since epoch. The following are the parsed RIff headers I am using : typedef struct RIFF_CHUNCK_DISCRIPTOR { char RIFF[4]; // RIFF Header Magic header int32_t ChunkSize; // RIFF Chunk Size int32_t WAVE[4]; // WAVE Header }; typedef struct CRIF_CHUNCK { char Crif[4]; int32_t Length; int32_t CrifCheckSum; }; typedef struct FMT_CHUNCK_DISCRIPTOR { char fmt[4]; // FMT header int32_t Subchunk1Size; // Size of the fmt chunk int16_t EncodingTag; int16_t NumOfChan; // Number of channels int32_t SamplesPerSec; // Sampling Frequency in Hz int32_t bytesPerSec; // bytes per second int16_t blockAlign; // 2=16-bit mono, 4=16-bit stereo int16_t bitsPerSample; // Number of bits per sample int16_t AudioFormat; // PCM = 0 , ADPCM = 2 int16_t SmplesPerChan; };typedef struct FMT_CHUNCK_DISCRIPTOR_PCM { char fmt[4]; // FMT header int32_t Subchunk1Size; // Size of the fmt chunk int16_t EncodingTag; int16_t NumOfChan; // Number of channels int32_t SamplesPerSec; // Sampling Frequency in Hz int32_t bytesPerSec; // bytes per second int16_t blockAlign; // 2=16-bit mono, 4=16-bit stereo int16_t bitsPerSample; // Number of bits per sample int16_t AudioFormat; // PCM = 0 , ADPCM = 2 }; typedef struct FACT_CHUNCK { char fact[4]; int32_t FactSize; int32_t dwSampleLength; }; typedef struct META_DATA { char meta[4]; uint32_t HeadData;// <length of the head data - 8> uint8_t Version; uint8_t Model; uint32_t Serial; uint32_t RecordingNumber; uint16_t ChunkNumber; uint32_t TimeStamp; uint32_t MetadataChecksum; }; typedef struct DATA_SUB_CHUNCK { char Subchunk2ID[4]; // "data" string int32_t Subchunk2Size; // Sampled data length }; typedef struct CDAT { char cdat[4]; // "data" string int32_t CdatCheckSum; // Sampled data length }; typedef struct FOOTER { char foot[4]; // "data" string int16_t PrevChunckNumb; // Sampled data length int16_t NextChunckNumb; int32_t FooterChunckSum; };
The Timestamp field in the WAV file metadata and the file creation date are to unrelated pieces of information. The file creation date is the date the file was created on the hard drive. You can use the Windows API GetFileTime to get the creation, last access and last write times. The Timestamp is just some information someone put inside the WAV file. It may or may not be present and may or may not be the same time/date information you will get with GetFileTime.
69,899,638
69,899,703
Program breaks before it is supposed to in C++
Not sure how I was supposed to formulate title! I'm trying to write a program that asks the user for the name of a student. Then it stores that name in a struct and asks for a course name and the grade for that course. It does this until the course name is stop. Then it asks for another student until the name given is stop. Here is my code: #include <iostream> using namespace std; struct student{ public: string name; string course; int grade; }student_t; int main() { while (student_t.name != "stop"){ cout << "Please type the name of a student: " << endl; getline(cin, student_t.name); if (student_t.name.compare("stop")){ break; } else{ if (student_t.course.compare("stop")){ break; } else { cout << "Please type a course name: " << endl; getline(cin, student_t.course); cout << "Please type the grade: " << endl; cin >> student_t.grade; } } } cout << student_t.name << " - " << student_t.course << " - " << student_t.grade << endl; return 0; } The problem is, it exits no matter what name I type. Any ideas?
It should be: if (student_t.name.compare("stop") == 0){ break; }
69,900,219
69,900,390
How to sort any vector by value?
How to sort a vector by absolute value in c++? suppose a vector {-10, 12, -20, -8, 15} output should be {-8, -10, 12, 15, -20}
My guess is that you want to sort the vector by absolute value. You can sort a vector with std::sort in any way you want by passing a lambda to it. The absolute value of an integer can be calulated using std::abs. std::sort(std::begin(vec), std::end(vec), [](const auto& lhs, const auto& rhs){ return std::abs(lhs) < std::abs(rhs); });
69,900,448
69,900,519
Enemy does not follow Player OpenGL 2D
I have a project to do where one the tasks is to make an enemy that follows the player. This is how I drew the player //Body modelMatrix = visMatrix; modelMatrix *= transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Scale(1, 1); modelMatrix *= transform2D::Rotate(playerAngle); modelMatrix *= transform2D::Translate(-50, -50); RenderMesh2D(meshes["square3"], shaders["VertexColor"], modelMatrix); //Eye1 modelMatrix = visMatrix; modelMatrix *= transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Scale(0.25f, 0.25f); modelMatrix *= transform2D::Rotate(playerAngle); modelMatrix *= transform2D::Translate(150, 200); modelMatrix *= transform2D::Rotate(0); modelMatrix *= transform2D::Translate(-50, -50); RenderMesh2D(meshes["square1"], shaders["VertexColor"], modelMatrix); //Eye2 modelMatrix = visMatrix; modelMatrix *= transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Scale(0.25f, 0.25f); modelMatrix *= transform2D::Rotate(playerAngle); modelMatrix *= transform2D::Translate(-150, 200); modelMatrix *= transform2D::Rotate(0); modelMatrix *= transform2D::Translate(-50, -50); RenderMesh2D(meshes["square1"], shaders["VertexColor"], modelMatrix); This is how I drew the enemy //Body modelMatrix = visMatrix; modelMatrix *= transform2D::Translate(translateEnemyX, translateEnemyY); modelMatrix *= transform2D::Scale(1, 1); modelMatrix *= transform2D::Rotate(enemyAngle); modelMatrix *= transform2D::Translate(-50, -50); RenderMesh2D(meshes["border"], shaders["VertexColor"], modelMatrix); //Eye1 modelMatrix = visMatrix; modelMatrix *= transform2D::Translate(translateEnemyX, translateEnemyY); modelMatrix *= transform2D::Scale(0.25f, 0.25f); modelMatrix *= transform2D::Rotate(enemyAngle); modelMatrix *= transform2D::Translate(150, 200); modelMatrix *= transform2D::Rotate(0); modelMatrix *= transform2D::Translate(-50, -50); RenderMesh2D(meshes["square2"], shaders["VertexColor"], modelMatrix); //Eye2 modelMatrix = visMatrix; modelMatrix *= transform2D::Translate(translateEnemyX, translateEnemyY); modelMatrix *= transform2D::Scale(0.25f, 0.25f); modelMatrix *= transform2D::Rotate(enemyAngle); modelMatrix *= transform2D::Translate(-150, 200); modelMatrix *= transform2D::Rotate(0); modelMatrix *= transform2D::Translate(-50, -50); RenderMesh2D(meshes["square2"], shaders["VertexColor"], modelMatrix); I made the enemy to face the player by calculating the angle like this, and this works enemyAngle = atan2(translateX - translateEnemyX, translateY - translateEnemyY); And I have tried to move the enemy towards the player like this enemySpeed = 10; translateEnemyX += enemySpeed * cos(enemyAngle); translateEnemyY += enemySpeed * sin(enemyAngle); But it does not work, the enemy just moves away from the player. The question is, how to make the enemy move towards player?
If it moves away from the player, perhaps you switched up sin and cos. My guess is, it should be this instead: translateEnemyX += enemySpeed * sin(enemyAngle); translateEnemyY += enemySpeed * cos(enemyAngle); Other than that I think the right side should also contain your delta time between frames, otherwise it's going to move faster at higher frame rate. Edit: Nevermind, that shouldn't work, your equation should contain the player's position, since that's what you want the enemy to move towards. Try taking the difference between the enemy position and the player position, something like this: translateEnemyX += (translatePlayerX - translateEnemyX) * enemySpeed * deltaTime; translateEnemyY += (translatePlayerY - translateEnemyY) * enemySpeed * deltaTime;
69,900,675
69,900,892
How to call a function in a member initialization list?
I have the following simple c++ (RAII pattern) wrapper around jpeg_decompress_struct (ijg/libjpeg-turbo): class Decompress { typedef jpeg_decompress_struct *ptr; jpeg_decompress_struct srcinfo; public: Decompress() { jpeg_create_decompress(&srcinfo); } ~Decompress() { jpeg_destroy_decompress(&srcinfo); } operator ptr() { return &srcinfo; } jpeg_decompress_struct *operator->() { return &srcinfo; } }; I am happy with this code, and I'd like to keep srcinfo as it is now (on the stack, just like upstream expect it.) Is there a way to rewrite the above constructor using a member initialization list ? I'd like to pass the check of gcc -Weffc++. Current warning is: jpeg.cxx:92:3: error: ‘acme::Decompress::srcinfo’ should be initialized in the member initialization list [-Werror=effc++] 92 | Decompress() { jpeg_create_decompress(&srcinfo); } | ^~~~~~~~~~
If (which we can probably safely assume here) jpeg_create_decompress() can operate on a jpeg_decompress_struct containing undefined values, then the code you posted is fine as is . I wouldn't personally touch it. However, the question can still be answered as aksed: Most question formulated as "How to do __blank__ in an initialization list" have the same answer: Do it in a function. jpeg_decompress_struct make_initialized_jds() { jpeg_decompress_struct result; jpeg_create_decompress(&result); return result; } class Decompress { typedef jpeg_decompress_struct *ptr; jpeg_decompress_struct srcinfo; public: Decompress() : srcinfo(make_initialized_jds()) {} ~Decompress() { jpeg_destroy_decompress(&srcinfo); } operator ptr() { return &srcinfo; } jpeg_decompress_struct *operator->() { return &srcinfo; } }; In modern compilers making use of NRVO, this won't even result in any additional overhead. Edit: From the updated question: If you just want to make the warning go away, you can explicitely zero-initialize the struct using member initialization: class Decompress { jpeg_decompress_struct srcinfo = {0}; // <---- here typedef jpeg_decompress_struct *ptr = nullptr; // <---- might as well... public: Decompress() { jpeg_create_decompress(&srcinfo); } ~Decompress() { jpeg_destroy_decompress(&srcinfo); } operator ptr() { return &srcinfo; } jpeg_decompress_struct *operator->() { return &srcinfo; } }; This will give srcinfo a defined value before invoking jpeg_create_decompress().
69,900,842
69,900,936
C++ command line interface help message wont display
I am trying to make a CLI app in C++. This is my first time coding in C++. I have this c++ code: #include <iostream> // using namespace std; static void help(std::string argv) { std::cerr << "Usage:" << argv << " [options]\n" << "Options:\n" << "-h (--help): Displays this help message.\n" << "-o (--output=[output file]): Specifies the output file.\n" << "-p (--ports=[ports]) Sets the ports to scan.\n" << std::endl; } int main(int argc, char** argv) { if (argc > 1) { std::cout << argv[1] << "\n"; if (argv[1] == "-h" || argv[1] == "--help") { help(argv[0]); return 0; } } else { std::cout << "No arguments were given" << "\n"; }; }; // g++ -o cli main.cpp It works! When I compile it, it successfully outputs No arguments were given, but when I run cli -h, I can see argv[1] is -h, but nothing is outputted. What did I do wrong?
In your string comparison, argv[1] is a C string: a null-terminated char array. You cannot compare these with == and get the result you expect. If, however, you assign it to a std::string you can compare it with "-h" and "--help" the way you want. std::string arg1 = argv[1]; if (arg1 == "-h" || arg1 == "--help") { help(argv[0]); return 0; } Alternatively you could use std::strcmp to compare C strings without creating a new std::string. In order to do this, you'll need #include <cstring>. if (std::strcmp(argv[1], "-h") == 0 || std::strcmp(argv[1], "--help") == 0) { help(argv[0]); return 0; }
69,900,996
69,901,080
How to insert values in set directly from input stream?
How to Insert input directly into set container from input stream? This is how I need while(n--) { cin>>s.emplace(); } Assume,I need to get n inputs and set container name is 's' while(n--) { int x; cin>>x; s.emplace(x); } This works fine but I need to cut this step.
Since C++20 you can use std::ranges::copy, std::counted_iterator, std::istream_iterator,std::default_sentinel and std::inserter to do it. The counted_iterator + default_sentinel makes it copy n elements from the stream. Example: #include <algorithm> // ranges::copy #include <iostream> #include <iterator> // counted_iterator, default_sentinel, istream_iterator, inserter #include <set> #include <sstream> // istringstream - only used for the example int main() { // just an example istream: std::istringstream cin("1 1 2 2 3 3 4 4 5 5"); int n = 5; std::set<int> s; std::ranges::copy( std::counted_iterator(std::istream_iterator<int>(cin), n), std::default_sentinel, std::inserter(s, s.end()) ); for(auto v : s) std::cout << v << ' '; } The output will only contain 3 elements since the first 5 elements in the stream only had 3 unique elements: 1 2 3 Prior to C++20, you could use copy_n in a similar fashion: std::copy_n(std::istream_iterator<int>(cin), n, std::inserter(s, s.begin())); Caution: If there are actually fewer than n elements in the stream, both versions will have undefined behavior. Streams are notoriously unpredictable when it comes to delivering exactly what you want and copy_n makes error checking really hard. To make it safe, you could create a counting_istream_iterator to copy at most n elements from a stream using std::copy like this: std::copy(counting_istream_iterator<foo>(cin, n), counting_istream_iterator<foo>{}, std::inserter(s, s.end())); Such an iterator could, based on std::istream_iterator, look something like this: template<class T, class CharT = char, class Traits = std::char_traits<CharT>, class Distance = std::ptrdiff_t> struct counting_istream_iterator { using difference_type = Distance; using value_type = T; using pointer = const T*; using reference = const T&; using iterator_category = std::input_iterator_tag; using char_type = CharT; using traits_type = Traits; using istream_type = std::basic_istream<CharT, Traits>; counting_istream_iterator() : // end iterator isp(nullptr), count(0) {} counting_istream_iterator(std::basic_istream<CharT, Traits>& is, size_t n) : isp(&is), count(n + 1) { ++*this; // read first value from stream } counting_istream_iterator(const counting_istream_iterator&) = default; ~counting_istream_iterator() = default; reference operator*() const { return value; } pointer operator->() const { return &value; } counting_istream_iterator& operator++() { if(count > 1 && *isp >> value) --count; else count = 0; // we read the number we should, or extraction failed return *this; } counting_istream_iterator operator++(int) { counting_istream_iterator cpy(*this); ++*this; return cpy; } bool operator==(const counting_istream_iterator& rhs) const { return count == rhs.count; } bool operator!=(const counting_istream_iterator& rhs) const { return !(*this == rhs); } private: std::basic_istream<CharT, Traits>* isp; size_t count; T value; };
69,901,130
69,905,294
Asking for conditional information in C++
Not sure how I was supposed to formulate the title. I'm writing a program that asks for a students name, and if the name is not "stop", then it asks for a course name. If the course name is not "stop", it asks for a grade, then returns to ask for another course until the course name is "stop". Then it asks for another student and does the whole thing again until the student name is "stop". Then it prints all the students with their courses and grades. Here is my code: #include <iostream> #include <vector> using namespace std; struct student{ public: string name; string course; int grade; }student_t; void input(){ cout << "Please type the name of a student: " << endl; getline(cin, student_t.name[i]); if (student_t.name.compare("stop")){ break; } else { cout << "Please type a course name: " << endl; getline(cin, student_t.course); if (student_t.course.compare("stop")) { break; } else { cout << "Please type the grade: " << endl; cin >> student_t.grade; } } } int main() { int i; vector<student> input(i); for (i = 0; i < 20; ++i){ student[i].input(); } cout << student_t.name << " - " << student_t.course << " - " << student_t.grade << endl; return 0; } It does not work at all.. I'm new to C++ so I dont really know why. Any ideas?
I can give one or two recommendations. Instead of checking if every step is wrong (i.e. equals "stop"), focus on what is right (i.e. what's the next things to read). From a mental perspective, I find it much easier to think about what has to be right for the program to progress as intended, as opposed to "What can go wrong here?" at every step. Your input() could then be (in pseudo code): if (student_t.name is not "stop") { Read_course_name(); if (student_t.course is not "stop") { Read_grades(); // Done return(StudentInfo); } } // Ending up here means "stop" was typed so deal with that // in a meaningful way ... Take a look at https://en.wikipedia.org/wiki/Separation_of_concerns and then ask yourself, -Is the input() function really an input or are there more than one concern that coud be broken out in a separate function? Cheers /N
69,901,179
69,901,647
Function accepting rvalue reference, how to use it twice if order is unspecified
Imagine a function accepting a rvalue reference that it can move from. If the function needs to use that object multiple times, the last usage can take advantage of the rvalue reference and can std::move from that. void tripple(std::string&& str) { std::vector<std::string> vector; vector.push_back(str); // invokes 'const std::string&', will copy vector.push_back(str); // invokes 'const std::string&', will copy vector.push_back(std::move(str)); // invokes 'std::string&&', will move } But what if the order of operation is indeterminately sequenced In a function call, value computations and side effects of the initialization of every parameter are indeterminately sequenced with respect to value computations and side effects of any other parameter. So for example void foo(std::string&& str) { std::unordered_map<std::string, std::string> map; map.try_emplace(str, str); // will copy key and emplace the value from copy of str // any of those three shouldn't be valid map.try_emplace(std::move(str), str); map.try_emplace(str, std::move(str)); map.try_emplace(std::move(str), std::move(str)); } Is the only option to use at least one move by explicitly making a copy and moving both as void foo(std::string&& str) { std::unordered_map<std::string, std::string> map; std::string copy = str; map.try_emplace(std::move(copy), std::move(str)); // ok, two moves } or am I missing something?
Your reasoning is absolutely correct. If you do it like you described it, you will not get issues. But every case is individual. The designers of the standard library foreseen this case and made two overloads: template< class... Args > pair<iterator, bool> try_emplace( const Key& k, Args&&... args ); // (1) template< class... Args > pair<iterator, bool> try_emplace( Key&& k, Args&&... args ); // (2) In this particular case no explicit copy is required, you can call without any issue void foo(std::string&& str) { std::unordered_map<std::string, std::string> map; map.try_emplace(str, std::move(str)); // ok, (1) is used. } Note, str is l-value, is reference to r-value, std::move(str) performs nothing except typecasting l-value to r-value reference. Notes Unlike insert or emplace, these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are move-only types, such as std::map<std::string, std::unique_ptr<foo>>. In addition, try_emplace treats the key and the arguments to the mapped_type separately, unlike emplace, which requires the arguments to construct a value_type (that is, a std::pair).