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 a... | 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... |
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 ... | 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 ... |
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 ite... | 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 sum... | 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());
// ... |
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 re... | 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_... |
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(Instructio... | 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?... | 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 answe... |
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, Segmentat... | 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))
{
... |
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 i... | 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 th... |
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]) {
... | 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;
... |
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 w... | 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 =... |
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) {
retur... | 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");
matc... |
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.... |
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 ... | 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(uDeforma... |
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];
... | 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 m... |
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;
... | 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... |
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 ... | 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 throwin... | 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:
... |
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 ... | 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 reliab... |
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 <... |
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>
#i... | 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 delimite... |
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 i... | 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;
... |
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 thi... |
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... | 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... |
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 Fau... | 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 joi... |
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};
... | 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 o... |
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 = s... | 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 ... |
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 ... | 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 exam... |
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 th... | 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... |
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);
IndexBuff... | 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 in... |
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... | 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(... |
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 outpu... | 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(ch... | 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... | 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 s... | 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>& V... |
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
... | 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 s... | 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
... |
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... | 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 ... |
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 n... | 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 ex... |
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 wo... | 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... |
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>
i... |
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);
... |
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 UC... | 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 sup... |
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... | 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 c... |
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 s... | 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 instanc... |
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 ke... |
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... |
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";
... | 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>
cla... |
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 refer... | 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 ... |
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... |
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 ... |
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... | 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 ... |
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) Function... | 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... | 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) $(CFL... |
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... | 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... |
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)... | 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 is... |
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;
}
}
retu... | 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 ... |
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 ... | 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;
... |
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 sta... | 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,... |
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_AL... | 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:... |
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_en... | 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 ... |
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 f... | 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::Mai... |
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... | 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 <QStyleO... |
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(... | 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 5... |
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){... | 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 withou... |
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 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... |
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 'z... | 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/... |
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-... | + 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'... | 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++)
{
i... |
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... | 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 ... |
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 declar... | 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;... | 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 ... |
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::o... |
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 ... | 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... |
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... | 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 t... |
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<NullTyp... |
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 que... |
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... |
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 compre... |
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 a... | 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);
... |
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; // Forbi... | 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 ... |
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 Compose... | 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 i... |
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 l... | 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 vo... | 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-alia... |
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 progr... |
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... | 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 ... |
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, ... | 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 libra... |
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... | 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
temp... |
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 ... | 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 applicat... |
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, l... | 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: d... |
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 ... | 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... |
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 ... | 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){
re... |
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);
... | 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... |
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); }
op... | 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 a... |
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"
<... | 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") {
... |
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_it... |
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 ... | 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 ... |
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); // invo... | 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<... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.