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,577,663 | 69,590,382 | Facing issue running Qt C++ on Visual Studio Code : no output on console, no gui showed | I'm trying to have a Qt C++ environnement on visual studio code with cmake.
Without Qt everything works perfectly but when I want to use an object Qt, I got no output on the console (with cout or qDebug()) and the GUI doesn't appear.
This is my code :
#include <iostream>
#include <QApplication>
#include <QMainWindow>
... | So I found my issue, I just forgot to add "C:\Qt\6.2.0\mingw81_64\bin" to my PATH environment variable.
|
69,577,830 | 69,577,987 | Is it UB to keep a pointer to a destroyed object and then use it to access re-created objects, possibly pointing to the first subobject? | Consider
struct full
{
struct basic
{
int a = 1;
} base;
int b = 2;
};
void example()
{
alignas(full) std::byte storage[/* plenty of storage */];
full * pf = new (storage) full;
basic * pb = &pf->base;
new (storage) basic; // supposedly ends lifetime of *pf (right?)
// if ... | The way it is written, your code has undefined behavior because both pf and pb stop pointing to an object as soon as it is destroyed (i.e. at the point of new (storage) basic;). In practical terms, the compiler is free to speculate the values that are accessible through these pointers across the new (storage) basic; ex... |
69,577,894 | 69,577,921 | C++ moving object on heap into local object in a well defined manner | Is it possible to move a moveable heap instance into a local object? I have the example code below:
#include <memory>
#include <type_traits>
#include <concepts>
#include <string>
template<std::move_constructible T>
struct LazyGuard
{
T value;
LazyGuard(T* const ptr) : value(std::move(*ptr)) { }
};
template <s... |
Can we guarantee the move constructor (or move assignment operator) will be called?
Yes
Heap vs stack only "means" anything as far as memory allocation/deallocation is concerned. Apart from that, they are effectively indistinguishable. An object is an object with all that this entails no matter where its memory is lo... |
69,578,543 | 69,595,555 | Map with multiple sorts and sets (like index into the map by not the [] kind) | I have a large map of records and I need to access subsets of the map in an order different from the keys (kind of like an index into a database). Say the map is lots of people and there is a list of all those people who are students (large subset). One of the fields is height in inches and the other weight in lbs. Giv... | After a break and coming back to it, I figured the "prev/next" thing was the bad part. I just need a studentHeightVector to go with the mini-map. Now, given "Greg" I know that's the first item in the vector and can find the next tallest by incrementing and the 2nd element is "Pete" which I can look up in the mainMap.
s... |
69,578,623 | 69,772,035 | pcap_set_rfmon succeeds but doesn't actually work | I'm currently trying to set up a simple packet sniffer with libpcap on Ubuntu 20.04.3 LTS and facing a lot of confusion over setting monitor mode with pcap_set_rfmon(). A trimmed version of my code and the compilation command I used is below:
g++ trimsniff.cc -g -o tsniff -L/usr/local/lib -lpcap
Code:
#include <iostre... | After looking around a bit, this is apparently a problem with Linux based systems. Libpcap needs to link with libnl to properly set monitor mode with pcap_set_rfmon(), and this doesn't happen, likely due to conflicting versions of the libnl library. This function works fine on my Mac for setting monitor mode, but in Ub... |
69,579,024 | 69,579,047 | How do I make a function execute a task when it ends? | I have a function that I wish to be called infinitely as long as conditions are met. However, I cannot simply call the function inside of itself, as that will cause a stack overflow. How do I end the function and start another one at the same time?
Example:
int myFunc() {
//do stuff
char again;
std::cout <<... | Well you haven't given any code example, so I'm probably out on a limb here, but I'm guessing you have something like this:
void my_func()
{
// do stuff
// ...
while (cond)
{
my_func();
}
}
There's two ways you can fix this:
1)
// this is wherever you call my_func
void some_other_func()
{
... |
69,579,085 | 69,579,140 | Difference between these 2 types of vector initialization | I tried to search online but didn't found any information.
Is vector adj[x] a type of 2d vector initialization?
vector <vector<int>> test(2);
vector <int> adj[2];
Their gdb details are also different.
(gdb) p test
$2 = std::vector of length 2, capacity 2 = {std::vector of length 0, capacity 0, std::vector of length 0,... | The first is a vector of vectors, where the 2 is the argument to the constructor.
The second is an c-style array of vectors, where [2] indicates the number of vectors in the array. There's no constructor argument given here.
|
69,579,159 | 69,584,400 | Can multiplying a pair of almost-one values ever yield a result of 1.0? | I have two floating point values, a and b. I can guarantee they are values in the domain (0, 1). Is there any circumstance where a * b could equal one? I intend to calculate 1/(1 - a * b), and wish to avoid a divide by zero.
My instinct is that it cannot, because the result should be equal or smaller to a or b. But... |
I have two floating point values, a and b…
Since this says we have “values,” not “variables,” it admits a possibility that 1 - a*b may evaluate to 1. When writing about software, people sometimes use names as placeholders for more complicated expressions. For example, one might have an expression a that is sin(x)/x a... |
69,579,648 | 69,579,731 | convert int to pointer int *ptr position; | i have 5 digits in 1 pointer
int* reversevec(int* ptr, unsigned int Ne){
int* ReverResult;
unsigned int rever=Ne, z;
ReverResult=(int*)malloc(Ne*sizeof(int));
for (int i = 0; i < Ne; ++i)
{
z=*(ptr+rever);
printf("%i ",z);//to be sure z starts from the last number on ptr to the fisrt
rever--;... | There are many problems here
z is a local variable int.
its address will not be useful to return, because it will be out of scope.
returning an offset from its address is even worse, since that is a totally unrelated place in memory.
you also have an off-by-one error. imagine Number elements is one. You will then try t... |
69,579,900 | 69,593,011 | Why can't GDB find some functions to disassemble by name? | Sometimes there is a function in my binary that I'm sure hasn't been optimized away, because it's called by another function:
(gdb) disassemble 'k3::(anonymous namespace)::BM_AwaitLongReadyChain(testing::benchmark::State&)'
Dump of assembler code for function k3::(anonymous namespace)::BM_AwaitLongReadyChain(testing::b... |
But if I ask GDB to disassemble it using the very same name that it refers to the function with, it claims the function doesn't exist
There are many possible mangling schemes; the relationship between mangled and unmangled names is not 1:1.
The parser built into GCC which turns foo::bar(int) into something which can... |
69,580,301 | 69,580,456 | Any way to call methods with array notation instead of parentheses? | In a large C++ project, I'm changing a struct to a class, but trying to minimise changes to any code that use the struct to make it easy to revert or reapply the change.
The struct is declared as follows:
struct tParsing {
char* elements[23];
};
And here's the current version of the class declaration (note I've sh... | Simply introducing an operator[] in tParsing will break existing code like parsingInstance->elements[0] – but what if the member provides this operator?
class tParsing
{
class Elements
{
public:
char*& operator[](size_t index);
char const* operator[](size_t index) const;
private:
... |
69,580,662 | 69,580,829 | When using variadric template, how to get nth arguments type? | I want to have a class that holds n values, much like std::tuple. I can't quite use tuple though, as there is additional logic in obtaining the values - they are on demand.
Please consider this class I wrote as an example:
// somewhere else
template<typename TVal>
TVal valueGetter() { ... };
template<typename ...TColV... | You can get the type from parameter pack with the help of a recursive inheriting type trait.
template<unsigned int TIndex, typename ...TColValue>
struct get_nth_from_variadric_type;
template<unsigned int TIndex, typename Head, typename... Tail >
struct get_nth_from_variadric_type<TIndex, Head, Tail...>
: get_nth_f... |
69,581,025 | 69,581,090 | How to combine header files and create a DLL | How are we supposed to create a DLL, included with header files?
For example, a project using the raylib game library requires raylib.dll to be present with the output file.
The raylib.dll is included with the header files of the raylib game library.
Is that how are supposed to create a DLL and include header files int... | There's only a limited relation between the header files and the creation of the DLL. In particular, you use the word "linked", and header files are not linked. Header files are included, libraries are linked. Including happens before a compile, linking afterwards.
Header files can provide declarations for functions de... |
69,581,271 | 69,670,543 | Fast Algorithm for Modular Multiplicatiion | I was trying to implement a large prime number generator, and the average time it takes to generate a 2048 bit length prime number is about 40s. I see from the analysis of call stack that the majority of the time (99%) was taken by modular multiplication, and performance changes very much changing this algorithm. I'm u... | You started out saying you want to generate prime numbers.
But you did not mention the connection between mod multiply and primes.
Knuth Volume 2 has lots of material on bignum arithmetic and finding large prime numbers.
A comment mentions Montgomery modular arithmetic.
Here is a link https://en.wikipedia.org/wiki/Mont... |
69,581,486 | 69,581,543 | Templated is_in() function (check if array contains string) in C++ | I would like to do the following:
std::string b = "b";
is_in("a", { "a", "b", "c" });
is_in("d", { "a", "b", "c" });
is_in(b, { "a", "b", "c" }); // fails
is_in(b, std::array{ "a", "b", "c" });
using the templates
template<typename Element, typename Container>
bool is_in(const Element& e, const Container& c)
{
// ... | For is_in(b, { "a", "b", "c" });, template parameter Element is deduced as std::string on the 1st argument b, and deduced as const char* on the 2nd argument { "a", "b", "c" }; they don't match.
You can give two template parameters for is_in, e.g.
template<typename E1, typename E2>
bool is_in(E1 e, std::initializer_list... |
69,582,117 | 69,582,344 | Calculating difference between two date-times in C++ | Problem Summary
I have two strings in the form YYYY-MM-DD:hh:mm:ss and I would like to calculate the time difference between them. For example, the difference between 2021-10-01:03:44:34 and 2021-10-01:03:44:54, should be 20 seconds. However, the result I get is 0.
Code
I have tried the following:
#include <iomanip>
#i... | You use the conversion specifier%b to get the month but it should be %m:
ssBuffer >> get_time(&tm, "%Y-%m-%d:%H:%M:%S");
%b - parses the month name, either full or abbreviated, e.g. Oct (non-numeric)
%m - parses the month as a decimal number (range [01,12]), leading zeroes permitted but not required
The year and mon... |
69,582,502 | 69,585,590 | std::unique_ptr::reset and object-specific deleters | Imagine a Deleter that has to stay with its object, as it is somewhat specific to its object. In my case, this is because the deleter uses an allocator library that needs to know the object size when deallocating the memory. Because of inheritance, I cannot simply use sizeof(T) but instead need to store the size of the... | The unique_ptr has a member type pointerwhich is equal to std::remove_reference<Deleter>::type::pointer if that type exists, otherwise T*. Must satisfy NullablePointer.
So you may try to add a pointer type to your deleter like this:
template<typename T>
struct MyDeleter {
struct pointer{
using type = T;
... |
69,582,950 | 70,447,122 | __func__ returns class name in debug but not in release | I'm working with 12 year old legacy software written in Embarcadero C++ and I noticed:
when you use __func__ or __FUNC__ in debug or release configuration for 32bit, it returns ClassName::FunctionName but when built in debug or release configuration for 64bit, it returns only FunctionName.
Is that expected behaviour an... | You can use __PRETTY_FUNCTION__ to get the full function signature. This macro is not listed in Embarcadero documentation, so it might not work with the Classic compiler.
Output in C++ Builder 10.3.3 is like:
int ClassName::FunctionName(int, int)
If you need to remove the return value and arguments, just parse the str... |
69,583,444 | 69,583,525 | "Vector erase iterator outside range" when trying to erase a previously saved iterator | In my project I am trying to create a vector and saving an iterator pointing to some element of the vector that I may want to remove later. In the meantime new elements will be added to the vector and after adding some elements I want to delete the iterator that I had saved from the vector.
This is what I tried to do:
... | Yes since your code invokes undefined behavior.
Adding items to vector invalidates all iterator and use of invalidated iterator leads to undefined behavior.
Reason is that there is some reserved memory for items of vector. When this memory is not enough to hold new item, new fragment of memory is allocated and content ... |
69,583,793 | 69,654,000 | Deribit FIX API Logon | Following code doesn't seem to work to Logon using FIX API. Getting "invalid credentials" from the exchange though same username and access key seem to work with REST API over websockets.
Seems like issue with the definition of nonce. Here I am trying a basic example to try to Logon.
string user = settings->get... | I was able to solve this problem and I am providing it's solution so others can also benefit.
Method used for base64 encoding:
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
std::string base64_encode(unsigned char... |
69,583,868 | 69,584,130 | Initialize struct with (shadowed) base-class data members in C++11 | It's possible to add members to a derived struct that shadow same-name members of the base class, whether this is an error or not is addressed by another Q&A. My question is about initializing hidden inherited members. By-value assignment of derived D to base class B is permitted by the is-a relationship, but it's hard... | D der = {1, 2} would work in C++17, as
D der = {{42}, 2};
Demo
For previous version, you cannot initialize base like that and you need a constructor.
|
69,584,270 | 69,586,209 | What is the difference between a name and a variable in C++ | According to C++ ISO Draft (2020) 6.1 (Basics) :
A name is a use of an identifier (5.10), operator-function-id (12.6),
literal-operator-id (12.6.8), conversion-function-id (11.4.7.2), or
template-id (13.3) that denotes an entity or label (8.7.5, 8.2).
Every name that denotes an entity is introduced by a declaration.... |
What is the difference between a name and a variable?
The most obvious (based upon your first quote) difference is that a name is more general than a variable. Every variable has a name, but not every name is of a variable. There are also names of functions, classes, operators, and templates. (This is not intended to... |
69,584,565 | 69,584,733 | Make a reduction with OpenMP to compute the final summed value of an element of matrix | I have the following double loop where I compute the element of matrix Fisher_M[FX][FY].
I tried to optimize it by putting an OMP pragma #pragma omp parallel for schedule(dynamic, num_threads), but the gain is not as good as expected.
Is there a way to do a reduction with OpenMP (of sum) to compute the element Fisher_M... | Your code has a race condition at line Fisher_M[FX][FY] += .... Reduction can be used to solve it:
double sum=0; //change the type as needed
#pragma omp parallel for reduction(+:sum)
for(int i=0; i<CO_CL_WL.size(); i++){
for(int j=0; j<CO_CL_WL.size(); j++){
if( CO_CL_WL[i][j] != 0 || CO_CL_WL_D[i][j] != ... |
69,584,657 | 69,584,722 | How can I access child class version of functions in the parent class from the child class if the objects are in a vector? | So I have a ParentClass and a ChildClass. I have a vector objects. I pushed back two items in it, a ParentClass newparent object and a ChildClass newchild object. I have a for-each loop and I want to access the child version function of the parent function from within this for-each loop but I cant. Please help.
here is... | If you have a vector of ParentCLass objects, that will hold ParentClass objects. When you add a ChildClass, C++ will need to apply a conversion - push_back takes ParentCLass const&. The conversion found is the standard child to parent conversion; so the parent part is copied.
This is called "slicing". You can create a ... |
69,585,074 | 69,585,726 | When is it worth it to change from std::vector to std::unordered_set? | I want to make a container with few elements and I will be just checking whether an element is part of that set or not.
I know a vector would not be the appropriate container if the set is big enough since each research would be worst-case O(n) and there are better options that use a hash function or binary trees.
Howe... | There are many factors affecting the point where the std::vector falls behind other approaches. See std::vector faster than std::unordered_set? and Performance of vector sort/unique/erase vs. copy to unordered_set for some of the reasons why this is the case. As a consequence, any calculation of this point would have t... |
69,585,223 | 69,623,007 | "Merge" PODs into one | Is there a way to compose (or merge, aggregate) PODs between them ? One intuitive solution:
struct Base1 { int i; };
struct Base2 { char c; };
struct Derived : Base1, Base2 {};
// in a more generalized way
// template <class... Ts> struct Aggregate : Ts... {};
Except, we lose something:
int main()
{
Derived d {4... | If we
don't care if the derived struct is a POD or not
, the task is pretty simple with Boost.PFR - just convert your PODs to tuples and concatenate them:
template<typename... Ts> using Merge = decltype(std::tuple_cat(
boost::pfr::structure_to_tuple(std::declval<Ts>())...
));
A simple test:
int main() {
stru... |
69,585,272 | 69,586,781 | C++ Signal is not received in QML slot | I have a C++ class that emits a signal. I want that signal to be delivered to QML.
I set the object as a context property of qml application engine root context.
My C++ class
// Sample.h
class Sample : public QObject
{
Q_OBJECT
public:
explicit Sample(QObject *parent = nullptr);
public slots:
void emitSome... | I didn't have version 5.9, but I tried it with 5.10.1. In that case, the text did not get printed to the console. I fixed it by changing the syntax on the signal handler. (Just remove function().)
Connections {
target: obj
onEmitted: {
console.log("received")
}
}
|
69,585,297 | 69,587,497 | Avoiding implicit conversion with concepts | Since templates and dynamic polymorphism don't mix well, I am currently designing a concept, instead of an interface (implemented with abstract class), for a Loggable type, which supports operations:
logger.log(LogLevel::info) << "some message" << 0 << 0.0 << 'c';
Provided the log levels defined:
enum class LogLevel
{... | To avoid implicit conversion, we can define a template operator<< that matches all other types.
In addition, in order to avoid blocking string literal, we can add a constraint for this operator<< to ensure that the operand cannot be converted to std::string:
#include <string>
template<typename T>
concept WeaklyLoggabl... |
69,586,634 | 69,586,871 | "Derived pointer to member" to "base pointer to member" error | To support some compile time magic I would like to use pointers to members like:
struct BaseT
{
};
struct DerivedT: public BaseT
{
};
struct TestT
{
DerivedT testMem;
typedef BaseT (TestT::* TestTMemPtr);
constexpr TestT() = default;
static constexpr TestTMemPtr testMemOffset()
{
retur... | From the point of view of inheritance, BaseT TestT::* and DerivedT TestT::* are two unrelated types¹, so you can't initialize the former from the latter nor vice versa, just like you can't initialize a int* with a double* because int and double are not based and derived classes.
¹ By that I mean that two objects of th... |
69,586,913 | 70,063,625 | How can I transform rotation to FVector in Unreal Engine 5? | How can I transform MainComponent->GetComponentRotation() to FVector?
Do I have to use AddForce() for child components?
I need to get its rotation vector. How do I get it correctly?
| You should be able to use either
MainComponent->GetComponentRotation().Vector();
or
MainComponent->GetComponentForwardVector();
See documentation - GetComponentRotation() and GetComponentForwardVector() for more details.
|
69,587,369 | 69,587,489 | Binary search in array is not working properly | // function for binary search in array
#include <iostream>
using namespace std;
int binSrch(int arr[], int n, int key)
{
int s = 0, e = n; // s for starting and e for ending
int mid = (s + e) / 2;
while (s <= e)
{
if (arr[mid] == key)
return mid;
else if (arr[mid] > key)
... | Assuming that you are passing n as the size of the array, you should give e = n-1 since arrays are 0-indexed based, that is where you are probably getting the wrong answer.
And you also should calculate mid after each iteration, so it should be inside the while loop.
Also, you should do mid = s +(e-s)/2 to avoid overfl... |
69,587,792 | 69,588,359 | OpenMP performance optmization with a large array (matrix) | I am fairly new to OpenMP, sorry if the question seemes reduantant.
Here is my sequential code that executes do_something() to every element in the row and save to the next row:
for (int i = column; i < row * column; i++)
A[n] = do_something(A[n - column]);
I tried to parallize it with simple parallel for
... | The loop over j is problematic. Starting thread team and synchronization at the end of parallel section is quite costly, especially for a large number of threads.
Moving loop outside breaks locality of reference. The classic solution to this problem is tiling. Split the problematic loop into two. One with step of cache... |
69,588,007 | 69,588,245 | portability of the sys/siginfo.h which approach to use | I am porting old code from Solaris to Linux. in one file I have the include:
#include <sys/siginfo.h>
that of course I can't find it anymore in Linux.
So I tried to include the new one in:
#include <asm/siginfo.h>
but I had a lot of problem trying to compile it (of course) and had errors like:
/usr/include/asm-gener... | Definitely #include <signal.h>. If you look into linux/siginfo.h it warns you not to include the file directly, but to use signal.h instead. It is the public API for POSIX signals.
The manpage shows that on the x86/ARM/most others, SIGLOST is not used. You may be hitting a part of your port that will take more effor... |
69,588,446 | 69,588,542 | How would I fix this to not be an array of reference? | Preface: Yes I am aware of the inconsistency in function definitions, I am in the process of trying to write the thing.
Specifically in line
void renderScreen(char& currentMap[100][100], int& screenX, int& screenY)
The char& currentMap[100][100] creates an array of references. How would I call a separate char variable... | I do not see any sense in the second and third parameter declarations declared as references
void renderScreen(char& currentMap[100][100], int& screenX, int& screenY);
because within the function the original objects used as arguments are not changed within the function. So the function could be declared at least like... |
69,588,461 | 69,588,484 | How to forward a mutable lambda | Here's a watered down example of the code I'm try to compile:
#include <iostream>
#include <functional>
template <class F>
auto foo(F&& fun)
{
return [callback = std::forward<F>(fun)](auto&&... args) {
std::invoke(callback, std::forward<decltype(args)>(args)...);
};
}
int main()
{
std::string cur(... | Just add mutable to the lambda inside the foo:
template <class F>
auto foo(F&& fun)
{
return [callback = std::forward<F>(fun)](auto&&... args) mutable {
//^^^
std::invoke(callback, std::forward<decltype(args)>(args)...);
};
}
|
69,588,813 | 69,606,209 | How can I start a download from c++ code compiled web assembly? | I've been trying to not do this javascript side and I haven't found anything satisfying yet.
Fetch API seems to be a good lead, but I can't seem to find a way to start the download in the browser so it can download a zip file.
This is emscripten code snippet, but it seems to be a local file of some sort.
#include <stdi... | Add this to your cpp file.
EM_JS(void, DownloadUrl, (const char* str),
{
url = UTF8ToString(str);
var hiddenIFrameID = 'hiddenDownloader';
var iframe = document.getElementById(hiddenIFrameID);
if (iframe === null)
{
iframe = document.createElement('iframe');
iframe.id = hiddenIFrame... |
69,588,829 | 69,589,341 | In OpenMP how can we run in parallel multiple code blocks where each block contains omp single and omp for loops? | In C++ Openmp how could someone run in parallel multiple code blocks where each block contains omp single and omp for loops?
More precisely, I have 3 functions:
block1();
block2();
block3();
I want each of these 3 functions to run in parallel. However I do not want each one of these functions to be assigned a single t... | The best solution is using tasks. Run each block() in different tasks, so they run parallel:
#pragma omp parallel
#pragma omp single nowait
{
#pragma omp task
block1();
#pragma omp task
block2();
#pragma omp task
block3();
}
In block() you can set some code, which is executed before the for loop and you ca... |
69,589,101 | 69,599,007 | How to create multithread logger in c++ | I want to create a multithread logger in c++ which can be called from c code as well.
This is in my source.cpp file:
#include <cstdlib>
#include <iostream>
#include <thread>
#include "source.h"
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
class thread_obj {
public:
void operator()(float* x)
{
... | There are multiple problems with your code:
argument for operator() should be float x NOT float* since this is what you are passing to thread
your log function conflicts with standard math log. Either change function name or put it into different namespace
printf using format specifier "%d". It should be "%f" since in... |
69,589,509 | 69,608,998 | ways for Direct2D and Direct3D Interoperability | I want make a Direct2D GUI that will run on a DLL and will render with the Direct3D of the application that I inject into it.
I know that I can simply use ID2D1Factory::CreateDxgiSurfaceRenderTarget to make a DXGI surface and use it as d2d render target, but this require enabling the flag D3D11_CREATE_DEVICE_BGRA_SUPPO... | The #3 is the correct one. Here’s a few tips.
Don’t use keyed mutexes. Don’t use NT handles. The only flag you need is D3D11_RESOURCE_MISC_SHARED.
To properly synchronize access to the shared texture across devices, use queries. Specifically, you need a query of type D3D11_QUERY_EVENT. The workflow should look like fol... |
69,589,561 | 69,589,762 | C++20 requires expression does not catch static_assert | I was really excited when I first heard about C++20 constraints and concepts, and so far I've been having a lot of fun testing them out. Recently, I wanted to see if it's possible to use C++20 concepts to test the constraints of classes or functions. For example:
template <int N>
requires (N > 0)
class MyArray { ... };... | Yes, nothing in the content of the stuff you interact with is checked. Just the immediate context of the declaration.
In some cases with decltype the non immediate context of some constructs is checked, but any errors remain hard.
This was done (way back) to reduce the requirements on compilers. Only in what is known... |
69,589,647 | 69,595,203 | How to measure high-resolution keypress time in C++? | I have a Millikey Response Box with a 1 000 Hz sampling rate and a light sensor with a 10 000 Hz sampling rate. I would like to measure end-to-end response time from the moment of a button press to a change on the screen triggered by the button press in my C++ program. I'm struggling to understand how to do it.
My idea... | The answer for me was to use LabStreamingLayer. I use App-Input to capture keyboard events, LabRecorder to capture the stream of these events, and then Python importer to parse the resulting XDF file. All the above runs and captures events in the background while the keypress triggers the screen change in my C++ progra... |
69,589,677 | 69,589,832 | Replace Substring of digits by Sum | I have a string that's in the form similar to:
"1111P1P"
I'm trying to replace all sub strings of ones by the total:
i.e. "4P1P"
The string will always contain 1's and no other numbers before replacement.
My initial idea was to split the string using regex and store it in a vector and i could manipulate it. But this re... | A single loop will allow you to complete this with O(n) runtime:
std::string str = "1111P1P";
std::string final;
int running_total = 0;
for(auto ch : str) {
if(ch == '1') {
running_total++;
continue;
}
if(running_total > 0) { final += std::to_string(running_total); }
final += ch;
... |
69,590,069 | 69,592,355 | parsing input in c++ for competitive programming | How to parse input like for example:
[[1,3,5,7],[10,11,16,20],[23,30,34,60]]
for 2d vector of m x n size. I have tried
char x;
vector<int> v;
vector<vector<int>> v_v;
vector<int> temp;
int br_op_cl = 0;
int row = 0;
while (cin >> x) {
// cout << x << endl;
if (x == '[' || x == '{') {
// cout << "ins... | Consider [1,3,5,7] to be a single row. Use stringstream to read this row. Then use another stringstream to read the content of this row.
getline will read each row until it hits ], another getline will read each column until it hits ].
Replace occurrences of { with [, to make parsing easier.
#include <iostream>
#inclu... |
69,590,113 | 69,598,332 | How to set up IK Trajectory Optimization in Drake Toolbox? | I have read multiple resources that say the InverseKinematics class of Drake toolbox is able to solve IK in two fashions: Single-shot IK and IK trajectory optimization using cubic polynomial trajectories. (Link1 Section 4.1, Link2 Section II.B and II.C)
I have already implemented the single-shot IK for a single instan... | The IK cubic-polynomial is in an outdated version of Drake. You can check out https://github.com/RobotLocomotion/drake/releases/tag/last_sha_with_original_matlab. In the folder drake/matlab/systems/plants@RigidBodyManipulator/inverseKinTraj.m
|
69,591,298 | 69,731,301 | Pybind 11: How to bind C++ function that has pointer arguments? | Let's suppose I am given a function that looks like this
void myFunc(int *a){
a[0]++;
a[1]++;
}
I tried to bind this function with the below
#include "pybind11/numpy.h"
#include "pybind11/pybind11.h"
namespace py = pybind11;
PYBIND11_MODULE(pybindtest, m) {
m.def("myFunc", [](py::array_t<int> buffer){
py::... | Try this in your python script
import numpy as np
import pybindtest
a=np.array([1,2], dtype=np.int32);
pybindtest.myFunc(a);
print(a)
The problem is that a is a python list, not an array of ints. By default pybind11 will convert the list into a suitable array - see the section about py::array::forcecast in the docs... |
69,591,371 | 69,596,535 | reinterpreting array of doubles as array of std::complex<double> | While C++11 standard says this about reinterpreting std::complex<double> as doubles:
For any pointer to an element of an array of complex<T> named p and
any valid array index i, reinterpret_cast<T*>(p)[2*i] is the real part
of the complex number p[i], and reinterpret_cast<T*>(p)[2*i + 1] is
the imaginary part of the c... |
Is it true for the backward reinterpreting? I mean is it safe to perform something like this: std::complex<double> *cppComplexArray = reinterpret_cast<std::complex<double> *>(cDoublesArray)
Casting/initialization itself is safe, using the result as-if pointing to an element of an array of std::complex<double> is not.... |
69,591,445 | 69,591,518 | How to specialize a templated class at the class level | Recently I was asked a question. I have the below templated class:
template<size_t SIZE>
class Cache
{
// A lot of class methods omitted
std::array<int, SIZE> _arr;
};
but someone might pass large a size and allocate on the stack, running out of stack memory. So you might suggest changing it to allocate on th... |
How is this class template specialization achieved without duplicating all the (omitted) class methods?
Abstract the thing you care about away into its own mixin class. For example:
template<size_t SIZE, bool> // default case, condition is false
class storage {
std::unique_ptr<std::array<int, SIZE>> _arr;
protect... |
69,591,725 | 69,591,822 | C++ random number generator for different opportunities | Help with this C++ code
C++I want to generate a random number for each opportunity. How can I do this? because if it is inside the "do" in the other "if" it is not definded.
#include<cstdlib>
#include<ctime>
#include<iostream>
using namespace std;
int main()
{
int guess = 20;
int opportunity=1;
srand((unsigned)time(0... | When srand() is seeded with time(NULL) it will generate a random number based on the time of the clock of the computer. So, if you initialize the variable randowm_integer with rand() the function is only called once. but, if you place the random_integer = (rand() % 30) + 1; inside of the do-while loop, it will be calle... |
69,592,181 | 69,592,218 | Recursive method counting | How does this recursive integer method count the number of nodes in a linked list? How can a constant 1 be added to a memory address?
int length(Node *head) {
if(head == nullptr)
return 0;
return 1 + length(head->link);
}
| Note that length(head->link) is a function call. The function being called, length, returns an int. So 1 is not being added to a pointer; it is being added to an integer.
|
69,592,239 | 69,592,302 | std::variant duplicate type cause no suitable constructor error(clang-1300.0.29.3) | Just wondering if this is the expected behaviour of std::variant, as well as the reasoning for this behaviour.
Simplified code to reproduce the error is as below:
double d= 1.0;
std::variant<std::monostate, double, double> v(d);
The error message is shown as below:
no suitable constructor exists to convert from "doubl... | Having multiple identical types in a std::variant is allowed. However, when the constructor of std::variant is invoked, overload resolution is performed to figure out which of the variant types it needs to hold. If you have 2 identical types, there's an ambiguity, and so you get an error.
You can specify which of the t... |
69,592,361 | 69,593,344 | Is there a way to prevent the contents of my window from "moving" when i resize the window in OpenGL | I would like my window contents to stay centered when my window resizes. OpenGL (or GLFW) - I'm not sure which - does give this desired effect when resizing horizontally, however when i resize the window vertically the window appears to show the more of the bottom of the cube. I expected it to cut off the cube like whe... |
Note: I do not make any glViewPort() otherwise the window contents would adjust to the new width and height.
This is the problem. You need to adjust the viewport. Adjust the field of view depending on the viewport:
const float defaultHeight = 600.0f;
const float defaultFov = glm::radians(45.0f);
while (!glfwWindowSh... |
69,592,529 | 69,593,602 | Iteration through linked list recursively | In this piece of code
Node* insert(int num, Node *head) {
if (head == NULL|| num <= head->next)
return addNewNode(num, head);
head->next = insert(num, head->next);
return head;
}
Why is it
head->next = insert(num,head->next);
and not
head = insert(num,head->next);
I understand we have to traverse throu... | When you don't insert the element as the first node, you want to keep the head and insert into the list's tail.
head->next = insert(num, head->next); replaces the tail with the modified one.
head = insert(num, head->next); would ignore the head and replace it with the result of inserting an element in its tail.
Example... |
69,592,838 | 69,592,874 | #define process in C++ | I am trying C++, There is a point about can not understanding about #define addition. The example code below.
#include <iostream>
using namespace std;
#define A 0
#define B A+1
#define C 3-B
int main(){
cout << A << endl;
cout << B << endl;
cout << C;
return 0;
}
The result gives A -> 0, B -> 1, ... | Do the text substitution. B expands to 0+1. C expands to 3-0+1 rather than 3-1.
cout << C;
Becomes:
cout << 3-0+1;
Because of order of operations this displays 4 rather than 2.
An easy way to see this would be to try something like:
cout << C * 50;
If we operate under the faulty assumption that C is actually 4, we'd... |
69,592,983 | 69,593,029 | One header file in multipe cpp files: Multiple definition | I am trying to access one header file in multiple C++ files. The header file is defined as follows:
#ifndef UTILS
#define UTILS
void toUpper(string &str) {
for(unsigned int i=0; i<str.length(); i++) {
str.at(i) = toupper(str.at(i));
}
}
void toLower(string &str) {
for(unsigned int i=0; i<str.l... | There are 2 solutions to this problem.
Solution 1
You can add the keyword inline infront of the function like:
myfile.h
#ifndef UTILS
#define UTILS
inline void toUpper(string &str) {
for(unsigned int i=0; i<str.length(); i++) {
str.at(i) = toupper(str.at(i));
}
}
inline void toLower(string &str) {... |
69,593,422 | 69,593,471 | getting the minimum for arrays and for statments? | I sorta need help getting the minimum I keep getting thirteen can some
one help me out? The issue I believe is I'm not showing the formula for low n line I'm confused I have tried to switch out the values for the array and I can't figure it out just if someone could explain to m please.
#include <iostream>
using name... | This is the corrected example:
int getLowest(int numArray[], int numElements)
{
int low = numArray[0];
for (int sub = 1; sub < numElements; ++sub)
{
//std::cout<<"checking: "<<numArray[sub]<<"with"<<low<<std::endl;
if (numArray[sub]< low){
low = numArray[sub];
}
... |
69,593,587 | 69,593,768 | Understanding pointer to member of class of type - no polymorphism | I thought it is straightforward that a 'pointer to member of class T of type DerivedT' can be used as a 'pointer to member of class T of type BaseT' if BaseT is base of DerivedT. The analogy seems to be obvious at least to me as DerivedT* can be used as a BaseT*, so DerivedT T::* should be able to be used as BaseT T::*... | A pointer-to-data-member is normally represented by a simple integer value, telling the offset of the beginning of the owner class to the beginning of the member. So the algorithm of retrieving a data member given a pointer to its owner is as simple as "add the offset to the address and dereference".
However, in order ... |
69,594,346 | 69,594,363 | when inputting a array the length of array replacing the first element in the array in c++ | When inputting a array in c++ the element in 0th position will become the length of the array.
have two functions to input and print the array when print function calls the output array has always the array length in 0th position.
#include<iostream>
using namespace std;
int getArray(int array[])
{
int len;
cout << ... | In C++, the size of an array must be a compile time constant. So you cannot write code like:
int n = 10;
int arr[n]; //incorrect
Correct way to write this would be:
const int n = 10;
int arr[n]; //correct
For the same reason the following code (last statement) is incorrect :
int k;
cin >> k;
int arr[k]; //incor... |
69,594,451 | 69,594,858 | (Why not) initialize struct val at definition | I know this kind of initialisation is discouraged but I can't remember why, while it's working, so does anyone knows why this should be avoided :
typedef struct struct_test {
int a = 1;
int b = 2;
int c = 3;
} t_test;
thanks
| It's illegal in C.
In C++ it's not discouraged. Unlike initializing in the constructor, it doesn't require you to list all fields the second time (see DRY), making it harder to forget to initialize fields.
|
69,594,453 | 69,595,051 | Why inherited member function from base template class not declared? | I'm testing the following code:
#include <iostream>
template<typename T>
class A {
public:
void koo(T) { std::cout << "Hello world!"; }
};
template <typename T>
class B : public A<T> {
public:
void pun(T i) { koo(i); }
};
int main() {
B<int> boo;
boo.pun(5);
}
with compilation info as:
main.cpp:12:2... | ADL is argument dependent lookup. A function name is looked for in the associated namespaces of its arguments. int has no associated namespaces, so no ADL occurs. Even if it did occur, it would only find free functions, so your method would not be found.
|
69,594,500 | 69,594,571 | How to perfectly combine C++ exception handlers with C libraries? | I try to use libcurl in a C++ program:
size_t getContainersCallback(const char *buff, size_t size, size_t buff_size, void *data) {
char newBuff[buff_size + 1];
memset(newBuff, 0, buff_size + 1);
memcpy(newBuff, buff, buff_size);
static_cast<string *>(data)->append(newBuff);
return size * buff_size;
... | try {
json j = json::parse(responseBody.c_str())
} catch (exception &e) {
curl_easy_cleanup(curl);
}
curl_easy_cleanup(curl);
I don't think you need curl_easy_cleanup inside the catch, since you're recovering from the exception, then the function will be called twice.
This is not a specific issue with C, ifc... |
69,594,623 | 69,595,785 | Can't filter out string vector in writing txt file in C++ | I want to read a text file that contains both text and number, and after reading it, write some data from that file into a new text file that contains the last 3 numbers of each row only. If there is a text of "120, Hello, Hi", I want to skip it and write only the last 3 numbers after "Hi", and enter a new line after w... | The issue here is that you're checking that VecData[i] is not "120", or it's not "Hello", or it's not "Hi". This will always be true.
Think about the case where VecData[i] is "Hi":
if ((VecData[i] != "120") || // (1)
(VecData[i] != "Hello") ||
(VecData[i] != "Hi"))
The comparison at (1) has evaluated to Tr... |
69,594,648 | 69,594,774 | How i can find the length of array pointer? | This is the function from where I am returning the array pointer.
#include<bits/stdc++.h>
using namespace std;
int *mergeArray(int a[], int b[], int as, int bs){
int* temp=new int[as+bs];
int i{0}, j{0}, k{0};
while(i<as&&j<bs){
if(a[i]<b[j]) temp[k++]=a[i++];
else temp[k++]=b[j++];
}
... | If working with naked pointers, then you'll have to explicitly pass around the size of the objects they're pointing to.
However since you're using C++, the actual answer to your problem is to use std::vector instead of naked pointer array. Using std::vector your original code turns into
#include <vector>
#include <iost... |
69,595,104 | 69,595,192 | How to run it on another Qt thread? | With Qthread in mind I tried the following but it seems everything is still running in the same thread.
main.cpp
#include "widget.h"
#include <QApplication>
#include "core.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qDebug() << Q_FUNC_INFO << QThread::currentThreadId();
Core core;... | You cannot call the slot compute() directly, it will call it in the same thread as runs the code which called it (as you can see in the output).
You need to run the slot via signals/slots mechanism (or with invokeMethod(), but let's ignore this one).
Typically this is done by connecting thread's started() signal to the... |
69,595,378 | 69,595,421 | Strict Weak Ordering of "i" and "Love" | Assumption:: a < b returns true when a precedes b.
Code
std::string a = "i";
std::string b = "Love";
std::cout << "(a < b) = " << ((a < b) ? "true" : "false");
Output
(a < b) = false
We know "i" preceedes "Love" so why is the above code return false?
Is my initial assumption wrong?
Help is appreciated thanks.
| Lowercase “l” has a higher character code than uppercase “L” in the character encoding your C++ implementation uses. Most C++ implementations currently use ASCII for the characters A-Z and a-z. In ASCII, the code for “L” is 76, and the code for “i” is 105.
To see the codes your C++ implementation uses for characters, y... |
69,595,429 | 69,595,596 | Multiple definition linking c++ project build with cmake | First of all, Im sorry if this ends in a noob question, but Im getting a grasp with CMake and I cant find the problem here. Its a multiple definition error, but as long as I know I have:
Included correctly my headers (posted below).
Declared and not defined in the headers the variables that gives the errors.
In CMakeL... | You have declared b and _patata in test.h. Since both test.cpp and main.cpp include test.h, then both test.cpp and main.cpp translation units have a global variable named b and _patata. Now there are two of each. There can only be one of each. The solution is to move int b; and patata _patata; into test.cpp since there... |
69,595,527 | 69,637,417 | Why does C++ need std::make_unique over forwarded unique_ptr constructor? | I don't ask about new operator like here. Please, read question carefully.
I want to know why we need special function make_unique over special constructor
of unique_ptr.
unique_ptr could use constructor like this to make make_unique unneccessary:
template<typename T, typename ...TArgs>
unique_ptr::unique_ptr(TArgs&&..... | I want to summarize discussion with Some programmer dude, StoryTeller - Unslander Monica and Raymond Chen
So, there are 2 reasons:
std::make_unique pairs well with std::make_shared which was introduced earlier so this was easier to learn than new constructor for unique_ptr.
There is possible ambiguity between construc... |
69,595,564 | 69,595,746 | Polymorphism : raw pointer vs smart pointer | how makes this work ?
I want to use a vector of multiple types (research, add, delete) for an inventory management (Potions, Weapons, etc.. all derived from virtual class Item).
I simplify the problem here :
I have a vector containing Item (Base class) and Weapons (Derived class).
For memory management issues, i prefer... | A unique pointer is exactly that: unique. There is only supposed to be one unique pointer to each object. As soon as you try to return the unique pointer, there would have to be 2: one in your vector elements and one returned from your function. There are ways around this I think, like returning a reference to the poin... |
69,596,108 | 69,596,901 | Keeping consteval-ness of function arguments | I am using the neat fmt library, which in its version 8, does compile-time checking of its format string if the compiler supports the relevant features.
I would, at some point, like to write the following code:
throw my_exception("error: {}", 123);
Sadly, the naive implementation:
struct my_exception : std::runtime_er... | In {fmt} 8.0 and later you can do this by using the format_string template that, as the name suggests, represents a format string (https://godbolt.org/z/bqvvMMnjG):
struct my_exception : std::runtime_error {
template <typename... T>
my_exception(fmt::format_string<T...> fmt, T&&... args)
: std::runtime_error(fm... |
69,596,694 | 69,596,823 | Why are we using pointer to pointer for one and a normal pointer to another? | // A complete working C++ program to demonstrate
// all insertion methods on Linked List
#include <bits/stdc++.h>
using namespace std;
// A linked list node
class Node
{
public:
int data;
Node *next;
};
/* Given a reference (pointer to pointer)
to the head of a list and an int, inserts
a new node on the f... | The functions push and append both need to be able to change the pointer to the head node.
If they were only passed a Node* pointing to the head, then they would only be able to change their local copy of that pointer to the head node. However, they need to be able to change the original pointer to the head node, which... |
69,596,874 | 69,597,891 | Why `it1++` works, but `it1=it1+1` does not, where it1 is iterator of list container | Given a std::list iterator called it, it1++ is equivalent to it1=it1+1. So why then does it1++ work fine, but it1=it1+1 is giving an error in the below code?
Code
#include <iostream>
#include <list>
int main()
{
std::list<int> l1{19, 2, 3, 21, 5, 19, 7, 11};
std::list<int>::iterator it1;
std::cout << "1st... | Re: "it1++ is equivalent to it1=it1+1” -- that's not the case. It's true for built-in numeric types, but once overloaded operators come into play, there's no inherent connection between the two operators. Iterators for std::list are forward iterators; they do not have an operator+, but they do have an operator++.
Edit,... |
69,597,316 | 69,604,685 | C++ composition without using the heap in embedded systems | I'm fairly new to C++, this is also my first post on here. I'm trying to use C++ in an embedded systems project so I can take the OOP approach. I'm using the AVR crosspack toolchain (AVR G++ compiler)
My problem is this:
From what i've read, the heap should not be used for dynamic memory allocation in embedded systems.... |
[...] the heap should not be used for dynamic memory allocation in embedded systems.
It depends. I'm currently in an embedded project with maximum safety-related requirements, and we use new, but not delete. So we have a heap, but don't allocate "dynamically", because all allocated objects are kept during the runtime... |
69,597,598 | 69,597,874 | Win32 C++ : Parent controls is drawn on top of children | I'm currently writing a GUI application using a self-made wrapper for Win32 windows and controls. I have made a custom class, which is supposed to act as a container for children controls. The problem is that my custom control is drawn on top of the children controls, which makes them invisible.
I've added the WS_CLIPC... | As Jeromy Adofo pointed out, the problem was related to Z-ordering.
I used SetWindowPos() (MSDN page here) and passed the first two arguments like this : SetWindowPos(childHwnd, parentHwnd, ...); and it worked.
Just another thing, SetWindowPos() asks for the child's position and size. If these values are already set fo... |
69,597,660 | 69,597,767 | Is this a valid way to upgrade a standard library lock? | The C++ standard library lacks an upgrade_lock method, similar to what boost thread provides. But looking at the adopt_lock facilities, one might be tempted to do the following:
// Declare a shared mutex
std::shared_mutex mtx;
// Create a reader lock
std::shared_lock rlock(mtx);
// Other code and program logic ...
... | From the Standard:
unique_lock(mutex_type& m, adopt_lock_t);
Preconditions: The calling thread holds a non-shared lock on m.
So no.
|
69,597,674 | 69,597,750 | error: no match for 'operator=' for operand types std::vector::iterator and __gnu_cxx::__normal_iterator | I'm getting a very nasty error because apparently my iterator types don't match when I try to assign from find_if to a predefined iterator. I'm not using auto because I want to exclude definitions from the for-loop to avoid reallocation.
This is the error in essence:
../components/aurora_fsm/aurora_fsm.cpp: In member f... | std::find_if will return the same type of iterator that was passed to it.
v_adjacent will have the type const std::vector<FSM_StateBase*>&. Notice the const being part of the type. That const means the iterators for this container will be constant iterators.
it, on the other hand, is not a constant iterator.
There's a... |
69,597,859 | 69,598,089 | Why is my display function not running C++ Structs Matrix Transpose? | My program is about taking the transpose of a matrix and displaying it, using structs. I'm using pointer to structs in each function, just for practice although I could've done it by simply passing the struct or by reference. The program is working fine until function inputMatrix. The program takes input and then finis... | The problem was in function transpose, I needed to allocate memory to Matrix transpose
The code is below:
Matrix transpose(Matrix* mat)
{
Matrix transpose;
transpose.rows = mat->rows;
transpose.columns = mat->columns;
createMatrix(&transpose);
for (int i = 0; i < mat->columns;i++)
{
... |
69,598,048 | 69,598,234 | Why is __builtin_parity opposite? | Both GCC and Clang support an implementation-defined function called __builtin_parity that helps determine the parity of a number.
According to what GCC states:
Built-in Function: int __builtin_parity (unsigned int x)
Returns the parity of x, i.e. the number of 1-bits in x modulo 2.
This means that if the number ... | They're just different arbitrary choices.
First note that "the actual parity flag" is a hardware feature only provided on some architectures; of architectures currently in mainstream use, I think x86 is the only one with such a flag. So the very existence, let alone the exact semantics, of such a flag, are not in any ... |
69,598,145 | 69,598,221 | Why use a Logger instead of cout? | In most of the open source C++ code I can see that a logger like the Google logging library glog is used. But what are the advantages? The only advantages that I could find:
Logging is thread safe, so preferred for multi threading
You can choose severity levels
So If I am not doing multi threading and I don't need se... | Using a logger is typically more versatile than directly writing to stdout. A logger usually can be configured to write to stdout or to a file or elsewhere.
In general, directly using std::cout is not recommended for anything but toy programs. Consider you have a function
void foo() {
auto x = calculate_some_res... |
69,598,244 | 69,598,302 | How to make a function unaware of the allocator of its const argument? | I have a class template that supports different allocators for its member:
template<typename Alloc>
class Foo
{
std::vector<int, Alloc<int>> data;
// other members ...
};
Consider a function func that accepts a const Foo&. As the allocator is a part of Foo's type, I need to declare it as a template as well:
te... | The issue you see with func is secondary. Different instantiations of Foo are completely different distinct types. Hence, also different instantiations of func must be different functions.
However, if the interface of Foo does not depend on the allocator, you can add a allocator unaware base class:
struct Foo_base {
... |
69,598,415 | 69,598,460 | How does this method being called with CLASS macro work? | I recently received a request from an acquaintance to assist with building a C++ solution after their developer unfortunately passed away. I'm relatively new to C++ and don't quite understand what the following lines are doing.
This code is from a customized version of the dcraw.cpp library by Dave Coffin.
The MACRO i... | The macro
#define CLASS
has nothing to do with your error. After the macro is expanded the function is:
void merror (void *ptr, char *where)
{
if ( ptr ) return;
//fprintf (stderr,_("%s: Out of memory in %s\n"), ifname, where);
sprintf (PSstring(),"%s: Out of memory in %s\n", ifname, where);
PSpu... |
69,598,643 | 69,607,458 | compiler gives uninitialized local variable error despite initialized variable | I'm studying the Declarations in Conditions topics in C++ and faced the below problem.
#include <iostream>
int main() {
int x;
std::cin >> x;
if(int a = 4 && a != x) {
std::cout << "Bug fixed!" << std::endl;
}
}
I declared and then initialized the variable a. In the The C++ Programming Language by Bjarne S... | In the expression inside the if condition
int a = 4 && a != x
what the compiler actually sees is
int a = (4 && a != x)
where the value of a is clearly being used before it's initialized (which is what the error is saying), and is not the intent of the code.
From C++17, you can use if-with-initializer syntax to achiev... |
69,598,820 | 71,848,260 | How does one run code from RAM on a STM32? | I have this really simple "Hello world" piece of software (see my project on Github), running on a STM32WB55 Nucleo board (basically, it sends "HELLO WORLD\n" via USART1, every 1000 ms).
I would be particularly happy if I could manage to run this piece of software from RAM, instead of Flash. This MCU has 196604 bytes o... | Use the linker script to place everything into RAM. I see you've already got a linker script (STM32WB55RGVX_RAM.ld) that looks like it does this. you can probably activate it by changing set(LINKER_SCRIPT ${CMAKE_SOURCE_DIR}/STM32WB55RGVX_FLASH.ld)
You can see that it defines two memory areas:
MEMORY
{
RAM (xrw) ... |
69,599,435 | 69,605,729 | Running programs using RtlCreateUserProcess only works occasionally | Disclaimer: This questions seems to get downvoted because I should use the normal Win32 API (CreateProcess, ShellExecute). I know about these APIs and I'm aware that RtlCreateUserProcess is not supposed to be called directly. However, the native API is a very relevant topic regarding security, that's why I am researchi... | CreateProcess after create new process do much more job, in particular it create activation context for new process based on exe manifest (BasepConstructSxsCreateProcessMessage + CsrClientCallServer) as result new process have initial activation context, stored in PEB (SystemDefaultActivationContextData and ActivationC... |
69,599,914 | 69,599,936 | Cannot read 'const char*' from python using ctypes | I have a simple function in a c++ dynamic library which returns a const char* value. This value is assigned from a string type as shown in the code. I want to read the returned value of the function in a python script using ctypes:
C++
#include "pch.h"
#include <string>
#define EXPORT __declspec(dllexport)
extern "C"... | Your string is destructing as you reach the end of your function block - and the memory for the associated const char * is getting freed.
EXPORT const char* sayHello()
{
std::string str = "hello world";
const char* chptr = str.c_str(); // points to memory managed by str
return chptr; // ... |
69,600,164 | 69,600,251 | Question regarding the use of std::bind in ROS2 tutorial | I am fairly new to C++ and I have a question regarding practices of std::bind. The following snippet is copied from this tutorial on the ROS2 website. The code creates a class where the timer_ field hosts a timer that is created using create_wall_timer(). creates_wall_timer() accepts a callback object of type CallbackT... | You can't pass a pointer to a member function in isolation (unless that function is declared static), because it needs an instance of the [right kind of] object to be called on.
std::bind binds a pointer to an object (this, in this example) to the member function pointer (&MinimalPublisher::timer_callback) so that when... |
69,601,008 | 69,601,076 | Time complexity of converting std::string to std::string_view | Minimal Reproducible example:
using namespace std;
#include<string>
#include<string_view>
#include<iostream>
int main()
{
string s = "someString";
string_view sV = string_view(s);
string_view sVTwo = string_view(begin(s), end(s));
return 0;
}
Is the time complexity of creating the string_view sV line... |
Is the time complexity of creating the string_view sV linear relative
to the number of chars in the string s or is it irrelevant how long
the string s is?
string_view(s) will call the string's operator std::string_view(), which is equivalent to return string_view(data(), size()), and since string's data() and size() ... |
69,601,043 | 69,609,876 | Boost.beast websocket - How to make a pending async_read() queue/work for io_context.run()? | Complete noob here learning c++ through an IoT project using Websocket.
So far, somewhat successfully modified this example beast async_client_ssl to handshake with a server.
My problem is ioc.run() runs out of work and exits after the initial callback.
I was having the same issue as this post two years ago.
Boost.best... | Okay, the simplest thing is to add a work_guard. The more logical thing to do is to have a thread_pool as the execution context.
Slap a work guard on it:
boost::asio::io_context ioc;
boost::asio::executor_work_guard<boost::asio::io_context::executor_type>
work = make_work_guard(ioc.get_executor());
(or simply auto... |
69,601,091 | 69,601,237 | pass stack variable to function that takes a std::shared pointer | If I have a global variable, or a stack variable can I pass it to a function that takes a std::shared_ptr with a templated class like this:
template<class T> class shared_ptr_stack:public std::shared_ptr<T> {
public:
shared_ptr_stack(T * target):std::shared_ptr<T>(target, [](T * t){}){};
};
};
The goal wou... | A function that takes a shared ptr has the right to make your data persist indefinitely. It can pass your data to different structures, threads, whatever.
Your code means that the data becomes trash when the stack frame goes out of scope, or at static destruction time, either of which can be before the last shared ptr... |
69,601,357 | 69,601,472 | How to implement and use vectors in C++/CLI Visual Studio 2019? | I've been trying to figure out how to implement vectors in the .Net framework with C++ but I keep getting errors that's saying its not able to define the vector. I'm also getting squiggly lines saying "namespace cliext has no member vector".
#include <cliext>
String^ toBinary(int decimal) {
cliext::vector<Str... | According to Microsoft documentation, you need to
#include <cliext/vector>
|
69,601,491 | 69,601,573 | Initialize global variable using extern global variable | Assume file_1.cpp and file_2.cpp are two files in one program. I encountered situation as follows:
// file_1.cpp
extern int y; // Line 1
int z = y + 1; // Line 2
int main() {
cout << y << endl; // 2
cout << z << endl; // probably 1, sometimes 3
}
// file_2.cpp
int x = 1; // Line 3
int y = x + 1; // Line 4
M... | The situation you describe is known as "global initialization order fiasco".
When a program starts, the memory for all global variables is filled with 0s (that is, each byte is 0). In the next stage, constructors or initializations for all global variables are executed. The order of those initializations within each fi... |
69,601,640 | 69,601,732 | How can I get C++ to prefer converting char* to string_view instead of bool? | I have a simple program like this:
#include <iostream>
#include <string_view>
class C {
public:
void print(std::string_view v) { std::cout << "string_view: " << v << std::endl; }
void print(bool b) { std::cout << "bool: " << b << std::endl; }
};
int main(int argc, char* argv[]) {
C c;
c.print("foo");
}
... | You can turn the string_view overload into a template function, and add a constraint to it so that it has a higher preference than the bool overload when it receives a type that can be converted to string_view.
#include <string_view>
class C {
public:
template<class T>
std::enable_if_t<std::is_convertible_v<... |
69,601,650 | 69,693,764 | Selection of inherited operator contrary to `using` clause in C++ | In the following example struct S inherits from two functional objects A and B each with its own operator (), and then declares using A::operator() to take the operator from A:
using A = decltype([](int){ return 1; });
using B = decltype([](){ return 2; });
struct S : A, B {
using A::operator();
};
int main() {
... | GCC (and Clang) are correct in this case.
A captureless nongeneric lambda has a conversion function to function pointer ([expr.prim.lambda.closure]/8), which is inherited by S (and doesn't conflict since the conversion functions from A and B convert to different types). So during overload resolution for a function call... |
69,601,954 | 69,602,176 | Standard input state after error condition | The following code snippet is taken from C++ Iostreams Handbook by Steve Teale. It suggests invoking cin in an endless loop so that the user is continuously prompted for the correct input, and only when the correct input is entered do we exit the loop.
This code snippet works correctly but I am confused by the if(cin)... | What you're observing is a result of inheritance and implicit conversion. More specifically, std::cin has an operator bool() that converts the state of the stream to a boolean and that operator returns !fail().
std::cin is a global std::basic_istream provided by the standard lib, and basic_istream inherits from std::ba... |
69,601,955 | 69,602,017 | Temporarily index letters in a string to a different binary | For self education purposes:
So ASCII puts every character to a binary representation right? A = 65 = 01000001, etc. I was curious though, if you wanted to temporarily switch the variable to something different to conserve space, is there a simple way to go about doing that? Like if I had a project where I only needed ... | Firstly it will only make your code theoretically take 20 times less space for those variables, not make it faster or reduce the size of the whole code. In practice the difference will be negligible, it will break compatibility with standards (ASCII) and there is no straightforward way to implement this in Python witho... |
69,602,649 | 69,602,742 | How to write multiple text files from a text file in C++? | I have a txt file that has 500,000 lines, and each line has 5 columns. I want to read data from this file and write it into different 5000 txt files that have 100 lines each, starting from the first line to the last of the input file. Also, the filename is output with the order number, say "1_Hello.txt", which has the ... | You're working too hard – you don't need to read the entire input first, and you don't need to care about the structure of each line.
Read and write line-by-line, a hundred lines at a time.
Stop when there is nothing more to read.
Something like this should do it:
int main()
{
std::ifstream in("mytext.txt");
in... |
69,603,036 | 69,603,186 | I am getting stack smash error specifically on moodle | I have ran the same code on my local compiler and it works perfectly but for some reason on moodle it runs , gives an output and at the end gives a stack smash error. Is it because of the sscanf?
Here is the input:
10
(1,3)
(12,10)
(6,5)
(22,13)
(2,15)
(35,-10)
(15,-15)
(20,5)
(12,-8)
(1,-10)
#include<iostream>
#inclu... | I looked at your code, and I think problem is in sscanf, and solution is actually simple.
Try to change declaration of string ( char array ) in main function from char c[5]; to char c[10]; it can be any other number, but I think, if you enter even bigger numbers and c[10] will make error, so I recommend you to make it ... |
69,603,056 | 69,605,922 | How to create a multi root flatbuffer json file? | How to create a multi root flatbuffer json file?
table Login {
name:string;
password:string;
}
table Attack {
damage:short;
}
I created the following json file
{
"Login": {
"name": "a",
"password": "a",
}
}
but get error: no root type set to parse json with
| Add root_type Login to the bottom of your schema file. If you also want to parse JSON from the command-line with Attack then stick that into its own schema, or use --root-type manually.
Also see the documentation, e.g. https://google.github.io/flatbuffers/flatbuffers_guide_using_schema_compiler.html
|
69,603,311 | 69,603,703 | How to read multiple input files and write into a new file in txt and excel in C++? | I used to run a calculation by reading from 1 txt file ("1_Hello.txt"), calculate and output by functions, and write the output into a new txt file.
But now I have 5000 txt files ("1_Hello.txt" to "5000_Hello.txt"). I want to read all 5000 txt files, calculate each txt file by functions ( variable "a" and vector "v"), ... | Here is some very simple and incomplete code that might help along the way:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
int main(int argc, char* argv[]) {
/* define some vectors to store the data in */
std::vector<int> id_vec;
std::vector<int> x_vec;
std::vector<int> y_ve... |
69,604,370 | 69,604,889 | Why is the converting constructor preferred to the conversion operator? | I have this class SmallInt that should represent a positive integer value in the range 0-255-inclusive:
struct SmallInt{
explicit SmallInt(int x = 0) : iVal_( !(x < 0 || x > 255) ? x :
throw std::runtime_error(std::to_string(x) + ": value outbounds!")){}
operator int&() { return iVal_; }
int iVal_;
};
... |
[over.match.oper]/4 For the built-in assignment operators, conversions of the left operand are restricted as follows:
...
(4.2) — no user-defined conversions are applied to the left operand to achieve a type match with the left-most
parameter of a built-in candidate.
Thus (int &)smi = 33 interpretation is explicitly ... |
69,604,562 | 69,604,812 | C++ - Object destruct itself and cant reach variables | I'm newbee about c++ and I'm having trouble with destructors. When i create an object and push to a vector that holds class, i can see variable "_path" is initialized. But after i try to reach the variable, i see object calls decontsuctor and i cant see the variable.
Here is the code:
#include <iostream>
#include <vect... | std::string s = std::to_string(i);
vectorA.emplace_back(returnA(s.c_str()));
std::string's c_str() method returns a pointer to std::string's internal buffer that's no longer valid when the std::string gets changed in any way.
This std::string gets destroyed at the end of this for loop, and that certainly meets... |
69,604,659 | 69,604,700 | Unable to avoid copying while pushing objects with copy-construcor into a vector | I'm trying to avoid copying with emplace_back() and reserve(). But when I've tried to do it, i caught myself getting 3 copies for reason i cannot really understand. reserve() actually helps to avoid copying, but emplace_back() actually does nothing with it (works the same way as push_back() in this case). Here's the co... | std::move isn't useful here. The temporary Vertex object is already a prvalue, so casting it to an xvalue doesn't change anything. The class has no move constructor, so copy initialisation cannot move; it has to copy. The implicit move constructor has been inhibited by the user defined copy constructor. Although, the m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.