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 |
|---|---|---|---|---|
73,865,784 | 73,866,781 | Limiting the scope of a temporary variable | Without resorting to the heap, I would like a temporary variable to pass out of scope, freeing its storage on the stack. However, I can think of no neat way to achieve the desired effect in a case like this:
#include <cstdlib>
#include <iostream>
int main()
{
const int numerator {14}, denominator {3};
// ..... | In C++17, you can use a function and a structured binding declaration:
auto x_lo_x_hi = [](int numerator, int denominator) {
std::div_t quotient_and_remainder {std::div(numerator, denominator)};
return std::pair{
quotient_and_remainder.quot,
quotient_and_remainder.quot + (quotient_and_remainder.... |
73,867,157 | 73,867,339 | The AVX intrinsic _mm256_rsqrt_ps has much greater relative error than it should have according to the intrinsics guide | The Intel Intrinsics Guide says that the intrinsic _mm256_rsqrt_ps has a relative error of at most 1.5*2^-12. But, when I compare the result of _mm256_rsqrt_ps to a standard C++ calculation of the inverse of the square root (1.0 / sqrt(x)), I get a relative error much greater than 1.5*2^-12.
I used the following progra... | Your relative error is in the bound.
1.5*2^-12 = 0.000366
It's just powers of 2 not powers of 10.
Also is does not claim to have this relative error in comparison to the single precision 1/sqrt(x) but to the exact result.
|
73,868,536 | 73,868,629 | I don't understand the problem that the error want to tell me. i copied the error message | #include <iostream>;
using namespace std;
int main()
{
int total_of_seconds;
cout << "please inter the total of seconds \n";
cin >> total_of_seconds ;
int seconds_per_day = 24* 60 *60 ;
int seconds_per_hours = 60 * 60 ;
int seconds_per_minutes= 60 ;
int number_of_days = floor (total_of_seconds/seco... | You have declared your variable at
int s = total_of_seconds % seconds_per_day ;
and you're trying to re-declare it at
int s %= seconds_per_hours;
remove the int declaration
P.S. include the cmath for using floor
|
73,868,751 | 73,869,825 | Make object searchable with two different keys | Given a class with two keys:
class A {
int key1;
int key2;
byte x[]; // large array
}
If multiple objects of class A are instantiated and I want to sort them by key1, I can insert them into an std::set.
But if I want to sort these objects both by key1 and by key2, how would I do that?
I could create two se... |
Storing pointers to the objects in the set instead of the objects themselves seems like a good solution. But would it be possible to store pointers in both sets?
Sure, your sets seem to share ownership of that objects, so:
class Person {
std::string name;
std::string address;
// other fields
};
using Per... |
73,870,301 | 73,948,872 | Why does ASIO not apply serial port settings when sending data (only receiving)? | I have a program that uses the modbus protocol to send chunks of data between a 64-bit Raspberry Pi 4 (running Raspberry Pi OS 64) and a receiving computer. My intended setup for the serial port is baud rate of 57600, 8 data bits, two stop bits, no flow control, and no parity. I have noticed that the data is only prope... | I was able to discover the cause and fix the problem!
I am using a Raspberry Pi 4 for this project and interfacing with GPIO pins 14/15 to use /dev/serial0. With the default configuration /dev/serial0 maps to /dev/ttyS0 which is a mini UART and is not capable of using multiple stop bits, etc.
Disabling Bluetooth sets t... |
73,870,453 | 73,870,546 | Difference between std::reverse_iterator member functions: _Get_current() and base()? | Both member functions appear to do the same thing.
In the example below, both return an iterator pointing to the same memory location.
a) Is there any practical difference?
b) Why cant I find any info for _Get_current() in the std class documentation? I suspect the underscore prefix is a clue.
std::string s = std::stri... | If you ever see an identifier that starts with an _ followed by a capital letter, that identifier is being used by the internals of the C++ implementation and should never be used by you. You don't see it documented because it's for internal use only, specific to that implementation of the library type.
Just use the ac... |
73,870,625 | 73,870,771 | pass rvalue to std::move and bind rvalue refence to it generate stack-use-after-scope error in ASAN | considering this code snippet
#include <iostream>
int foo() {
int a;
return a;
}
int main() {
auto &&ret = std::move(foo());
std::cout << ret;
}
compile with ASAN g++ -fsanitize=address -fno-omit-frame-pointer -g -std=c++17 main.cpp -o main, run ./main shows error
==57382==ERROR: AddressSanitizer: stack-use-af... | Assigning a prvalue (such as an int) to an auto&& variable will enable lifetime extension. The temporary will exist as long as your variable exists.
Passing a prvalue to std::move() will convert the prvalue (int) to an xvalue (int&&). Lifetime extension no longer applies, and the temporary is destroyed before reachin... |
73,872,417 | 73,872,438 | How to declare assembly function with dynamic arguments in C++ like in C | I have some C code and I want to port it to c++, the problem is that in C++ I can't use an assembly function due to it's dynamic use
C version
extern asmFunc(); // C function prototype version
//actual use example
asmFunc(var1,ptr2,HANDLE);
asmFunc(ptr4,var2,NULL,eg ...); //everything works
C++ version
extern "C" VO... | Use ... in the argument list to specify the function is a variadic function taking unspecified arguments, eg:
extern "C" VOID asmFunc(...); // C++ function prototype version
//actual use example
asmFUNC(var1,ptr2,HANDLE);
asmFUNC(ptr4,var2,NULL,eg);
|
73,872,436 | 73,873,892 | Adding values in an array by skipping one specific value in every iteration | I am trying to solve this problem from hours but could not find a solution. What I am trying to do is, I have an array of 4 indexes arr[4] = {7, 3, 2, 4}. Now the task is to add every element in every iteration but skipping that value on which iteration is going on. For example:
input = arr[4] = {7, 3, 2, 4}
1st iterat... | You have to move your sum declaration inside the outer for loop, so that it gets reset at every outer iteration. Then in every inner iteration, you only add the element, if i!=j. Then you don't need to subtract anything from sum and you don't need the additional result variable.
#include <iostream>
int main() {
in... |
73,872,461 | 73,872,596 | Error: expected primary-expression before ']' token. Need assitance with function definition and calling | This is my first semester of computer science, and I need help with my first project. So far, it's still a mess, and I am mainly doing test cases to ensure basic things like my functions work.
The goal of the project is to ask the user how many robots they want to make, name them, then they can use the robot's name (th... | First off, userRobot RobotArray[NumberOfRobots]; is a variable-length array, which is a non-standard extension supported by only a few compilers. To create an array whose size is not known until runtime, you should use new[] instead, or better std::vector.
That said, your main issue is that you are trying to define yo... |
73,873,332 | 73,873,357 | Error C2280 in a simple piece of C++ code | I'm trying to solve a "stupid" problem I got with Visual Studio Enterprise 2022.
I created a new MFC application from scratch, then I added this single line of code:
CFile testFile = CFile(_T("TEST STRING"), CFile::modeCreate);
When I try to build the solution, I get this error from the compiler:
error C2280: 'CFile::... | CFile objects can't be copied, but that is exactly what you are trying to do - you are creating a temporary CFile object and then copy-constructing your testFile from it. 1
Use this instead to avoid the copy and just construct testFile directly:
CFile testFile(_T("TEST STRING"), CFile::Attribute::normal);
1: I would ... |
73,873,635 | 73,873,736 | Why are `function<void (string)>` and `function<string (string)>` parameter types sometimes ambiguous for overloading? | Following up my question c++ - How do implicit conversions work when using an intermediate type?, from which I understood the rule of 1 implicit conversion max, I'm trying to understand a more advanced use case involving function arguments.
Let's say I have a function, which accepts as a parameter another function. Tha... | This is because std::string(*)(std::string) is "compatible" with both std::function<void(std::string)> and std::function<std::string(std::string)> since the former can simply ignore the underlying function's return value.
That is, both of the following are valid:
std::function<void(std::string)> voidFunc(printNonVoid);... |
73,873,893 | 73,873,962 | Time Complexity of nested for loops with different conditions | What would be the time complexity for this snippet? I'm having a little trouble understanding how to find the time complexity of nested for loops with different conditions.
I originally thought that it would be n^3 x n^2 which gives O(n^5), but should it be (n^3)^2 which gives O(n^6)?
for(int i = 0; i < n*n; i++) {
... | If you correctly incremented j in the inner loop (replacing i++ with j++ in the inner loop increment step), it would be O(n⁵). The outer loop runs the inner loop n² times, with each inner loop running n³ times; the total is strictly multiplicative, n² * n³ == n⁵.
As written, it'll never stop running if n > 1 (because j... |
73,873,989 | 73,886,473 | Is there a g++ flag that can detect and warn about this unreachable code in a switch statement? | This isn't quite the minimum possible reproduction, but hopefully illustrates the issue well while being bite-sized.
#include <iostream>
int main(int, char **)
{
int i;
std::cin >> i;
switch(i)
{
case 0:
break;
std::cout << "too small" << std::endl;
case 1:
break;
... | This is basically resolved in the comments by Eljay and Jerry Jeremiah, but for the sake of closing the question out, it looks like gcc silently removed unreachable code detection back in 2014 because it gave different results at different optimization levels.
This seems like a remarkably stupid justification for remov... |
73,874,619 | 73,956,681 | Compilation issue on mac Error: No matching constructor for initialization of 'wavenet::WaveNet' | I have a Compilation issue on mac, I'm trying to build this Neural Amp Modeler https://github.com/sdatkinson/iPlug2/tree/main/Examples/NAM on a Apple M1 MBP macOS 12.6 / Xcode 14.0
The code in that repository works on Windows but on my machine I get these errors:
Error: No matching constructor for initialization of 'wa... | I made a quick guess based on my experiences (Unfortunately, I cannot test it on a Mac).
Since the compile error comes from get_dsp.cpp we should try to fix it there before trying to change something in the class WaveNet itself.
The make_unique call is issued in get_dsp.cpp, line 83.
In line 87 is the 4th parameter to ... |
73,875,331 | 73,875,348 | Is it an UB when I try to pass the address of temporary as argument? | For the following C++ codes:
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "A()\n"; }
~A() { cout << "~A()\n"; }
A* get() { return this; } // <------
};
void f(const A * const &a, const A * const &b) {
cout << "f()\n";
}
int main() {
// f(&A(), &A()); // error: taking address of... |
So my question is, is it an Undefined Behaviour to use get()?
No, it's not undefined behavior. It's valid because the temporary object is first constructed, then the function is called, and then (only after the function returns) is the temporary object destroyed again. So during the lifetime of the function call, y... |
73,875,402 | 73,875,469 | Why does std::map crash when it is declared static inline inside a class and used early? | I have found several times that when a std::map is declared inside a class as a static inline (C++ 17),
struct MyStruct
{
static inline std::map <A, B> mymap;
MyStruct(A& a, B& b)
{
mymap[a] = b;
}
};
the MyStruct constructor will crash if it is called early, i.e. before main, inside the first... | Declaring a static inline class member effectively ODR-defines that class member in some randomly-chosen translation unit that forms the final executable.
At this point Static Initialization Order Fiasco becomes a factor when the class member gets referenced in a translation unit in the manner you described.
This resul... |
73,875,833 | 73,875,956 | Meaning of code involving function binding | Can someone explain what is going on in the below code snippet line by line
auto enq_func = [](std::queue<reg_t>* q, uint64_t x) { q->push(x); };
std::queue<reg_t> fromhost_queue;
std::function<void(reg_t)> fromhost_callback =
std::bind(enq_func, &fromhost_queue, std::placeholders::_1);
I think I get the gist of it,... | This is a slightly overly-complex way to create a function-like callable object that pushes its argument into fromhost_queue. That is, fromhost_callback(123) will end up calling fromhost_queue.push(123).
auto enq_func = [](std::queue<reg_t>* q, uint64_t x) { q->push(x); };
This is a lambda expression that creates a c... |
73,876,624 | 73,876,653 | Classes not giving required output in c++ | I have created a class name Employee and inside that I have declared a function and two variable(name ,age) . After creating a variable x I am not getting the name insted getting empty name and age =0
CODE:
#include<iostream>
using namespace std;
class Employee{
public:
string name;
int age;
void print(){... | Employee(string name, int age) {
name = name;
age = age;
}
you are not modifying the class members, but the parameters instead.
You have three ways to solve this problem:
use this-> to precisely target the right variables.
Employee(string name, int age) {
this->name = name;
this->age = age;
}
use an i... |
73,876,979 | 73,878,956 | C++ Convert string logical expression to conditional expression | I have a logical expression in string and need to evaluate. Is there a way in C++ do it?
std::string exp = "(1||0)&&(1&&1)&&(1||0&&0)";
Eg:
if ((1 || 0) && (1 && 1) && (1 || 0 && 0))
{
std::cout << "true\n";
}
| There's no easy built-in way in C++ to evaluate logic expressions like that. If you want to evaluate such an expression in runtime, you need to parse a string into some intermediate representation first (e.g. an expression tree) by writing a parser and write an evaluator that will flatten that tree into a single value.... |
73,877,598 | 73,954,016 | GRPC with one server and several clients | Q1:
When I have a GRPC connection with one server(S) and several clients(C1 and C2)(Using Response-streaming RPC).
I wonder how frames S sends to C1 and C2?
For example, there's 10 frames that server needs to response. What will C1 and C2 receive separately and Why?
C1 gets 5 frames and C2 gets another 5(I tried my pr... |
gRPC is point-to-point. The connection C1 -> S and C2 -> S are separate. Any message that S sends will be directed at either C1 or C2. If duplication is required between clients, the server application logic will need to manage this itself.
Great question. This is a point that people often miss in designing their pro... |
73,878,113 | 73,878,716 | Repeatedly non-stop output when I input char into int variable | The folowing code tells user to input their age, it is set to be input interger between 0 and 120, it is capable to deal with wrong input like 'M' or 133 or -1. Warning message goes like this:Warning message
case 1: // input age
cout << "Enter your age: ";
cin >> age;
... | By emptying the keyboard buffer before a new entry.
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int age;
cout << "Enter your age: ";
cin >> age;
while(age <= 0 || age > 120)
{
cout << "Invalid input! Please enter again" << endl << ">>>";
cin.clear();
... |
73,878,221 | 73,878,245 | Static pointer to a class method, if possible and meaningful | Usually for singleton classes, one has to write all the time something like this:
SomeSingleton::GetInstance().someVariable
And I'm looking for a simplification that can be seen everywhere, so should be put in the (header and source) files of the class itself.
So, the (non-working) stuff should look something like thi... | I think the only thing you are missing is extern in your header
extern SomeSingleton& (*INSTANCE)();
|
73,878,908 | 73,880,020 | Is it possible to devirtualize this method call with GCC? | In the piece of code below, I expect the a->f2() call to be devirtualized, providing all compiler optimizations are enabled (-O3).
#include <memory>
#include <iostream>
class AbstractA {
public:
virtual ~AbstractA() = default;
virtual void f1() = 0;
virtual void f2() {
std::cout << "AbstractA::f2"... | Assuming you know that AbstractA::f2 is not a pure member function, then you can simply override it explicitly from ConcreteA so GCC can inline AbstractA::f2 and so ConcreteA::f1:
// In ConcreteA:
void f2() override
{
AbstractA::f2();
}
The vtable is still present due to a missing global optim... |
73,879,411 | 73,879,610 | C++ Error: error: expected unqualified-id before string constant | What should I do in this line of code (highlighted by comment) ?
# include <iostream>
int main()
{
int occurrences = 0;
std::string::size_type start = 0;
std::string base_string = "Hello World in C++!";
std::string to_find_occurrences_of = "o","+"; // error
while ((start = base_string.find(to_find... | std::string to_find_occurrences_of = "o","+"; won't compile, because you have two strings, rather than one.
You could just have an initialiser list of the things to find:
int main()
{
int occurrences = 0;
// std::string::size_type start = 0; // need to reset for each character
std::string base_string = "He... |
73,880,034 | 73,880,075 | Operator>> overloading: "cannot bind 'std::istream {aka std::basic_istream<char>}' lvalue to 'std::basic_istream<char>&&'" | Here's my fraction class:
class fraction { // type definition
int num;
int denom;
ostringstream sstr;
public:
fraction(int c=0, int d=1) :
num(c), denom(d)
{ sstr = ostringstream(); }
fraction(const fraction &f) : num(f.num), denom(f.denom) { /*void*/ }
friend ostream& operator<<(ostre... | Remove the const:
friend istream& operator>>(istream &is, fraction &f){
Clearly, since operator>> is modifying f, it should not be const.
On the other hand, the const in operator<< is correct, because that function does not modify f.
Also, is >> "(" is incorrect. Not clear what you intend by that, but you cannot read ... |
73,880,279 | 73,956,879 | Unable to successfully instantiate BreakIterator even after u_setDataDirectory was set | I am using ICU's BreakIterator (icu 68.2) for word segmentation.
I have used u_setDataDirectory to initialise the data path as mentioned in below code snippet's 1st line.
But when I check the status of createWordInstance(), I am getting U_MISSING_RESOURCE_ERROR. This kind of error should be solved by calling u_setDataD... | If u_setDataDirectory is the only cause for your error, you must call it with the correct path to the data directory.
change your first line from
u_setDataDirectory;
to (on Linux/Unix)
u_setDataDirectory( "/path/to/ICU/data/" );
or on Windows to
u_setDataDirectory( "C:\\Path\\To\\ICU\\Data\\" );
Unfortunately I d... |
73,880,594 | 73,880,888 | static_cast to the base of base class with protected inheritance | I don't quite understand why below code is not legal.
struct A {
int a;
};
struct B : protected A {
int b;
};
struct C : B {
int c;
} tc;
const A &ra = static_cast<A &>(tc);
Could someone help to explain it? Thank you very much.
| The public, protected and private specifiers let access in different-wide areas. You can access protected members only in your class functions or its heirs.
For example that code works:
struct A {
int a;
};
struct B : protected A {
int b;
};
struct C : /*implicit `public` b... |
73,880,798 | 73,884,081 | Drake: Integrate Mass Matrix and Bias Term in Optimization Problem | I am trying to implement Non Linear MPC for a 7-DOF manipulator in drake. To do this, in my constraints, I need to have dynamic parameters like the Mass matrix M(q) and the bias term C(q,q_dot)*q_dot, but those depend on the decision variables q, q_dot.
I tried the following
// finalize plant
// create builder,... | I think you want to impose the following nonlinear nonconvex constraint
lb <= M * qddot + C(q, v) + g(q) <= ub
This constraint is non-convex. We will need to solve it through nonlinear optimization, and evaluate the constraint in every iteration of the nonlinear optimization. We can't do this evaluation using symbolic... |
73,880,812 | 73,895,305 | C++ version in .vcxproj files | Is this possible to fetch project's standard of C++ language from .vcxproj files without opening Visual Studio and manually checking it?
| I can not add comment. So I post answer here.
In Visual Studio C++ project, LanguageStandard will not appear if the language standard has not been changed (Default C++14). After specifying the language explicitly and rebuilding the project, You will find LanguageStandard in the .vcxproj file.
There should be similar co... |
73,880,878 | 73,973,261 | QT QString to qml string converts with question marks on windows | When I am trying to display text that contains "·" symbol in QML, I am facing a strange behavoiur.
If I define the string with this symbol directly in the qml file:
...
Text {
text: "1 · 2"
}
Everything displays fine, but when I am trying to get this string from c++:
...
Q_INVOKABLE QString brokenStr() {
retur... | As Öö Tiib mentioned, compiler on windows could not read the plain "·" correctly.
The workaround was to use QChar(0xb7) instead.
Final solution is returning QString("1 %1 2").arg(QChar(0xb7)) from cpp function
|
73,881,018 | 73,881,148 | Passing a lambda to a template function taking a std::function as parameter | I have a template function taking a std::function parameter, the template arguments defining function signature:
template<typename... Args>
void addController(const char * name, const std::function<bool(Args...)> & func);
It works passing a std::function variable:
std::function<bool()> foo_func = [this]()->bool {retur... | Way to go is generic callable:
template<typename F>
void addController(const char* name, F f)
You can forward it to your std::function version if needed:
template <typename... Args>
void addController(const char* name, const std::function<bool(Args...)> & func)
{
/*..*/
}
template <typename F>
void addController(c... |
73,881,357 | 73,884,163 | How to get std::bind refer the explicit constructor defined in class while providing pointer to class member function as arguement? | I'm using std::bind in my code as shown below:
std::bind(&Filter::odometryCallback, filter, std::placeholders::_1, odomTopicName, poseCallbackData,
twistCallbackData);
The Filter class has explicit constructors defined and hence no default constructors are generated by the compiler (for this class)... | If you want to std::bind a reference parameter, you need to wrap it in std::reference_wrapper, as bind is an ordinary function, that does lvalue-to-rvalue conversion on it's arguments.
std::bind(&Filter::odometryCallback, std::ref(filter), std::placeholders::_1, odomTopicName, poseCallbackData, twistCallbackData);
|
73,881,526 | 73,881,712 | Equivalent Resistance using integers c++ | What am I trying to do?
I am trying to calculate the equivalent resistance of this resistance setup:
R1, R2, R3, R4 are of type int given by the user. The computer should compute the equivalent resistance Req of type int rounding it to the nearest integer.
What have I tried?
I have tried rounding using the ceil functi... | To do it with integer types you have to go through two steps. First, do the division. Second, check the remainder to see whether the truncated result needs to be adjusted.
int result = (R12 * R34) / (R12 + R34);
int rem = (R12 * R34) % (R12 + R34);
if (2 * rem >= R12 + R34)
++result;
If you write code like that in... |
73,881,936 | 73,894,490 | How to separate monochromatic objects of different sizes in opencv | I want to separate a noiseless 1-bit (black and white) image with white circles based on the concave part of the outline.
Please refer to the picture below.
This is the white object to separate:
The target result is:
Here is my implementation with the watershed algorithm:
The above result is not what I want.
If the ... | If you want to find the minimal openings, you can use a medial axis based approach.
Pseudo code:
compute contours of bitmap
compute medial-axis of bitmap
for each point on medial-axis:
get minimal distance d from medial axis algorithm
for each local minimum of distance d:
get two points on bitmap contours wit... |
73,881,963 | 73,882,682 | Understanding libunifex's member_t template metaprogramming facility | I'm currently trying to understand the std::execution proposal by studying libunifex's implementation. The library makes heavy use of template metaprogramming.
There's one piece of code I really have trouble understanding:
template <class Member, class Self>
Member Self::* _memptr(const Self&);
template <typename Self... | _memptr is a function declared in such a way that
_memptr<Member>(self)
will give you a pointer to member of <class type of self> of type Member regardless of self's constness or value category. So if Self is possibly a reference type,
Member Self::*
would be ill-formed, but decltype(_memptr<Member>(std::declval<Self... |
73,882,312 | 74,170,820 | Missing libstdc++ headers for arm-none-eabi on Fedora Linux | I am programming the Raspberry Pi Pico-W and I would like to link against the C++ STL, in order to use some of the Standard Library functionalities and containers.
I have found the package on Ubuntu, which I used in a professional development environment and I therefore also wanted to install it on Fedora 36, but found... | Fedora does not seem to provide such packages and I have also not been able to find copr repos for that.
Therefore the only solution left, was to install directly from arm.
This link gives a short guide for those that need it.
Additionally, since I am using NeoVim with its built-in lsp, I need to add a flag to the clan... |
73,882,720 | 73,883,549 | couldn't infer template argument - do I need to use explicit template parameters? | template <int I, typename T> struct Wrap {
T internal;
};
template <int I, typename T>
Wrap<I, T> DoStuff(int z) { return Wrap<I, T>{(T)z}; }
class Wrapped {
public:
// Working
Wrap<1, int> GetInt() { return DoStuff<1, int>(1); }
Wrap<2, long> GetLong() { return DoStuff<2, long>(2); }
// Not working
Wrap<3, ... | Deduction doesn't use return value... "Except" for converting operator.
So you might create a class which convert to any Wrap<I, T>:
struct ToWrap
{
int n;
template <int I, typename T>
operator Wrap<I, T>() const { return Wrap<I, T>{T(n)}; }
};
ToWrap DoStuff(int z) {
return ToWrap{z};
}
Demo
|
73,883,660 | 73,883,856 | Avoiding stack overflow when implementing depth first search in c++ | connected components of triangle faces in a mesh
I have implemented depth first search using the above link and works fine for most of my data samples. When my data sample is very large, the code reaches a break point, likely to be stack overflow as the recursive function gets too deep. Is there any way to avoid this? ... | With a recursive algorithm, there is no way to avoid a stack overflow. But, you need to re-implement your algo with an iterative version using a stack.
Here is a rough implementation .
void Graph::DFSUtil(int v)
{
stack<int> stack;
stack.push(v);
cout << v << " ";
while (!stack.empty())
{
in... |
73,883,980 | 73,884,249 | Can't debug 32bit application with gdb and a dynamic loader into remote target arm64 | I'm trying to use gdb for debug an application in an arm64 device in a particular situation:
-The device is an embedded linux arm64 running linux:
$ uname-a
Linux HMI-fa93 4.14.78-rt47 #1 SMP PREEMPT RT Fri Apr 29 08:40:42 UTC 2022 aarch64 GNU/Linux
I have no problem at all when trying to use gdb with an application ... |
I launch the debug in this way
Yes, when you launch the app this way, GDB will think that you are running ld-linux-armhf.so.3, and debugging will be very difficult.
It is possible to debug the app launched that way -- you would need to figure out where the main binary (assuming it's PIE) and all the shared libraries ... |
73,884,235 | 73,885,214 | How to use C++ library in Vala | I want to use vega library for working on dicom files. Sample code from its website is as follows:
#include <string>
#include "vega/dictionary/dictionary.h"
#include "vega/dicom/file.h"
int main() {
// Set the dictionary file
vega::dictionary::Dictionary::set_dictionary("/path/to/dictionary/dictionary.txt");
... | Yes, that would be correct, I believe. You can only link a C library, without namespaces and whatnot.
To use your C++ library in Vala, I would say you have to either have to either a) rewrite everything in C, but this is obviously lots of work, so very undesirable, or b) find a version of your library written in plain ... |
73,884,580 | 73,884,866 | Sfml lostFocus / gainedFocus cpu usage | Why when I run this simple code and just doing nothing CPU usage by this app is around 0.4%
#include <SFML/Graphics.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 800), "hi", sf::Style::Close | sf::Style::Titlebar);
window.setFramerateLimit(60);
sf::Event event;
bool lostFocus = false;
... | As already mentioned, when your window doesn't have focus and you're not updating the window, the loop goes into a hot spin where it's continuously checking for events. When you've lost focus, you instead want to block and wait for a GainedFocus event to occur. As a very simple example, you could do something like
void... |
73,884,830 | 73,884,932 | Accessing private member of base class using derived class member function | I have just started learning about inheritance and I know that private members of base class are not inherited by the derived class.
But when I run the 'get_data1' function of the derived class, it returns the value of data1 from the base class even though I have defined a new 'data1' in the derived class.
So shouldn't... |
I know that private members of base class are not inherited by the derived class.
No, private members are inherited just like other members. The difference is that they're not accessible from the derived class unlike public or protected members.
shouldn't it return 3 instead of 5 as it is a member function of the d... |
73,885,177 | 73,885,398 | Why can't I use 'delete' for this line? | I've started to learn linked lists today, and I am trying to delete nodes.
void deleteEnd(Node* refNode) {
Node* lastNode;
lastNode = new Node;
while((refNode->next)->next != NULL) {
refNode = refNode->next;
}
lastNode = refNode->next;
refNode->next = NULL;
delete lastNode;
}
void... | As pointed out by the comments, there are several things wrong with this code. All issues are from the comments, none are found by me, all credit goes to François Andrieux, Jesper Juhl, Sven Nilsonn, Avi Berger, and Thomas Matthews.
First, the code probably doesn't work because you mixed new and free. new is a C++ API ... |
73,886,229 | 73,886,670 | Templated sub-class with `std::string`-to-`T` conversion in virtual function | I have a sub-class that has to implement a virtual function so that callers can interface with it without knowing its concrete type. But I'd like to template this sub-class to work with different types. Basically, this:
class Base
{
public:
virtual void insert(const std::string & val, const std::string & type_str) ... | You can use if constexpr (C++17 and later):
#include <type_traits>
class Base
{
public:
virtual void insert(const std::string & val, const std::string & type_str) = 0;
};
template<typename T>
class C : public Base
{
public:
virtual void insert(const std::string & val, const std::string & type_str) final
{... |
73,886,251 | 73,886,808 | C++ input/output queue for multiple input source | I have a task that requires listening to multiple data source, and process the data to calculate some statistics (like cumulative sum of all data) for every new record coming in.
I am reading this post for a queue with condition variables. I wonder if this solution will work for multiple input scenario.
Say we have two... | Yes, but what is the the problem? Producer A (we call them producers) will lock, add an item to the queue, notify, unlock (or in some versions - not in C++ - unlock and then notify). Producer B will lock, add an item, notify, unlock. The consumer will wake up, lock, check the queue, get an item, unlock, and process the... |
73,886,685 | 73,891,668 | Segmentation Fault when working with argv C++ | I have until now:
int main(int argc, char * argv[]) {
std::vector<std::string> args;
for (int i = 1; i < argc; i++) {
args.push_back({ argv[i] });
}
std::string dateString = args[1];
return 0;
}
and I get Segmentation Fault on line: std::string dateString = args[1];
What I want to do is to use somethi... | When you use ./myalgorithm.cpp 2022-09-01, what are argc and argv?
argc is count of arguments + program name.
argv is program name and these arguments.
So argc = 2 and argv = { myalgorithm.cpp, 2022-09-01 }
std::vector<std::string> args;
for (int i = 1; i < argc; i++) {
args.push_back({ argv[i] });
}
Afte... |
73,886,997 | 73,887,121 | Was a new constructor added to std::string in c++23 that accepts std::array<char, N>? | Recently a bug was discovered in our code where we were accidentally converting a std::array<char, N> to std::string. The buggy code doesn't compile in c++20 mode but compiles and //mostly// works in c++23 mode except for some edge cases with null termination. I'm using gcc 11.1.
#include <iostream>
#include <string>
#... | Yes, it is related to P1989.
One of std::string's constructors is:
template< class StringViewLike >
explicit constexpr basic_string( const StringViewLike& t,
const Allocator& alloc = Allocator() );
which is constrained on StringViewLike being convertible to std::string_view.
P1989 adde... |
73,887,205 | 73,922,663 | __static_initialization_and_destruction_0 seg fault | I was developing a C++ program and everything was working fine. Then, while I was programming, I ran make and ran my program like usual. But during the execution of it all, my computer crashed and shut itself off. I reopened my computer and ran make again but this time it gave me a bunch of errors.
Everything seemed of... |
this segfault occurs without ever printing that, so it led me to believe that this error is linker related.
The linker is not involved in your program running, so it can't be "linker related".
There is a dynamic loader (if your program uses shared libraries), so perhaps that's what you meant.
In any case, the crash i... |
73,887,477 | 73,887,516 | Can someone explain the syntax behind this line of code? C++ | My professor is having us change her functions to work for her assignment on Binary Search Trees. I know that this line she has assigns myHeight to whatever value being compared that is greater, but I have no idea how it's actually doing that.
int maxH = (hL > hR) ? hL : hR;
I want to use this in the future since it ca... | This is the so called "conditional operator" in c++. It works as follows:
the expression before the ? is evaluated and converted to bool,
if it evaluates to true, the second operand is evaluated (i.e. hL in your example),
otherwise, the third operand (hR in your example) is evaluated.
The result is assigned to maxH.
... |
73,887,705 | 73,887,750 | fields use to implement hash and comparison functions in unordered_map | Is it necessary for the comparison and the hash function of a custom type in an std::unordered_map to use the same set of fields? (i.e) given:
struct Foo { int i; float f; };
If I generate hashes only using i but use both i and f to implement equality, will I run afoul of anything? In my understanding, the comparison ... | That's fine, all that is required is that x == y implies hash(x) == hash(y) which your scheme does.
|
73,888,449 | 73,888,740 | C++ Complex number expression for integrating | I'm trying to implement Monte-Carlo method to solve an integral and can't figure an approximation for my function.
double function(double x)
{
std::complex<double> fz = (pow(-7 * pow(x, 4) - 3 * x + 11, 1.0/3.0) / pow(-2 * pow(x, 6) - 14 * x - 8, 1.0/4.0));
cout << fz << endl;
double f = fabs(fz);
retur... | The problem was with std::pow function. To apply it to complex numbers, the first argument of it must be of complex type:
std::complex<double> numerator(-7 * pow(x, 4) - (3 * x) + 11);
std::complex<double> denumerator(-2 * pow(x, 6) - (14 * x) - 8);
std::complex<double> fz = pow(numerator, third) / pow(denumerator, qua... |
73,888,694 | 73,888,772 | decltype does not preserve ref qualifier from structured binding | Usually decltype perseveres the ref qualifiers
auto a = 0;
auto& a_ref = a;
static_assert(std::is_reference_v<decltype(a_ref)>);
But apparently not when it's argument is obtained from structured binding
auto p = std::pair{1, 2.f};
auto& [i, d] = p;
static_assert(std::is_reference_v<decltype(i)>); // fails
https://god... | Looks like this is how it is supposed to be:
decltype(x), where x denotes a structured binding, names the referenced type of that structured binding. In the tuple-like case, this is the type returned by std::tuple_element, which may not be a reference even though a hidden reference is always introduced in this case.
... |
73,889,051 | 73,889,161 | std::initializer_list rvalue/literal as parameter of (variadic) template | Please help me to understand why a std::initializer_list literal can't be deduced as a template parameter? AFAIK, there's no notion of an init-list literal in the language yet, but then why/how does this work?
auto il = { 1, 2, 3, 4, 5 };
Here is my code:
import <iostream>;
import <string>;
import <vector>;
... | The short answer: initializer lists (the language mechanic, not the type) are magic. No, really.
The C++ standard has explicit wording for initializer-list syntax to produce a std::initializer_list object in certain circumstances such as constructing an auto-parameter, but an initializer list expression is not itself a... |
73,889,446 | 73,889,544 | Is there an advantage of using parentheses in decltype over explicitly typing const ref | Which is better:
decltype((foo)) x = bar;
const decltype(foo)& x = bar;
If these are just two ways of saying the same thing, why are the parentheses even part of the language?
| If you want to declare "a reference to the same type of object as foo", then I would prefer the second option. That's not really what the other form of decltype is for.
The decltype keyword pulls double-duty:
It tells you the type of a variable
It tells you the type and value category of an expression
That's what th... |
73,889,608 | 73,891,209 | How to detect a CMenu visiable or not in MFC? | I'm making a right click menu in my application. And I want to check whether the menu is shown or not. But I read the Microsoft docs of CMenu and found that there is no way to make it. How to get the menu state, and is there any way to get the menu disappear event?
| The system sends a WM_ENTERMENULOOP message to a menu's owner window whenever a menu is about to be shown, and a WM_EXITMENULOOP message after it has been dismissed.
Those messages map to the CWnd::OnEnterMenuLoop and CWnd::OnExitMenuLoop message handlers that your code can override to keep track of the menu state. The... |
73,890,249 | 73,891,111 | I have a question about the paramether of GetPriorityClass Function (and [in] attribute) | DWORD GetPriorityClass(
[in] HANDLE hProcess
);
In the documentation they says if the function succeeds, the return value is the priority class of the specified process.
The parameter takes [in] HANDLE hProcess that will be the process that i will be take the priority, but i dont know what means [in] or if i have t... | As you can see in the documentation, GetPriorityClass:
Retrieves the priority class for the specified process.
(emphasis is mine)
The handle to the process is passed as the hProcess input argument (marked with the [in] attribute) to the function.
This just means you have to supply it yourself.
Something like:
HANDLE ... |
73,891,476 | 73,893,800 | change optimal base of radix/counting sort? | Im learning to implement radix sort but im having trouble understanding how to change to a base different from the optimal base log(n) on base 10 to 2^log(n), with a floor function on the ln. Im using this code from GeeksForGeeks which tend to follow the CLRS pseudocodes, to learn:
// C++ implementation of Radix Sort
... | The base is the factor by which you would divide a number repeatedly to identify its digits in that base.
For instance when base is 10, and we have the number 12, then we can identify the least significant digit by dividing it by the base, which gives us 1 with remainder 2. That remainder is the least significant digit... |
73,891,771 | 73,891,860 | Class template argument deduction using function return type | I want to make a class with a template parameter and a function (also with a template parameter) that returns a class instance.
However, for shorter code, I want to omit template parameters when returning the result of class construction.
I have no clue how do I call this type of technique and if it is possible.
For a ... | This is not possible.
Template types are concrete after compilation, unlike languages like C# where there's metadata so it can allow uncomplete generic types, C++ doesn't.
Types like Class<> or Class<int,> are not possible.
You could do Class<void> and let template deduction fill the void (pun intended).
Or you could t... |
73,891,984 | 73,892,113 | GTest pass std::vector as a parameter source | I have a function which reads out all files in a selected directory.
std::vector<std::string> getAllFilesInDirectory(const std::string_view strDirectory);
Now I'd like to run my tests on each element of that vector.
My test fixture is pretty straight forward.
class myTestfixture: public ::testing::TestWithParam<std::s... | You have almost done it but with a small mistake. Try to use ValuesIn() instead of Values().
INSTANTIATE_TEST_CASE_P(
myTest,
myTestfixture,
::testing::ValuesIn(
getAllFilesInDirectory("myDir")
));
|
73,893,154 | 73,893,342 | Decay std::array to pointer | I have class like this:
struct S{
void method1(int *a){
// use a
}
void method2(int *a){
// use a
}
};
To avoid allocation, I am doing following:
std::array<int, 100> a;
S s;
s.method1(a.data());
However much nicer will be if I can able to do, without making all methods templates.
std::... | You can use non-member std::data and call it like s.method1(std::data(a));.
That works for raw arrays, std::array, std::span and others.
|
73,893,180 | 73,904,508 | Pass JS function to C++ as function parameter | I want to make async call to C++ native function, but have some problems: when I call native function in async block (in Promise, exactly), it blocks UI thread and no async call is made. I want to pass callback to C++ function and call it. How can I pass function object?
class frame : public sciter::window {
public:
... | Well, here are a few possibilities: we can use callback.call() if a function or function object was passed or just return Promise like object. Examples:
void asyncFunction(::sciter::value callback)
{
std::thread{ [callback]()
{
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
scite... |
73,894,166 | 73,896,952 | Why do profilers fail to get information from my program? | I am trying to profile a C++ program but whenever I run a profiler I get no information even though the debug information works as I can run a debugger on it.
I tried using AMD uProf, Very Sleepy and Visual Studio but all of them give me no information. No functions get detected.
The program is compiled using clang-cl ... | It seems like Windows Defender was messing with somethings, it has caused me some trouble in the past as well. Disabling it and rebooting seems to have fixed the problem. Also due to the program having such a short execution time most profilers aren't able to get enough samples
|
73,894,292 | 73,896,155 | Plot Histogram from vector data in C++ | I'm trying to do a simple task. Draw an Histogram in C++, I'm reading data from a audio file and stored the counted values in a vector.
wav_hist.h
class WAVHist {
private:
std::vector<std::map<short, size_t>> counts;
public:
WAVHist(const SndfileHandle& sfh) {
counts.resize(sfh.channels());
}
... | The C++ standard itself does not provide any classes for visualization or graphical user interfaces. There are, of course, many frameworks and libraries available for that.
Since you already know gnuplot, you may be interested in a C++ interface for gnuplot.
Other alternatives include Qt Charts or Boost.Python.
See als... |
73,894,588 | 74,657,856 | getting nested values from a decoded SAMLresponse XML with rapidxml | I have been trying to get the values of the decoded XML, all 3 of them.
The XML file is as follows (it has way more nodes but this is just a testing preview)
<Response ID="number" Version="2.0">
<Issuer xmlns=":assertion">
check1
</Issuer>
<Status>
<StatusCode Value="Success" />
chec... | In case anyone is wondering what i did to fix not being able to search nodes by string input.
i wrote a function that searches for sibling nodes.
//gets the coun of child nodes present in current node
int getChildCount(rapidxml::xml_node<> *n)
{
int c = 0;
for (rapidxml::xml_node<> *child = n; ch... |
73,894,743 | 73,901,210 | ROS2 publish mesh marker | I'm trying to display a mesh resource in Rviz. It must be pretty straightforward as was in ROS1, but I'm not sure why it is not working.
Here is a sample code I tried:
// meshpub.cpp
#include <rclcpp/rclcpp.hpp>
#include <std_msgs/msg/color_rgba.hpp>
#include <geometry_msgs/msg/pose.hpp>
#include <visualization_msgs/m... | File paths have to be in the form file:///path/to/file or package://path/to/file. I mistakenly assumed
ament_index_cpp::get_package_share_directory("package") will by default return the path in the mentioned form.
So just manually appending a file:// to the returned path string fixed the issue.
|
73,894,913 | 73,894,984 | The compiler bug? Returning std::vector and std::string in std::tuple. But I got strange values | I would like to return multiple values and declare that function using auto.
But that does not work well. Values can not be returned correctly. It was overwritten.
I try to execute following functions f1~f3. Those function should return vector and string in tuple.
But only f3 works well.
#include <iostream>
#include <v... | The problem occurs because std::forward_as_tuple returns references to local variables - the return type is tuple<vector<double>&,string&>.
The first two functions produce undefined behaviour.
The third one works because you explicitly return by value, although the forwarding doesn't work because you did not move the l... |
73,895,431 | 74,003,596 | Unresolved External Symbol while trying to use bit7z library C++ / Qt | I've been trying to install and properly link bit7z into my C++ code as I have to do a task for my internship which concludes in automatically zipping a certain directory and sending the zip-file out as an email. Right now the email is not interesting to me as I can't even get the base program. I just keep getting the ... | The problem you're having is that the linker cannot find the bit7z static library.
By default, the bit7z library is built to bit7z\bin\$(PlatformShortName)\, where $(PlatformShortName) is either x86 or x64 according to your target architecture.
However, you specified a different library directory (bit7z\lib\), which is... |
73,895,736 | 73,895,788 | C/C++ Little/Big Endian handler | There are two systems that communicate via TCP. One uses little endian and the second one big endian. The ICD between systems contains a lot of structs (fields). Making bytes swap for each field looks like not the best solution.
Is there any generic solution/practice for handling communication between systems with diff... | Generally speaking, values transmitted over a network should be in network byte order, i.e. big endian. So values should be converted from host byte order to network byte order for transmission and converted back when received.
The functions htons and ntohs do this for 16 bit integer values and htonl and ntohl do this... |
73,895,847 | 73,896,033 | language c++, Error invalid types 'int[int]' for array subscript | I find the error that is in the title, this in my program that is a static queue with all its methods or functions, this error is in the following function.
void Cola::queve(TIPO_DATO datos){
if(cola1.vacia()){
final = (final+1)%TAM;
datos[final] = datos;
}else{
cout<<"No hay espacios en la cola"<<endl;
}
}... | The function parameter datos hides the members variable of the same name,
either
use different name:
void Cola::queve(int new_datos){
if(cola1.vacia()){
final = (final+1)%TAM;
datos[final] = new_datos;
}else{
cout<<"No hay espacios en la cola"<<endl;
}
}
or use this-> for the hidd... |
73,896,217 | 73,896,375 | Minimum in bitonic array with plateaus | I'm trying to find minimum in array which has this kind of structure in general:
Array consists of non-negative integers [0; 1e5-1]. It may contain any number of such steps, be sorted or just a constant. I want to find it in O(logn) thats why I'm using binary search. This code handle all cases except cases there is an... | I am afraid it is not possible to do in log n time in general.
Assume an array of n elements equal to 1 and a single element of 0.
Your problem now reduces into finding that 0 element.
By "visiting" (=indexing) any member 1 you gain no knowledge about position of 0 - making the search order irrelevant.
Therefore you h... |
73,896,764 | 73,896,830 | C++20 Concepts Apply constraint on templated function | I'd like to start with c++20 concepts.
class MyClass
{
template<typename T>
void copy(const T& data);
};
copy() only works if T is is_trivially_copyable. Before C++20 I'd have used
static_assert(is_trivially_copyable<T>, "Type must be trivially copyable");
within the copy function.
But from my understanding, this... | You need to add a type parameter for your sTriviallyCopyable to be applied to. That would give you
class MyClass
{
template<isTriviallyCopyable T>
void copy(const T & data);
};
|
73,897,460 | 73,899,122 | Random results when passing byte array from c++ DLL to c# client | I am passing a byte array from a function inside c++ DLL to a c# client.
I am using a widely suggested method IntPtr pointer in C# and then Marshal.Copy to create byte array in the C# client.
When I read the resulting array it seem I am getting random values. No actual values from the DLL are passed.
It seems the Int... | Your primary issue appears to be that the char* array is declared locally, and disappears as soon as the function finishes. One way to do this properly is to allocate it on the heap, and make a separate Free function.
But you are far better off just passing in a buffer. I'm not familiar with C++ very much, but somethin... |
73,897,702 | 73,897,781 | Get return code of a child process created with fork() | I'm trying to get the return code of the child process created by fork(). I'm using wait() function to get the return code. Everything is working fine but the return values given by wait() is 256 times the actual return value. Can anybody explain why is that.
Code:
#include <iostream>
#include <unistd.h>
#include <sys/... | Please read the wait manual page. The value given by wait doesn't only contain the child-process exit code, but also other flags and values.
To get the exit status you first need to make sure that the child-process really exited the normal way. This is done with the WIFEXITED macro.
Then to get the actual status use t... |
73,897,975 | 73,898,082 | How do I parse a string delimited by / into an array? | I have tried several methods of parsing a string and adding the elements to an array with using a / as a delimiter. I know I will eventually need to use stod(). Can anyone point me in the right direction? I will need to parse the string rec.
void make_record() {
int size = 4;
double* record = nullptr;... | It's really not a lot more complicated than your current approach.
// better approach
record = new double[size];
for (int i = 0; i < size - 1; i++) {
char slash;
cin >> record[i] >> slash;
}
cin >> record[size - 1];
The slash variable reads (and discards) the slashes in your input... |
73,898,385 | 73,916,623 | Load and Set Skeletal Mesh and Animation at runtime | I have a generic vehicle class, derived from the standard AWheeledVehiclePawn and I would like to load and change skeletal mesh and wheels animation at runtime depending on a vehicle type enum in input.
If I spawnm cars and set these assets from the editor, everything works fine, but if I try to set them programmatical... | For some unknown reasons I found that there was no controller associated to the spawned actor, and then the ChaosVehicleComponent was not able to set the throttle and steering values provided.
To solve this, I just added an AIController, move all the automatic movement logic there, and associated it to my car when crea... |
73,898,475 | 73,898,513 | C++ Reimplementing assignable "at()" function of vector | What i discovered
I discover that C++ vector::at() is an assignable function, how is it possible?
I mean I can call at() function to get the value of vector at certain position, and i can assign a value to a certain position of the vector.
std::vector<int> vec;
vec.push_back(4);
vec.push_back(5);
vec.pu... |
I want to reimplement in my own vector class without inherit it or copy the original class; how can i do it?
Not trying to sound too snarky but you could read the documentation:
Return value
Reference to the requested element.
Therefore something like this:
class myIntVector
{
int arraye[50] = {0};
//o... |
73,899,093 | 73,899,818 | Interfacing C++ iterators from C | I'm writing a C backend for a C++ library and I want the C code to be able to iterate over the individual items of a forward iterator. In C++ the code which iterates over the items looks like this:
auto rng = wks.range(XLCellReference("A1"), XLCellReference("Q1"));
for (auto& cell : rng) {
// do something with "cell... |
auto rng = wks.range(XLCellReference("A1"), XLCellReference("Q1"));
for (auto& cell : rng) {
// do something with "cell"
}
I like doing 1:1 relationship between C++ and C. The following code outputs 3 lines var=1 var=2 var=3.
By wrapping the objects inside structures, the C side only forward declarations of stru... |
73,899,269 | 73,899,573 | Conditionally initialize class variable depending on the template type | Suppose I have the following code:
enum class Type
{
Type32,
Type64
};
template<Type T>
class MyClass
{
public:
using MyType = typename std::conditional<T == Type::Type32, uint32_t, uint64_t>::type;
MyType getSum()
{
MyType sum = 0;
for(size_t i = 0;i < sizeof(arr);i ++)
... | Here is a simple way:
#include <array>
#include <cstdint>
#include <type_traits>
enum class Type { Type32, Type64 };
template <Type>
struct As128Bits;
template <>
struct As128Bits<Type::Type32> {
using Integer = std::uint32_t;
std::array<Integer, 4> data{0x1234, 0x5678, 0x9ABC, 0xDEF0};
};
template <>
stru... |
73,899,540 | 73,900,513 | How can I resume a stopped process? | Following this documentation, I am testing how to stop and resume a process. I have basic code to test as follows:
#include <iostream>
#include <csignal>
#include <unistd.h>
int main() {
std::cout << "Hello" << std::endl;
int pid = getpid();
kill(pid, SIGSTOP);
kill(pid, SIGCONT);
std::cout << "Bye... | A solution, if a bit complicated, is to create a child process to start and stop the parent. Here is a small code example, that might help:
#include <iostream>
#include <csignal>
#include <unistd.h>
int pid; //Include declaration outside so it transfers to the child process
int main() {
std::cout << "Hello" << st... |
73,899,992 | 73,900,072 | How can I kill a function after a timeout in Qt? | I have a function, let's call it foo().
void foo()
{
int count = 0;
while(1)
{
count ++;
if(count>= 30000)
{
count = 0;
}
}
}
foo() will run indefinitely, but let's say I want to fun my function foo() after 1 minute.
How can I do that using Qt?
I have already s... | You shouldn't kill threads but instead give them a condition to check if they should continue or quit. One way could use an atomic<bool> so that you can set it from another thread. You could also limit the time by measuring how long time the function has executed.
Example:
#include <atomic>
#include <chrono>
void foo(... |
73,900,540 | 73,901,478 | Why is a C++ lambda life cycle bound to the smallest block scope? | In the following example program, I would expect the counter to reset at the beginning of each cycle:
#include <iostream>
#include <functional>
void run_lambda(std::function<void()> fun){ fun(); fun(); }
int main(){
for(int i = 0; i < 3 ; ++i){
run_lambda([i](){
static int testVal = 0;
... | Your code is basically equivalent to:
#include <iostream>
#include <functional>
struct lambda
{
lambda(int i): i(i) {}
int i;
void operator()()
{
static int testVal = 0;
std::cout << "value[" << i << "]:" << testVal << std::endl;
++testVal;
}
};
void run_lambda(std::function<void()> fun){ fun();... |
73,900,598 | 73,901,691 | Why does -fPIC hinder inlining? | I have this foo.cpp:
int add(int a, int b) {
return a + b;
}
int add_wrapper(int a, int b) {
return add(a,b);
}
Compiling like so
g++ -c -S -fPIC -O4 -finline-functions foo.cpp -o foo.s
Gives the (demangled) assembly:
.globl add(int, int)
.type add(int, int), @function
add(int, int):
.LFB0:
.... | If you add the always_inline attribute to add, you can see the compiler error when it tries to inline:
warning: 'always_inline' function might not be inlinable [-Wattributes]
1 | [[gnu::always_inline]] int add(int a, int b) {
| ^~~
In function 'int add_wrapper(int, int)':
error: in... |
73,900,661 | 73,939,776 | Using swig Python wrapper: argument 2 of type 'std::unordered_set< std::string > const &' | I am updating an old project using (parent project of) the Python package coqui_stt_ctcdecoder generated from C++ using SWIG. Some parameter types in some methods have changed. I am stuck with the method Scorer::fill_dictionary that takes const std::unordered_set<std::string>& as an argument in C++. In the old Python ... | SWIG includes support for std::unordered_set, but note that the interface oddly doesn't accept Python set objects. tuple and list work, however.
Tested example:
test.i
%module test
// Code injected into wrapper
%{
#include <iostream>
#include <string>
#include <unordered_set>
// Function using the parameter type fro... |
73,900,921 | 73,901,576 | Queueuserworkitem vs TrySubmitThreadpoolCallback | Main Question:
What is the difference between QueueUserWorkItem and TrySubmitThreadpoolCallback given that they both queue a work item to the Thread Pool
TrySubmitThreadpoolCallback
This function adds a work item to the thread pool's queue (by calling
PostQueuedCompletionStatus) and returns TRUE if successful; it ret... | QueueUserWorkItem is from the legacy threadpool API. The newer function gives you more control over the environment in which the callback is executed by virtue of permitting you to initialize an environment for the callback (via InitializeThreadpoolEnvironment). In my experience, when MS starts calling something "legac... |
73,900,929 | 73,900,980 | iso c++ forbids variable length array, didn't understand other question with same topic | I've seen a question on this, but I am not really understanding it as I haven't learned pointers/memory in school, and this is an assignment for school. I'm trying to write a program that takes an integer value from the user, and prints out an upper right triangle with the same leg length. I'm using an array and then s... | A variable length array is an array whose size is determined at run-time.
According to the C++ language, array sizes (capacities) must be determined at compile time.
In your code, the capacities are determined at run-time, thus violating the size constraint of an array.
Please switch to using std::vector, whose capacit... |
73,900,959 | 73,901,171 | How to create an array of anonymous functions in C++? | C++ has 'lambdas' or anonymous functions. If they do not capture, they can be used in the place of function pointers. I could also declare an array of function pointers as follows:
double (*const Trig[])(double) = {sin, cos, tan};
cout << Trig[0](M_PI/2) << endl; // Prints 1
However I cannot figure out the correct syn... | The code is correct. The problem was due to the compiler defaulting to an older version of C++, before support for lambda expressions was added in C++11.
All I had to do was to tell the compiler to use C++11 (or newer):
g++ /Users/user/Lambda.cpp --std=c++11
|
73,901,480 | 73,918,135 | How to set the correct Intellisense configuration for include path in VS Code? | I am trying to work with Emscripten. I have the compiler set up and working and now I'd like to write some code.
However, the include for emscripten remains underlined in red and I can see this error:
#include <emscripten/emscripten.h>
#include errors detected. Please update your includePath. Squiggles are disabled for... | Ok, I found it, it's to the right bottom of the screen next to language type selection:
|
73,901,573 | 73,901,667 | How to have an #ifdef block only evaluate when VS Code intellisense is reading it? | I am working with emscripten, which uses some macros that VS Code IntelliSense does not like. This is not unusual. So what I'd like to do is this:
#ifdef INTELLISENSE_IS_READING_THIS
#define PROBLEMATIC_MACRO
#endif
That way, I can keep the macros as is but VS code will stop whining.
Sad thing is I remember solvin... | ! Found it. Just needed to craft a query that excludes all the questions about IntelliSense NOT reading or defining defines.
This is the way:
#ifdef __INTELLISENSE__
#define EMSCRIPTEN_KEEPALIVE
#endif
And this also works, but may also evaluate in Microsofts compiler:
#ifdef _MSC_VER
#define EMSCRIPTEN_KEEPALI... |
73,903,038 | 73,903,064 | C++ Bubble Sort Algorithm | I have the following code written in c++ and the algorithm works when in this scenario. I am knew to c++ and don't understand what I did wrong in my 2nd test.
#include <iostream>
using namespace std;
void bubbleSort(int numbers[], int size) {
for (int i = 0; i<size;i++) {
for (int j=0; j<size;j++) {
... | for (int j=0; j<size;j++) {
If size is 3, if the array has three values, for example, this loop iterates with values of j of 0, 1, and 2.
if (numbers[j] > numbers[j+1]) {
When j is 2 this compares numbers[2] with numbers[3].
There is no numbers[3]. This is undefined behavior. The loop is off by 1 value.
Additionally,... |
73,903,321 | 73,903,841 | Removal of an Object from a List during iteration | I am trying to make a list of projectile objects that are on screen which execute different methods. This has worked but I keep getting an error when I try to remove the object once it is off screen.
std::list<Bullet> bullets;
//bullets are added on mouse click
//start iterating through objects to move
std::list<Bulle... | Your code has multiple sources of undefined behavior:
erase() invalidates the iterator that is passed to it. You are dereferencing and incrementing that iterator after it has been invalidated. erase() returns a new iterator to the next item in the list, you need to continue your loop using that iterator.
you are manu... |
73,903,328 | 73,920,434 | How can I export a function in C++ using #pragma comment(linker, "/export:...) when the path contains a special character and spaces in it? | I'm trying to create an export by doing the following:
#pragma comment(linker, "/export:Breakpad_SetSteamID=C:\\Program Files (x86)\\Steam\\crashhandler64.dll.Breakpad_SetSteamID,@1")
But I get the error:
1>dllmain.obj : fatal error LNK1276: invalid directive 'Files' found; does not start with '/'
Because the path co... | I've found the solution:
#pragma comment(linker, "/export:Breakpad_SetSteamID=\"C:\\Program Files (x86)\\Steam\\crashhandler64.dll.Breakpad_SetSteamID\",@1")
|
73,903,928 | 73,903,943 | Variable 'maxHours' being used without being initialized | So I'm developing a program where I need to get information about what month the user has purchased for a subscription package cellphone plan. Based on the hours of the chosen month and the number of hours the user used within that given month I need to calculate their total costs.
My problem arises when I try to use t... | maxHours is initialized under the if and else if block. If neither of the condition is met, maxHours will stay un-initialized. That is the reason you are getting this error. If you try to print the value of a variable that is not initialized, then you will get a garbage value.
Better initialize it with int number
At th... |
73,904,747 | 73,904,894 | How to reuse CURL and set different doh url at every time in libcurl? | I set the hosts file on PC like this:
127.0.0.1 www.baidu.com
Then I wrote a simple test:
CURL *curl = curl_easy_init();
for (int i = 0; i < 3; ++i) {
if (curl) {
curl_easy_setopt(curl, CURLOPT_DNS_CACHE_TIMEOUT, 0L);
curl_easy_setopt(curl, CURLOPT_URL, "www.baidu.com");
if (i == 1)
... | curl easy uses the existing connection of the 2nd iteration on the 3rd iteration. See Name Resolving
libcurl tries hard to re-use an existing connection rather than to create a new one. The function that checks for an existing connection to use is based purely on the name and is performed before any name resolving is ... |
73,904,787 | 73,904,813 | Clang warning on delete pointers | I begin to use clang to replace gcc. But when I delete[] pointers, it gives warning. But when I change, the warning disappears. Why and how to deal with that?
int *a = new int[1];
int *b = new int[1];
delete[] a, b;
a.cpp:7:17: warning: expression result unused [-Wunused-value]
delete[] a, b;
int *a = new int[1];... | delete[] a, b;
is parsed as:
(delete[] a), (b);
Which you can really think of as:
delete[] a;
b;
In which case it is pretty clear that you're not doing much with b.
Where's the warning with GCC?
If you use -Wall, gcc will also warn on this since atleast 2007 (gcc 4.1.2):
<source>: In function 'int main()':
<source>:... |
73,905,902 | 73,907,632 | Initializing struct with json partial information | Supposing a struct A which has 7 member element:
struct A {
bool m_a;
std::string m_b, m_c;
float m_d, m_e;
double m_f;
time_t m_g;
A() = default;
A(
bool a, std::string b,
std::string c, float d,
float e, double f, time_t g
)
: m_a(a), m_b(b), m_c(c),
... | Here is a suggestion that is not particularly tuned to high performance (why do you need the efficiency?).
It is implemented by overloading from_json from the nlohmann::json library, see here.
Because C++ does not have introspection, you must implement a switch statement or several if blocks to map the json keys to you... |
73,906,018 | 73,906,103 | Why is the `operation on 'i' may be undefined`and how to fix this warning? | The operation on 'i' may be undefined appears at the second i++ in the line as follows:
int i = 4;
const uint16_t rawVoltage = (rxBuffer[i++]<<8) | rxBuffer[i++];
I believe it is related to the order of operations, but I guess the parenthesis has priority over the last increment.
Btw, the code works fine, as expected... | Parentheses affect parsing but not order of evaluation. You have two operations in your expression that modify i: i++ on the left-hand side and i++ on the right-hand side.
In general the order of evaluation is not specified in C++. For some operators certain sequencing rules apply, but in particular | does not enforce ... |
73,906,057 | 73,906,240 | Is it necessary to pay attention to non-error prompts? like no package ‘***’ found? | These prompts exist during the compilation of OPENCV, but no error is reported after the compilation. Generally, if there is no error prompt, I will not pay attention to the information, but I am also worried about it. So, I want to know whether it is necessary to solve these non-error prompts? Thank you.
Found OpenEXR... | If you're not familiar with how Configure style scripts work, you're probably quite overwhelmed by what's going on here.
These sorts of scripts look for a lot of different dependencies, some optional, some mandatory, and there might be more than one option for each dependency.
If something is missing that may or may no... |
73,906,062 | 73,906,689 | Why does my dynamic array in c++ crash after runtime? | I am trying to make a dynamic array that resizes continuously in runtime
In the following code the array should resize on any keypress
It works for around three key presses but then suddenly crashes. What is the issue
#include<iostream>
int main(int argc, char const *argv[])
{
std::string b;
int size=1;
in... | C++ is not obvious, unfortunately.
const int count = 3;
int* x = new int[count]; // is array of 3 items which values are trash.
int* y = new int(count); // is one variable of int equaling 3.
If there is array out of bounds, so it is Undefined Behavior in C++. The crash is one of the outcomes.
Examples:
x[ 0], x[1], ... |
73,906,372 | 73,906,633 | Internal Storage and SD Card sector Read/Write for MTP connected android device in C/C++ | I want to Read/Write sector (not in File System) from Android device internal storage and SD card.
The android device is connected via MTP.
Normally, we can use CreateFile/ReadFile/WriteFile API functions for Read/Write sector from DISK in Windows. Also, can use fopen/fread/fwrite functions in Linux.
But about the andr... | What you are asking for is not possible.
The whole point of MTP is to abstract away the mass storage aspect and even the file system. You are communicating over a protocol that is based on commands like "copy this file", "what folders are there", etc., and it's up to the device to interpret these commands. Some devices... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.