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,150,510 | 69,150,583 | Reason for using std::forward before indexing operator in "Effective Modern C++" example | Quoting from item 3 ("Understand decltype") of "Effective Modern C++" :
However, we need to update the template’s implementation to bring it into accord
with Item 25’s admonition to apply std::forward to universal references:
template<typename Container, typename Index>
decltype(auto) authAndAccess(Container&& c, Ind... | It depends on how the Container is implemented. If it has two reference-qualified operator[] for lvalue and rvalue like
T& operator[] (std::size_t) &; // used when called on lvalue
T operator[] (std::size_t) &&; // used when called on rvalue
Then
template<typename Container, typename Index>
decltype(auto) authAndAcces... |
69,151,041 | 69,151,188 | Copy Constructor called unexpectedly | I am new to C++ programming. I am using Visual Studio Code, my code:
#include <iostream>
using namespace std;
class Calculator;
class Complex
{
float a, b;
string Operation;
string name;
friend class Calculator;
public:
Complex(float, float, string, string);
Complex(float);
Complex();
... | You will take a copy of Complex object on those functions:
Calculator::SumRealComp(Complex, Complex);
Calculator::SumImgComp(Complex, Complex);
So, on every call to those functions, you take two copies of the Complex object. You could pass a Complex const& object to avoid copy:
Calculator::SumRealComp(Complex const&, ... |
69,151,377 | 69,151,512 | How is it possible that tv_sec of both timeval structures are the same but subtracting them gives me a non zero value | timeval end_time;
timeval Dbg_timer;
The above time structures where initialized with gettimeofday() at some point.
Below is how I calculated the time difference:
long int elaspsed_time_s = end_time.tv_sec - Dbg_timer.tv_sec;
printf("elaspsed_time_s =%d -> end_time_tv_sec=%d Dbg_timer_tv_sec=%d \n",
elaspse... | %d is not a proper conversion to use for the long int value elaspsed_time_s. (By the way, the correct spelling is “elapsed”.) Use %ld for elaspsed_time_s.
%d is also not a proper conversion to use for the time_t values in the tv_sec member. On POSIX systems, time_t is an integer type, but it is not necessarily an int, ... |
69,151,642 | 69,156,351 | Is this a wrong approach to find whether array is subarray of another array? | bool isSubset(int arr1[], int m,int arr2[], int n){
set<int> hashset;
for (int i = 0; i < m; i++){
hashset.insert(arr1[i]);
}
for (int i = 0; i < n; i++) {
if (hashset.find(arr2[i]) == hashset.end())
return false;
}
return true;
}
Is this correct method to find wheth... |
Is this correct method to find whether arr2 is sub array of arr1 or not
No, it isn't. Your method doesn't consider the order of elements. It is more of a method to find whether a bunch of numbers (given in arr2) exist in an arr1.
For instance, if int arr1[] = {1, 2, 3} and int arr2[] = {2, 1}, the method you implemen... |
69,151,937 | 69,152,611 | How to determine the maximum number of threads? | I am learning parallel programming. I use OpenMP with C++ and I want to understand how to determine the maximum number of parallel threads I can set on my laptop. In the documentation I found the function omp_get_max_threads(), but how can I make sure the return value is correct?
When I'm compiling this code:
#include ... | When you want to find out how many threads you are able to use. You can do this by calling std::thread::hardware_concurrency().
|
69,152,078 | 69,152,311 | chrono type to string c++20 | I am trying to format the time into hh::mm::ss then put it in a wide-string-stream. The code is as follows.
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::chrono::steady_clock::duration time_elapsed = end - start;
std::chrono::hh_mm_ss formatted {std::chron... | The following works for me in MSVC.
As of 2021-08-12 I had to use the /std:c++latest switch with Visual Studio version 16.11.2 in order for this solution to work.
const auto start{ std::chrono::steady_clock::now( ) };
std::this_thread::sleep_for( std::chrono::milliseconds{ 1000 } );
const auto end{ std::chrono::steady_... |
69,152,150 | 69,152,847 | How to display a QChartView inside a QStackedWidget? | I want my form to have a QStackedWidget with 2 (at least) pages and each of them has a QChartView.
In the form editor, through the 'promote' menu, I made a QChartView from QGraphicView. (screenshoot (so far there is only 1 QChartView on it - so that i can see which page is open)).
From the main window, when one of the ... | Doing ui->graphicsView = new QChartView(chart); does not replace the QChartView, you are just assigning the pointer. The solution is to reuse the existing QChartView so it changes to: ui->graphicsView->setChart(chart);.
|
69,152,217 | 69,328,601 | Can i connect winCC OA with Unreal Engine? | How can I put into the WinCC OA a 3D model like in the Unreal Ungine? I have 3D model which might act in UE, and I want it to fetch data and logic for its actions from WinCC OA. Is it possible to put 3D model into WinCC OA and make it act, or if not, maybe there is a way to make interaction between WinCC OA and UE?
| I guess one way would be to implement an External Widget Object (EWO). EWOs are based on Qt so you can implement everything you are able to implement in a QWidget object. The interaction between WinCC OA and the EWO is done by accessing the exposed properties and events of the EWO and with ctrl script.
The WinCC OA doc... |
69,152,299 | 69,152,570 | error: conflicting declaration ‘typedef signed char int8_t’ | how can i solve this
In file included from /usr/lib/gcc/x86_64-linux-gnu/8/include/stdint.h:9,
from /usr/include/inttypes.h:37,
from /usr/include/stdio.h:44,
from kernel.cpp:5:
/usr/include/stdint.h:122:59: error: conflicting declaration ‘typedef signed char
int8_t’
typedef signe... |
how can i solve this
Remove the line:
typedef char int8_t;
From the file includes/types.h. Or do not include stdint.h.
|
69,153,124 | 69,153,319 | Why is my constant buffer not being updated? | Bellow is the cpu side declaration for the buffer I'm having the issue:
struct PSMaterialTransform {
float Alpha;
bool WrapUV;
XMFLOAT2 padding;
} static m_PSMaterialTransformDesc;
And bellow is the gpu side declaration for the buffer:
cbuffer MaterialTransform: register(b1) {
float Alpha;
... | The size of bool in HLSL is 4 bytes, so your CPU structure should be something like
struct PSMaterialTransform
{
float Alpha;
int32_t WrapUV; //or uint32_t
XMFLOAT2 padding;
}
If you want, you can use typedef/using alias like this:
typedef int32_t bool32; //or
using bool32 = int32_t;
Then yo... |
69,153,191 | 69,153,428 | OpenGL doesn't sample 2D texture correctly | I use this code for all OpenGL preparations. I took these pieces from my sources, so there can be omitted parts and uninitialized or undeclared variables, etc. but this works. I tried to post only the meaningful parts of the code.
// Texture reading
int w{}, h{}, channels{};
unsigned char * bytes = stbi_load(path.c_str... | You have to look up the texture in the fragment shader. The vertex shader is just executed for each vertex coordinate of a primitive. However the fragment shader is executed for each fragment. The vertex shader outputs are interpolated along the primitives and passed to the fragment shader. Therefore your code lookup t... |
69,153,401 | 69,153,608 | Can't assign a pointer to a template-derived class | I'm working on a template class. Not that it matters, but my goal is a list class that will use some static members to maintain a linked list of class objects. Each different class will have it's own list. Not only that, but each class will have a compile-time allocated pool of available instances of the object rath... | What we do is not derive ListOfSomething from the list base class. We would make ListOfSomething the singleton and have a generic list class.
class ListOfSomething
{
public:
static ListOfSomething& instance()
{
static ListOfSomething los;
return los;
}
// Obtain a reference to the list.
... |
69,153,415 | 69,153,574 | to_string returning the ascii value | This is a program to print the subsequences and thei ascii values using recursion
#include <iostream>
using namespace std;
void sub(string str,string ans)
{
if(str.length()==0)
{
cout<<ans<<endl;
return;
}
string ros=str.substr(1);
char ch=str[0];
sub(ros,ans);
sub(ros,ans+... |
why is to_string function returning the ascii value of the character
There is no std::to_string(char), so the best matching function is chosen, in this case it's (most probably) std::to_string(int). std::to_string(int) just prints the number in decimal, as-if by using printf("%d", value). See
https://en.cppreference.... |
69,153,764 | 71,623,341 | unshare user namespace, fork, map uid then execvp failing | I am trying to do the following sequence of actions:
unshare the user namespace;
Map the user in child process to root;
execvp.
However, when running id, my code outputs the user as a nobody or fails without error.
#include <sched.h>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <stdlib.h>
#include ... | Pretty sure you've already found the answer, but this is a minimal sample I could come up with:
// gcc -Wall -std=c11
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sched.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdarg.h>
void write_to_file(const char *which, const char *format, ...... |
69,153,879 | 69,153,972 | Replace QTime::elapsed() | I want to plot sin(t) where t is time in seconds:
void MainWindow::realtimePlot()
{
static QTime time(QTime::currentTime());
double key = time.elapsed()/1000.0;
QTextStream(stdout)<<(key);
static double lastPointKey = 0;
if(key - lastPointKey > 0.002)
{
ui->widget->graph(0)->addData(key... | Use QElapsedTimer:
static QElapsedTimer timer;
double key = timer.elapsed() / 1000.0;
|
69,154,255 | 69,154,305 | Is it ok to return a variable or object by reference in C++? | So i'm curious whether or not its ok to pass a variable or an object by reference from one file to another in C++ like in the examples below.
String example:
int main() {
//
std::cout << GetName() << std::endl;
}
std::string name = "Paul";
std::string& GetName() {
return name;
}
Object example:
int main() {
... | Yes, the above works, but is not commonly used. It works only because in your case the objects whose address you return are static. The following will not work:
std::string& GetName() {
std::string name = "Paul";
return name;
}
Note that the compiler might let you do this, however since the variable name is alloca... |
69,154,367 | 69,256,971 | Is it better to use "static member" in circular linked list or just go by iterative way? | Code I made for circular linked list:
#include<iostream>
using namespace std;
class node
{
public:
int data;
node* next;
node():data(0),next(NULL){}
node(int x):data(x),next(NULL){}
};
void push(node** head_ref,int val);
void printlist(node* n);
int main()
{
node* head=NULL;
push(&head,14);
push(&head,2... | Okay, first of all regarding the static variable it is a pretty good hack to keep the last node (i think you were intending to do that when you started to implement the code). But a quick remark your circular linked list will be reversed in this case because by the idea of the linked list you should add your nodes to t... |
69,154,997 | 69,155,047 | Why auto is not allowed in template function for creating a built-in array? | This code below does not compile:
template<typename... Ts>
void CreateArr(const Ts&... args)
{
auto arr[sizeof...(args) + 1]{ args... };
}
int main()
{
CreateArr(1, 2, 3);
}
due to the following errors:
'arr': in a direct-list-initialization context, the type for 'auto [6]' can only be deduced from a single ... |
Why cannot I use auto to define the type of the array?
For the same reason, following does not work/ allowed!
auto ele[]{ 1, 2, 3 };
More reads: Why can't I create an array of automatic variables?
How to define it properly to work with the template?
Use the std::common_type_t for specifying the type
#include <typ... |
69,155,016 | 69,155,129 | CT class instance with non-literal variables in separate namespace | I have a simple struct:
struct Test
{
int a;
Test(int b, int c)
{
a = b * c;
}
};
I need to declare CT TransformData variable. It works with #define:
#define testDefault = Test(1, 2)
But I need to separate this variable to a separate namespace. If I use consexpr I get the error:
the type «co... | The class you show is actually a good candidate for producing constexpr constants. But its constructor needs to be marked constexpr.
struct Test
{
int a;
constexpr Test(int b, int c)
: a(b*c) // must be initialized up to C++20
{
a = b * c + 1; // but can still be reassigned
}
};
A "lite... |
69,155,272 | 69,159,885 | Qt3D input handling system works differently depending on the place it was created | I was implementing a custom camera controller for Qt3DRender::QCamera and I faced a rather strange behavior of the Qt3DInput::QMouseHandler. Depending on the environment it was created it either responds to mouse events or not. There are two cases: create both the device and the handler in the MainWindow object or crea... | Looks like you just connected to different signals.
In first case you are using &Qt3DInput::QMouseHandler::positionChanged which will be sended quite often. In second one - &Qt3DInput::QMouseHandler::pressAndHold which will be sended when a mouse button is pressed and held down.
After fix both logging functions are cal... |
69,155,417 | 69,155,468 | C++ Primer (5th edition); Ch 19 - Algorithms: std::lower_bound | This is from C++ Primer (5th edition); Ch 19. "Appendix: algorithms":
lower_bound(beg, end, val)
lower_bound(beg, end, val, comp)
Returns an iterator denoting the first element such that val is not less than that element, or end if no such element exists.
upper_bound(beg, end, val)
upper_bound(beg, end, val, comp)
R... |
Is it a mistake in the book?
If you trust cppreference, then: Yes, it is a mistake:
std::lower_bound
Returns an iterator pointing to the first element in the range [first, last) that is not less than (i.e. greater or equal to) value, or last if no such element is found.
Or, if you don't trust that website, this Dra... |
69,155,498 | 69,155,573 | How to get the values of a std::vector<int>*? | I do not know what to put in the 'Title' box so I consider that the title does not completely answer my problem and I am sorry about it.
First of all, I would like to give a bit of context. I discovered the development of the network for two weeks now for a 3D game.
Today I'm focusing on shipping packages using std::ve... | memcpy(&buffer[written], &vec, sizeof(vec));
You already have problems here, even before receiving anything.
sizeof(vec) is the size of std::vector<int>. Which will probably be 8 or 16 bytes, or something like this. The size of the vector will always be the same, whether the vector is empty, or holds an image of every... |
69,155,988 | 69,156,141 | call to non-static member function without an object argument when call my Struct in function that use in std::async | I have this code :
#include <future>
#include <iostream>
struct Status
{
std::string Available;
std::string Connected;
std::string DisConnected;
};
class Test
{
public:
Test();
Status &status()
{
return _status;
}
void setStatus(const Status &newStatus)
{
_status = newSt... | You need to change it to _status.Available.
You're attempting to reference the Status struct, rather than your instance of that structure.
|
69,156,201 | 69,156,265 | Can cin be connected to a string variable? | For example, if I type 'a', how do I print out the value of the variable a, i.e. "0 1" ?
string a = "0 1"; string c = "1 1";
string b = "0 1"; string d = "1 1";
cin>>
cout <<
| You are asking about some kind of instrospection like some interpreted languages have, but C++ doesn't work that way.
This is not the right way to think about a C++ program (or in any other compiled language), the identifiers in the source code really disappear once the program is compiled.
In other words, there is no ... |
69,157,732 | 69,158,660 | Couldn't use generator and task in clion on mac | I have such code:
generator<int> range(int start, int end) {
while (start < end) {
co_yield start;
start++;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
for (auto n: range(0, 10)) {
cout << n << ' ';
}
}
When I compile it, I get an error:
error:... | As 康桓瑋 said, it is still in the proposal stage, the workaround is to use a third-party library such as cppcoro's generator implementation.
|
69,158,170 | 69,189,446 | Alleviate long qualifications in header files | I define an inline function object in a header file, like this:
// fmap.hpp
namespace util {
inline auto constexpr fmap = boost::hana::curry<2>(boost::hana::flip(boost::hana::transform));
}
Client code can simply #include "fmap.hpp" and start using util::fmap as they like.
So far so good.
But sometimes the definit... | Thinking about it, I can solve the riddle by just constructing and calling on the fly a lambda from void (hence the () between [] and {} can be removed) to the desired lambda:
namespace utils {
inline auto constexpr fmap = []{
using namespace boost::hana;
return curry<2>(flip(transform));
}();
}
|
69,158,206 | 69,158,289 | How do I pass in distribution functions as parameters for a function? | I would like to pass in random distribution functions (they can be different depending on what I want, which can change), so I'd like them to be a parameter function essentially, how can I achieve this?
auto GenerateRandomVector(double &mean, double &SD, int &VecSize) -> std::vector<double> {
std::random_device... | You simply take it by reference (if you want to keep its internal state) or pass it by value.
Example using references:
std::mt19937& prng() {
thread_local std::mt19937 mersenne_engine(std::random_device{}());
return mersenne_engine;
}
std::vector<double> GenerateRandomVector(double& mean, double& SD,
... |
69,158,516 | 69,159,470 | Do we really need placement new-expressions? | I am trying to understand placement new-expressions in C++.
This Stack Overflow answer states that T* p = new T(arg); is equivalent to
void* place = operator new(sizeof(T)); // storage allocation
T* p = new(place) T(arg); // object construction
and that delete p; is equivalent to
p->~T(); //... | The first thing to note is that *p = T(arg); is an assignment, not a construction.
Now let's read the standard ([basic.life]/1):
... The lifetime of an object of type T begins when:
storage with the proper alignment and size for type T is obtained, and
its initialization (if any) is complete (including vacuous initia... |
69,159,030 | 69,160,665 | How to make my game to run fast on DOSbox, too? | I have been developing a simple RTS game using C++ in Linux. By the DJGPP, I can also cross-compile the game to DOS build.
In Linux, once the game starts, it only uses about 25MB of RAM though many game objects such as game units are created.
But when it runs in DOSbox, it is very slow at the beginning and getting slow... |
The game uses about 25MB of RAM in Linux, so does it have to use such an amount in DOS, too?
Linux executables are 32 or 64-bit whereas DOS is a 16-bit OS so many objects will be smaller in DOS. However many 32/64-bit operations in DOS would be longer in DOS due to obvious reasons, which means they'll require large... |
69,159,188 | 69,159,236 | Null character when using range-based loop over temporary string? | When I loop over a temporary std::string (rvalue?) using a range-based for loop, there seems to be an extra character, the null terminator \0.
When the string is not temporary (lvalue instead?), there is no extra character. Why?
std::map<char, int> m;
for (char c : "bar") m[c] = 0;
for (auto [c, f] : m) {... | Because "bar" is not a std::string, but a char array (const char[4]) containing 4 elements, including the last null character. I.e. c-style string literal:
The null character ('\0', L'\0', char16_t(), etc) is always appended to the string literal: thus, a string literal "Hello" is a const char[6] holding the character... |
69,159,522 | 69,159,659 | Why do I get "invalid use of incomplete type", when the class is fully defined? | I know this type of errors occur when a base class is only forward declared, but in my case it's fully implemented as far as I can tell:
I'm trying to create a unit system which would only compile if the correct units are used, employing literals and algebraic operators.
I start with a base class Units which is just a... | Looks like the compiler is confused and the warning is misleading. Provide the missing template argument to fix it:
return Mps<T>{static_cast<T>(rhs) / static_cast<T>(lhs)};
^^^
You can (probably) define a deduction guide if you wish to avoid specifying the argument explicitly.
Other issues:
Missing semico... |
69,159,636 | 69,159,886 | What is the storage duration of a temporary object: automatic, thread, static, or dynamic? | What is the storage duration of a temporary object: automatic, thread, static, or dynamic?
I know that the lifetime of a temporary object ends at or before the full expression where it was created, unless it is bound to a reference, in which case its lifetime is extended to that of the reference and that gives us a low... | The standard is a bit vague. It says that temporary objects can have automatic, thread or static storage duration, but within definition of those storage durations, it only specifies when variables have such duration.
The standard doesn't exactly say what the storage duration of temporary is by name in each case. Rathe... |
69,159,853 | 69,161,309 | CUDA assert - overload on __host__ __device__, why no warnings/errors? | I'm trying to understand how CUDA assert works under the hood. The assert macro calls the __assert_fail function, of which I can find the following signatures:
/usr/include/assert.h:extern void __assert_fail (const char *__assertion, const char *__file,
/usr/local/cuda-10.2/targets/x86_64-linux/include/crt/common_func... | Consider the following example program main.cu which is compiled via nvcc --keep main.cu -o main
#include <cassert>
__global__ void kernel(){
assert(false);
}
int main(){
kernel<<<1,1>>>();
cudaDeviceSynchronize();
assert(false);
}
Compilation of a CUDA program is performed in several steps as desc... |
69,159,941 | 69,160,937 | How to get data from a non-member function into a member function in Qt? | I have a Qt project (in Win10) that requires a non-member function in my MainWindow cpp file. It's a callback function that is triggered automatically from an external library when data from an attached sensor arrives. I like to display this data on a MainWindow widget (a plainTextEdit), but of course I cannot access a... | You should use QMetaObject::invokeMethod to call a slot of a QObject from a non QObject slot (your callback funtion).
Here is an example:
class MainWindow : public QMainWindow
{
Q_OBJECT
//...
public slots:
void displayData( QString szNewData );
};
//Cpp MainWindow.cpp file
static MainWindow * mainW... |
69,159,968 | 69,160,001 | What is the difference between these two structure declarations? | I am confused about these two structures from different tutorials:
typedef struct complex {
float real;
float imag;
} COMPLEX;
typedef struct {
float real;
float imag;
} COMPLEX;
COMPLEX c1;
Are they both correct? Why? and is it necessary to add the lowercase of complex before struct? What is genera... | With the first you can use either the type-alias COMPLEX or struct complex.
With the second you have an anonymous structure which can only be used with the type-alias COMPLEX.
With that said, in C++ any structure name is also a type-name and can be used as a type directly:
struct complex { ... };
complex c1;
|
69,160,099 | 69,160,149 | How to avoid an explicit loop when pulling out a vector of a particular member from a vector of a class containing that member | Suppose I have a class
struct Foo {double x; double y;}
and std::vector<Foo> xy;
I also have a function to pull out the x members:
std::vector<double> bar(const std::vector<Foo>& xy);
which loops through each element of xy.
Is there a way of using the C++ standard library so I can avoid an explicit for loop?
| You can use std::transform. E.g.
std::vector<double> bar(const std::vector<Foo>& xy) {
std::vector<double> rt;
rt.reserve(xy.size());
std::transform(std::begin(xy),
std::end(xy),
std::back_inserter(rt),
[](const Foo& f) { return f.x; });
return... |
69,161,698 | 69,161,795 | Not able to use std::size() in one program | I am working with arrays. So to find size of array, I need to use std::size(), it works well in one program but fails to work in another.
The program that works:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
int array[]{ 30, 50, 20, 10, 40};
std::sort(std::begin(array), std::end(arr... | First of all, this definition :
int components[]{};
Is completely wrong. If you really needed to you old c-style arrays, you need to define their size using new:
int *components = new int[size];
C-style arrays have to know their size during compilation, unless you use keyword new.
If you want to use collection with ... |
69,161,859 | 69,161,935 | how to implement smart templated type casting (e.g. C<int> / C<double> -> C<double>) | Consider the following code:
template<typename T, typename U>
constexpr auto divide(T rhs, U lhs) { return rhs / static_cast<T>(lhs); }
Here divide defaults to the rhs type (which is the same default behavior we get from the compiler.
But what if we wanted to make divide smarter such that it would deduce in compile t... | I think you are looking for std::common_type:
#include <type_traits>
#include <iostream>
template<typename T>
constexpr T divide_impl(T rhs, T lhs) { return rhs /lhs; }
template<typename T, typename U>
constexpr auto divide(T rhs, U lhs) { return divide_impl<std::common_type_t<T,U>>(rhs,lhs); }
int main ()
{
... |
69,162,055 | 69,164,597 | boost::stacktrace fails to provide line number | I'm having issues with getting the line number of a stack frame provided by boost::stacktrace. When printing the task with boost::stacktrace::to_string it prints the line number but when calling source_line() it returns 0.
Example:
auto frame = boost::stacktrace::stacktrace()[0];
std::cout << frame << std::endl;
std::... | I get the same behaviour on Ubuntu 18.04 with full debug info.
Using
strace -f -e execve,clone,fork,waitpid ./sotest
Shows that the command being executed is
[pid 5972] execve("/usr/bin/addr2line", ["/usr/bin/addr2line", "-e", "./sotest", "0x000055EC1854F7FF"], 0x7fff8e99bdd8 /* 82 vars */) = 0
Indeed, manually che... |
69,162,170 | 69,162,209 | What is the behavior of nested If's in C++? | #include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 2;
if(a > 0)
{
cout << "we are in the first" << endl;
if(b > 3)
{
cout << "we are in the second" << endl;
}
}
else
{
cout << "we are in else" << endl;
}
}
Accordi... | When they say "nearest" then they refer to the distance to the whole if statement, not only the if keyword. The whole if statement is:
if (a>0){
cout<<"we are in the first"<<endl;
if (b>3){cout<<"we are in the second"<<endl;}
}
It ends at the }. The } closes the block of the outer if and that is the if which i... |
69,162,601 | 69,302,895 | Using GSL Monte Carlo Integration in C++ for a multidimensional function | I'm trying to use GSL Monte Carlo Integration in a C++ code that I'm generating.
The idea would be to have a brownian motion function (brownian), which is used in another function (g) for performing 4-dim numerical integration.
double brownian(const double &x,const double &x0,const double & sigma,const double & t) {
... | This is a diff between your code and the one that compiles. This does not mean that my code is correct: you only get what you asked for - since you did not provide a complete minimum working example, anyone trying to help you is forced to guess what your problem really is.
13c13
< double g(double *k, size_t dim, void ... |
69,162,942 | 69,185,854 | STEAM: Failed to Initialize game server with Steam - Warning unable to Host | I am following this tutorial "https://medium.com/swlh/ue4-tutorial-how-to-connect-a-multiplayer-game-with-steam-ccc89bd8d8a9" to use Steam with Unreal.
The project file is here: https://github.com/bluebubblebee/UE4_CoopPuzzleGame/tree/master/CoopPuzzleGame/Source
After making changes to the ini file to set Steam as Def... | So it seems it is a problem in version 4.27 as @dratenik pointed out that it breaks the advanced session plugin.
As suggested in the forum steam works if I set SessionSettings.bUseLobbiesIfAvailable = true;
It works even if I set DataAdvertisementType to ViaOnlineService. It works on 2 PCs on 2 different steam accounts... |
69,163,275 | 69,163,503 | Return std::array from a function as a range | Say I have two arrays:
constexpr std::array<int, 3> a1{1, 2, 3};
constexpr std::array<int, 5> a2{1, 2, 3, 4, 5};
What is the right way to convert them to ranges of the same type to make it possible to call process_result function with their return values?
constexpr void process_result(RangeType range) { for (auto ele... | You might use (non owning) std::span to allow any contiguous ranges:
constexpr void process_result(std::span<const int> range)
{
for (auto elem: range) {
//do something with elem
}
}
|
69,164,187 | 69,164,407 | Using filter on vector of variant | I am trying to iterate over filtered (by type) std::vector<std::variant<T...>>.
Problem I hit is that the std::get is overloaded function(and has many implicit template args I need to type out) so I would need to cast it to something specific.
This seems ugly and hard so I tried to hack together holds_alternative and g... | By changing const R& to forwarding reference R&& (and fixing typo), it works:
template <typename R, typename T>
decltype(auto) operator|(R&& r, variant_filter_t<T>) {
return r | std::views::filter(engaged<T>)
| std::views::transform(variant_get<T>);
}
int main() {
std::vector<Color> colors{Red{}, Green{... |
69,164,268 | 69,164,348 | How to specialize a function using enum | I'm trying to refactor some code. Basically is a state machine based with enum.
There are a lot of switch statements and functions that got called with different names and ambiguations.
Since they force me to keep the enum, I would like to refactor it using template. Basically I would like to use template to implement ... | You need a compile time evaluatable constant, this will work
int main()
{
constexpr auto CurrentAnimal = AnimalType::Dog;
Foo<CurrentAnimal>();
return 0;
}
or directly use
Foo<AnimalType::Dog>();
Note : you can't use your construct to make decissions at runtime.
Templates only lead to compile time polym... |
69,164,280 | 69,164,695 | IMU Client responce values are all zero when runing ROS services | I create ROS services that pass the IMU sensors values from the Server to Client. Im able to build the package but some how the Client values are all zeros.
So I would like to create IMU ROS services. I have a Server(in my case is a microcontroller ESC32) that can obtain IMU reading and should pass to the Client (in my... | The server is just returning the values of req which in the above code is a default service message passed in from main(). You need to cache the IMU values when them come in on a topic(in the server code). Then when the service is called it needs to pulled from the last IMU value. Your server needs to include something... |
69,164,361 | 69,164,561 | Is there any name space called "sdds" ? Because I am not able to find out about it anywhere | I am trying sdds namespace in my code as it is asked to do so but that is throwing me error message.
The code is right below:
using namespace sdds;
Error message which I am getting is pasted down,
Error (active) E0725 name must be a namespace name w1p1 D:\w1p1\vendingmaching.cpp 5
| There is no namespace called sdds in the c++ standard library. For the using directive:
using namespace sdds;
The namespace sdds must exist. Note that anybody can create a namespace and name it as they want. If you merely want to silence the error without changing the existing code you can add:
namespace sdds {
}
H... |
69,164,836 | 69,164,976 | concept using helper class | In order to be able to write stuff like cout << vec for iterable types like vector<int> vec;, I wanted to define operator<<(osteam&, const T&) for iterable T only. My first shot was
template<class T> using extract_iterator_t = typename T::iterator;
template<class T> concept iterable = requires { typename extract_iterat... | The issue is that in your primary definition:
template <class T> struct extract_iterator { using type = T::iterator; };
the failure that happens when we try to do T::iterator is outside of the immediate context of the substitution, so it is not SFINAE-friendly.
You could fix this by adding the right constraint:
templa... |
69,164,950 | 69,165,390 | Is it possible to implement the state design pattern in C++ without dynamic polymorphism? | Let's say I have following C++ code
class ControlAlgorithm {
public:
virtual void update() = 0;
virtual void enable() = 0;
virtual void disable() = 0;
};
class Algorithm_A : public ControlAlgorithm {
public:
void update();
void enable();
void disable();
};
class Algorithm_B : public ControlA... | You could use composition over inheritance. Something like below, for example.
#include <iostream>
#include <functional>
struct control_algorithm {
const std::function<void()> update;
const std::function<void()> enable;
const std::function<void()> edit;
};
control_algorithm make_algorithm_A() {
return... |
69,164,988 | 69,165,340 | Confusing Behaviors in Sorting with C++ vector | I just begin to program in C++ and I meet some confusing results when implementing a mergeSort algorithm with std::vector.
I used to program in Python and Java. It is the first time I use C++. Besides, I search for some information about reference and pointer. But it does not solve my problem.
void merge(vector<int>& a... | There are two major issues in your code:
First, your mergeSort takes its vector argument by value, which means that any action it performs on that vector will be lost when the function returns. To fix this, pass that argument by reference:
void mergeSort(vector<int>& arr, int start, int tail) // Pass "arr" by reference... |
69,165,185 | 69,165,337 | float number leading and trailing zeros format | I have a float number ranging from 0.001 up to 999.999
The question: how I can format all the range numbers like this:
0.001 becomes 000.001
0.002 becomes 000.002
0.2 becomes 000.200
1.001 becoes 001.001
9.090 becomes 009.090
99.100 becomes 099.100
Thanks
| use std stream formatters from iomanip.
Stop using printf : Why not use printf() in C++
#include <iostream>
#include <iomanip>
#include <vector>
int main()
{
std::vector<double> values{ 0.001, 0.002, 0.2, 1.001, 9.090, 99.100 };
for (const auto value : values)
{
std::cout << std::fixed;
s... |
69,165,380 | 69,166,087 | If a mutex is already locked how can pthread_mutex_lock(pthread_mutex_t *mutex); block the thread and still return a value at the same time? |
The mutex object referenced by mutex shall be locked by calling pthread_mutex_lock(). If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner.
My que... | Short answer to your question: pthread_mutex_lock(&mutex) will not return a value until the thread unblocks after it gets the lock. However, your code just sees a function call and perceives a direct return value.
Here is some more explanation.
About return values:
If function pthread_mutex_lock(&mutex) returns zero, ... |
69,165,415 | 69,165,839 | Create shared objects in container using STL | I'm trying to generate a container with shared objects.
Say, two linked list with a couple of common nodes.
L1 : {1 2 3 2 1} and L2 : {2 1}
I know if we use the Node* head and add the dynamically created objects as link, that's possible to chain common objects in both linkedlist, but is it possible to create such share... | You can use std::shared_ptr as that will keep its objects alive regardless if another std::shared_ptr pointing to the same object is deleted from a different container.
The container type isn't important for that, so you can use std::vector for example:
std::vector<std::shared_ptr<int>> v1
{
std::make_s... |
69,165,449 | 69,170,926 | Accessing intermediate armadillo object member without naming it [C++] | Using the armadillo library, one may write
// Log if this is non-finite
if ( ! averages.is_finite() )
{
arma::uvec nonfinites = arma::find_nonfinite( averages );
LOG_WARN( "There are ", nonfinites.n_elem, " of ", averages.n_elem,
" non-finite elements in the band border averages of the input signal... | Use the .eval() member function to forcefully evaluate the expression:
(arma::find_nonfinite( averages )).eval().n_elem
Alternatively, directly convert the expression to uvec:
arma::uvec(arma::find_nonfinite( averages )).n_elem
|
69,165,485 | 69,165,534 | Passing r values by reference? | I frequently write functions that take arguments by non-const reference, but the downside is that I can't pass r-values.
A colleague of mine showed me this piece of code which supposedly solves the problem:
#include <iostream>
// example function
int f(int& x) {
x += 5;
return x;
}
// is this undefined behavi... | Temporaries are destroyed (except some exceptions) when full expression is finished.
So you are fine here.
More details about lifetime:
All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects w... |
69,165,516 | 69,165,577 | Insert node of linked list at the end but program keep crashing | As the title say, I tried to insert node of linked list at the end but C++ program keep crashing
class SymbolTable
{
struct Node
{
string id;
int num;
string str;
Node *next;
};
public:
SymbolTable() {}
void insert(string id);
private:
Node head = { "head", -99, "", nullptr};
};
void Sy... | I do find few problems, first of all in-class definition you declared function insert as:
void insert(string id, string type);
however, when you declare a function outside of it you skipped 2nd argument:
void SymbolTable::insert(string id);
I don't understand how this code would even compile.
I also fixed algorithm i... |
69,165,930 | 69,166,123 | Is it bad practice to use an abstract base class to enforce a common interface for a template parameter type? | I'm new to template programming, and have stumbled upon this idiom. For example, something like:
class FooBase {
public:
virtual void do_something() = 0;
};
template <class Foo> // Foo is derived from FooBase
void g(Foo& foo) {
static_assert(std::is_base_of<FooBase, Foo>::value);
// ...
foo.do_something();
... | It's bad practice because you're using the wrong tool for the job. You're writing code that is communicating the wrong things, and with no actual enforcement mechanism.
The point of dynamic polymorphism is that it's dynamic: defined at runtime such that you can pass objects to functions that don't fully know the type t... |
69,166,448 | 69,172,543 | Flush sink writer to prevent loading all samples into memory? | Is it possible to flush the current progress of the sink writer to file? Similar to IMFSinkWriter::Finalize, but allowing samples to still be written. Currently, I have to write all samples to the SinkWriter then finalize. However, this means all samples are required to be loaded into memory.
I am writing compressed H2... | Media Foundation sinks are not supposed to load samples into memory and hence the tagline question is incorrect in first place. There is no direct answer for this, or, if a short answer is needed, then the answer is "No".
Important part behind this challenge is the structure of the produced data stream (typically a fil... |
69,166,564 | 69,943,132 | consteval with templates possible? | I am trying to make some templated version of consteval functions, I am not clear if there are any restrictions here.
template <typename T>
consteval T max(const T& a, const T& b) {
return (a > b) ? a : b;
}
template <typename T>
consteval T mid(const T& a, const T& b, const T& c) {
T m = max(max(a, b), c);
... | As pointed out by, @cigien this is indeed a clang bug. It works fine with gcc.
|
69,166,580 | 69,166,910 | C++ Override Template class virtual function in Template class | I am trying to override functions in my program in the method below but when compiling it shows variable1 as undefined in the Derived clear function.
I have been able to get this to work when changing the derived class to a non-template, but then I am missing the DATATYPE and VALUE variables when initiating the templat... | A compiling version of your code:
template <typename data_t, short value_v>
class Base
{
public:
Base() = default; // <== was missing impl, set to default
virtual ~Base() = default; // classes with virtual methods must have virtual destructor
virtual void clear() = 0;
protected:
int... |
69,166,863 | 69,167,412 | How to put stream operator<< outside of templated class body, via `friend`? | I have a templated class, and I am trying to create a stringifier for a nested enum.
I can get it compiling and working if I inline the operator<< code directly into the body of the class, but I'm trying to put it in a separate impl.hpp file, for legibility.
But, I can't get it to compile. It seems like it should be po... | The friend functions here are just that: non-template functions stamped out by the class template. As such, there’s no way to define them en masse, although you could define individual versions like
std::ostream& operator<<(std::ostream &os, Foo<int>::State s) {…}
std::ostream& operator<<(std::ostream &os, Foo<float>:... |
69,167,015 | 69,237,576 | Getting base address of dll of specific process using JNA | Updated: See updates at the bot of the question
I would like to get base address of game.dll which is inside war3.exe process.
I'm trying to do it via JNA library version 5.9.0, but no success.
The issue I faced with: I can't get game.dll module from war3.exe process.
I tried to get it using:
int pid = getProcessId("W... | Finally I found solution, but not in Java or JNA.
I wrote this code using C++ and I will use it like dll in Java.
Here is my C++ code:
#include <conio.h>
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#include <psapi.h>
using namespace std;
DWORD_PTR GetProcessBaseAddress(DWORD processID)
{
DWORD_P... |
69,167,215 | 69,167,280 | Using enum class values in constexpr branches | the code below prints val2 on both f() calls. What would be a proper way to execute specific branch in f() based on enum value ?
enum class E
{
val1,
val2
};
using val1_t = std::integral_constant<E, E::val1>;
using val2_t = std::integral_constant<E, E::val2>;
template <typename T>
void f(T t)
{
if co... | If you move the enum into the template parameter, then you could use
template <E val>
void f()
{
if constexpr (val == E::val1)
{
std::cerr << "val1\n";
}
else
{
std::cerr << "val2\n";
}
}
And you would use it like
int main()
{
f<E::val1>();
f<E::val2>();
}
|
69,167,521 | 69,168,473 | Evaluate multi digit expression | I wrote this code to evaluate postfix expressions, but in this code I can only evaluate an expression with only single-digit numbers. I want to edit this code for it to evaluate multi-digit numbers. How can I do this?
#include <iostream>
#include <stack>
#include <string>
using namespace std;
float calc(float o1,floa... | For multi-digit numbers, you need a separator symbol eg. space. All the tokens in postfix will be space separated. You need to read one token at a time.
For example, expression "28 2 / 5 -" can be evaluated as follows:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
float calc(float o1,flo... |
69,167,574 | 69,169,426 | Calling c++ function (bcb6 dll/lib) function from 10.3 project | I've encountered a very confusing phenomenon trying to call a function of a borland c++ builder 6 dll defined as _declspec(dllexport) in combination with a nested struct pointer parameter.
The struct declarations contain AnsiString, std::string and std::vector members, and it did work when I was calling the dll from a ... | You simply can't use non-trivial types across a DLL boundary, such as AnsiString, std::string, std::vector, etc. It is just not safe to do, in any version. Differences between DLL and EXE in terms of compilers used, configurations like alignments, memory management, etc all affect compatibility. Even when the EXE an... |
69,168,543 | 69,168,643 | how to debug a clang C++ compiler bug? (clang frontend command failed with exit code 139) | I'm repeatedly running into clang 12.0.1 compiler bugs when trying to integrate a rather complex library using c++20 features in an existing code base. The library itself has thorough unit tests which compile correctly and I'm having problems recreating the bug in any reasonably small example. It seems that it only tri... | I suggest getting the preprocessed source code that triggers the error (i.e. a single C++ file without #include or any other preprocessor statement), along with the corresponding command line for clang that attempts to compile the source code. Then you can simplify both the source code and the command line one step at... |
69,168,816 | 69,170,942 | How to pass static method of the class as deleter for std::unique_ptr? | I have been trying to pass a static method of following class as deleter of unique_ptr but I couldn't figure out the correct syntax.
Please excuse if the below syntax is horribly wrong as I just started hands on with unique_ptr.
#include <iostream>
#include <memory>
class Singleton {
public:
static void deleter... | There is no need to store both type and value. The type can do the dispatching.
In c++11 you can just write this toy:
template<class F, F f>
struct call_t {
constexpr operator F() const{ return f; }
};
which magically works. (When you invoke it with (), C++ looks for a conversion to function pointer). This is an ... |
69,169,118 | 69,169,342 | Is `sizeof(T)` with an incomplete type a valid substitution-failure as per the C++ Standard? | I've seen it come up a few times on StackOverflow and elsewhere that decltype(sizeof(T)) can be used with std::void_t to SFINAE off of whether T is complete or not. This process is even documented by Raymond Chen in Microsoft's blog titled Detecting in C++ whether a type is defined with the explicit comment stating:
I... | "Shall not be applied" means that it would normally be ill-formed. In an SFINAE context, if something would normally be ill-formed due to resulting in "an invalid type or expression", this becomes a substitution failure, as long as it is in the "immediate context" (C++20 [temp.deduct]/8) and not otherwise excluded from... |
69,169,119 | 69,185,680 | How to join range of ranges? | How to join range of ranges?
auto points() const
{
auto ranges = children() | std::views::transform([](auto child) { return child->points(); });
return std::views::join(ranges);
}
Can`t use points at
for(auto& pt: points())
Error no operator "!=" matches these operands
| Everything depends on what exactly children() and child::points() return.
If children() returns a container by value, then you are creating an adaptor (via piping with |) that is dangling - its iterators cannot be dereferenced.
In addition, child::points() must return a view. Returning a container won't work.
Here is a... |
69,169,123 | 69,169,328 | Variant of variants in C++ | I have the following variant
std::variant<Type1, Type2<subType1>> myVariant;
Type2 is a template class, there are 2 possible sub types subType1, and subType2 are possible.
Is the following supported?
std::variant<Type1, Type2<std::variant<subType1,subType2>> myVariant;
If yes, how would get<index>(myVariant) work with... | The problem is that a std::variant is a new type and is distinct from all the types it can hold. Just like a good old union:
union int_or_double {
int i;
double d;
};
which is neither an int nor a double but a distinct type that can hold either an int value or a double value.
So here std::variant<Type1, Type2<... |
69,169,267 | 69,169,728 | How to skip choosing folder in microsoft pdf printer? | I use MFC and understand how to skip configuration menu (set pInfo->m_bDirect to false). But I want to set the folder and filename programmatically, without a special dialog. If it is impossible, can you advise me about a PDF printer with this functionality (may be changing configuration file for this goal)?
| One question at a time, has limitations so here goes.
Q.) I want set folder and filename programmatically without special dialog.
A.) If you look at the output port of a recent windows installation of Microsoft Print To PDF
You may note it is set to PORTPROMPT: and that is exactly what causes the request for a filenam... |
69,169,417 | 69,169,942 | How does this backtracking code ensure that the two strings don't have common elements? | I am trying this question on LeetCode:
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindro... | The code ensures disjointness because the two recursive steop blocks in helper do not ever pull the same character into both s1 and s2.
Firstly, each call to helper will not return until processing the string until the end, including all the recursive cases which that triggers. Then the pop_back will return the respect... |
69,169,909 | 69,177,436 | Reparenting wm and BadWindow errors | I'm writing a reparenting window manager in XCB and C++:http://ix.io/3yNo
At the moment it works pretty well, but occasionally when I close a window, all the windows of that application close because the process exits with a BadWindow. For example if I have a couple xfce4-terminal windows open, all managed by one proce... | Your link contains almost 500 lines of code. I am not going to try to fully understand that. Instead, I'll just randomly guess.
auto window_manager::handle_unmap_notify(xcb_unmap_notify_event_t *ev) -> void {
if (unmap_ignore > 0) {
unmap_ignore--;
return;
}
client *cl = nullptr;
size_t idx = 0;
for (... |
69,170,019 | 69,171,447 | Can't Implement Method in Subnamespace For Derived Class | Dotnet dev with embedded C experience here moving into cpp land to give you an idea of my experience/knowledge.
I've got a base class Window in src/Core/Window/:
namespace Pyrite::Core::Window
{
class PYR_API Window
{
public:
using EventCallbackFn = std::function<void(Pyrite::Event&)>;
virt... | First, the separation between source files and namespaces in C++ is a feature in that they can follow the same structure if appropriate but other organizations are also possible. Beyond that, it’s impossible to do (literally) what you ask, because it produces weird “siblings” for name lookup that are considered to be ... |
69,170,031 | 69,170,095 | Why is this example using memcpy to convert uint8_t* parameter to a structure? | I was using a TCP library that has an incoming data handler with the following signature:
static void handleData(void *arg, AsyncClient *client, void *data, size_t len)
When I tried to cast the data like the following the access the field values of the structure, the board crashed.
MyStructure* m = (MyStructure*)data;... | Without the full picture of the lifetimes of all the data, it's hard to say what's going wrong in your particular case. Some thoughts:
uint8_t *bytes;
...
MyStructure* m = (MyStructure*)bytes;
What the snippet above is doing is using m to interpret the region of memory pointed to by bytes as a MyStructure. It's import... |
69,170,038 | 69,236,008 | Possible encoding issue between PS and C++ | I have a C++ program written using Qt that I'm using as a front end to create AD accounts. Essentially I launch an elevated process that executes PowerShell commands within an elevated PowerShell session. I can create the accounts fine but when I attempt to pull membership from a pre-existing user to copy it over to th... | I was able to resolve the issue. I found that when I pulled the so called template user from the QComboBox it contained a carriage return. I had written the logs to a text file and found it was pushing it to the next line; so the $tmpusr was broken. I was able to resolve the issue by modifying the duser.template_user v... |
69,170,151 | 69,170,234 | How can I instantiate C++ class A in the constructor of class B such that its object is available to the member functions | Most of my background is in Python and I am trying to re-learn C++ as it applies to micro-controller boards like Arduino.
I have created a standalone C++ class named DigitalGPIOPin. I also have another class named DigitalRGBPin that will need to instantiate 3 objects of the DigitalGPIOPin class in the constructor and ... | You have declared red_pin, green_pin, and blue_pin as local variables inside of your DigitalRGBPin() constructor. As such, the compiler error is correct - they are not in scope for initialize_rgb_pin() (or any other method of DigitalRGBPin) to access.
You need to make them be members of the DigitalRGBPin class (just a... |
69,170,408 | 69,170,509 | C++ throwing error "terminate called after throwing an instance of 'std::bad_alloc'" | I'm trying to run the following code, which should get user input, place it in a string, copy that string over to an array of chars, extract the first character to another array of chars, and finally get the rest of it after a space to an array of ints. But, it throws an error and I can't tell why:
terminate called af... | Think real hard about what this piece of code is doing:
temp = new char[name.size()-2];
name = name.substr(2,name.length());
name.copy(temp, name.size() + 1);
If name.size() is less than 2 characters, the new[] is invalid. But even if name.size() were greater than 2, say 5, then you would allocate temp as only 3 char... |
69,170,563 | 69,170,603 | Creating the execv argument array when the arguments are unknown at compile time | I am trying to revive an in-house CAM application, i.e. get it to compile on a current gcc so I can maintain it. I have 27 years of experience as an occasional C/C++ hack ;-)
The part in question is the command-line core, so no UI. It has a sort of front-end that does some checking and manipulation of its input argumen... | Change the type of the array to char *[], then you can assign to each array member before passing it to execv.
This is allowed because a char *[] can be converted to a char * const[] but not a const char *[] or const char * const[]
|
69,170,833 | 69,170,909 | How to use non ascii characters in CMake add_executable | For example, in CmakeLists.txt:
add_executable( ❤ test.cpp )
Will cause:
CMake Error at CMakeLists.txt:37 (add_executable):
The target name "❤" is reserved or not valid for certain CMake features,
such as generator expressions, and may result in undefined behavior.
I think useing non-ascii characters today is qui... | Your options are limited with what you can use as target names, but you have much more flexibility with the OUTPUT_NAME property.
Working example:
add_executable(heart test.cpp)
set_target_properties(heart PROPERTIES
OUTPUT_NAME ❤
)
Output:
$ make
[ 50%] Building CXX object CMakeFiles/heart.dir/test.cpp.o
[100%] L... |
69,170,923 | 69,171,107 | c++11: Why a in-class initialization of a static constexpr not a definition? | Consider the simple following:
#ifndef TEST_H
#define TEST_H
class Test {
public:
static constexpr int a = 1;
}
#endif
Note:
There's no ODR violation due to the macro.
Why the constexpr static int a not considered a definition since it's defined in the class Test? Because it's not a definition, hence it needs t... |
Why a in-class initialization of a static constexpr not a definition?
Because of One Definition Rule (ODR). The rule says that there must be exactly one definition of each non-inline non-member and static member variable. Class definitions, due to their nature, are typically included into multiple translation units. ... |
69,170,946 | 69,177,607 | Thread creation on a derived class method results in error | I have an abstract class as follows:
class AbstractClass : public std::enable_shared_from_this<AbstractClass> {
public:
virtual ~AbstractClass() = default;
virtual bool Start() = 0;
virtual void Stop() = 0;
};
This is the derived class:
class DerivedClass : public AbstractClas... | Your code is not selfcontained, so we have to guess things. Here's what I think you would have/want:
Live On Coliru
#include <boost/thread.hpp>
#include <memory>
#include <iostream>
class AbstractClass : public std::enable_shared_from_this<AbstractClass> {
public:
virtual ~AbstractClass() = default;
virtual... |
69,171,267 | 69,171,310 | how to use default arguments in c++? | in python I can write:
def test(a, b=None):
if b is None:
return
else:
print(123)
in cpp, it's better to avoid pointers, so I use reference instead,
so how to do the same thing?
#include "stdio.h"
void test(int a, const int &b) {
// how to check ?? since b should not be nullptr
printf("1... |
in cpp, it's better to avoid pointers, so I use reference instead
References can't refer to NULL, so pointers are the traditional way to do this, e.g. void test(int a, const int *b=NULL). Much of the reason references are encouraged over pointers is because it saves you from handling NULL arguments; if you need NULL ... |
69,171,751 | 69,172,077 | Using callbacks in C++ | I'm working on a project in C++, but at some point in the application it fails and generates a core dump. The application uses a couple of classes, which for the purposes here I'm concentrating on one of the classes, which I'm calling A, and is instantiated as object a. This has a large number of member functions, of w... | Callback, in simple words, is some function that will be called later at some point. Example:
void callback_fn(int a);
using callback_t = (void)(*)(int a);
void some_func(callback_t);
You can use some_func() like so:
some_func(callback_fn);
Full example here: https://godbolt.org/z/ET3GhfYrv
For your usecase the para... |
69,172,748 | 69,179,357 | Convert DDMMMYY[25JUN20] to YYYYMMDD[20200620] in c++ | '''
int main()
{
struct std::tm tm;
std::istringstream ss("25JUN20");
ss >> std::get_time(&tm, "%e%b%y"); // or just %T in this case
std::time_t time = mktime(&tm);
std::cout << tm.tm_year << std::endl;
}
'''
I tried using this code, but my year gets skewed.
Any help would be appreciated.
Thanks
|
Even a simpler solution to my problem would able be appreciated @S.M. –
sparsh jain
This is very simple using Howard Hinnant's C++20 chrono preview library (open source, header-only).
#include "date/date.h"
#include <chrono>
#include <iostream>
#include <sstream>
int
main()
{
std::istringstream ss("25JUN20");
... |
69,172,885 | 69,172,975 | When should I delete the std::string returned from std::smatch inside a regex iterator, if at all? | I'm new to C++, and I have been playing around with its standard regex library. I made this proof of concept search function based on the following reference.
https://en.cppreference.com/w/cpp/regex/regex_iterator
This code compiles fine and runs as expected, but looking in retrospect, there are a couple of spots I'm w... |
When should I delete the std::string returned from std::smatch inside a regex iterator, if at all?
You only delete pointers. More specifically, you delete pointers that were returned by a (non-placement) new expression.
match.str() doesn't return a pointer. It returns an instance of std::string. You don't need to, an... |
69,173,117 | 70,623,666 | Substitution failure in an atomic constraint of template function requires-clause | Constraints in C++20 are normalized before checked for satisfaction by dividing them on atomic constraints. For example, the constraint E = E1 || E2 has two atomic constrains E1 and E2
And substitution failure in an atomic constraint shall be considered as false value of the atomic constraint.
If we consider a sample p... | This is Clang bug #49513; the situation and analysis is similar to this answer.
sizeof(T)>0 is an atomic constraint, so [temp.constr.atomic]/3 applies:
To determine if an atomic constraint is satisfied, the parameter mapping and template arguments are first substituted into its expression. If substitution results in a... |
69,173,141 | 69,173,180 | String not working with if else statement | I'm creating a BMI calculator that works in the English and Metric systems. I'm not really sure what's going on, but no matter what I input it only goes to the first conditional.
#include <iostream>
using namespace std;
int main()
{
int weight;
int height;
string measurementSystem;
cout << "Metric ... | On lines 17 and 22, you must include the name of the variable in the second clause of the OR operator. E.g.
if (measurementSystem == "metric" || measurementSystem == "Metric") {
Without this, the bare string Metric will evaluate to true, because it is non-zero.
|
69,173,301 | 69,173,316 | Calling base class' constructor without defining it in derived class | class A {
public:
int _a
A(int a) : _a { a} { }
};
class B : public A { }
Why can't I initialize a variable of A type with using the inherited constructor?
B a(5);
Error: "No matching constructor for initialization of 'B'"
| Because B doesn't have such a constructor taking int by default, unless inherit it explicitly:
class B : public A {
using A::A; // inheriting constructor
};
|
69,173,814 | 69,174,141 | ImportError: libopencv_hdf.so.4.5: cannot open shared object file: No such file or directory | This question has been asked many times here. but I tried all the answers so far but nothing worked. this is the code I am trying to run.
#!/usr/bin/env python3
import rospy
from sensor_msgs import msg
import cv2
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridge... | Basically as you said you tried installing opencv for c++ and after getting errors you came back...
Try removing opencv completely from your system
This resource may help. Afterwards install opencv using pip. You can install opencv in a virtual environment to keep both libraries aside. If you have such a usecase.
pip3 ... |
69,173,906 | 69,174,444 | reducing time complexity of compare two characters in one single string in c++ | I have to compare first letter of a string with other letters of string in c++
for ex: in "bsadasdaddgkoj"
i have to compare b i.e first letter to all other letters and see if it is alphabetically smaller
but i have to do this really quick
vector<string> possibleChanges(vector<string> usernames) {
int n=usernames.size(... | Let's assume that you really need answers as strings...
vector<string> possibleChanges(const vector<string>& usernames) {
const size_t n = usernames.size();
vector<string> answers(n, "NO");
for (size_t i = 0; i < n; ++i) {
auto firstChar = usernames[i][0];
auto it = std::find_if(usernames[i].begin() + 1, use... |
69,174,365 | 69,174,463 | to how many subroutines can x86 processors call? | i'm writing a small program to print a polygon with printf("\219") to just see if whatever i'm doing is right for my kernel. but it needs to call many functions and i don't know whether x86 processors can accept that many subroutines and i can't find results in google. so my question is will it accept so many function ... | Your function depth is not limited by the processor, but by the size of your stack. Behind the scenes, calls to C++ functions usually translate to call instructions in x86, which push four (or eight, for x64 programs) bytes onto your program's stack for the return pointer. Sometimes calls are optimized and don't touch ... |
69,175,738 | 69,214,749 | gRPC Server shutdown hangs forever | Hello i have gRPC Asynchronous Server written in C++.
I'm receiving rpc with AsyncNext that is ruining in it's own thread and currently it has deadline of 16ms.
i'm using suggested shutdown procedure
Server->Shutdown();
Que->Shutdown();
DrainQue();
Under normal conditions everything works fine, but when client sends r... | Turns out the the requests can be canceled with Context.TryCancel(); and in progress rpcs can be ended with Responder.FinishWithError(grpc::Status::CANCELLED, this);
Also i was not using AsyncNotifyWhenDone
|
69,176,330 | 69,176,390 | error: cast from 'char*' to 'int' loses precision [-fpermissive] on using reinterpret_cast (C++) | I was trying out the different casting operators in C++.
In my understanding of reinterpret_cast, it converts don't type into a fundamentally different type.
But the following piece of code throws this error "cast from 'char*' to 'int' loses precision [-fpermissive]".
#include <iostream>
#include <typeinfo>
using names... |
What does the error mean?
Most importantly, the message means that the program is ill-formed. A conversion from the type char * into the type int is not defined in the language (in this case).
The message also contains extra detail "loses precision". From that we can deduce that there can be more memory addresses rep... |
69,176,650 | 69,176,974 | QListView not showing data in model | When I run the program, the list view doesn't show the data in the model I've set up. What am I missing/where am I going wrong?
QStandardItemModel mymodel(this);
QStandardItem *item1 = new QStandardItem("This is item one");
item1->setData("item", Qt::UserRole + 1);
mymodel.appendRow(item1);
QStandardIt... | Thanks to @vahancho - you should allocate from heap. Here's the revised snippet:
QStandardItemModel *mymodel = new QStandardItemModel(this);
QStandardItem *item1 = new QStandardItem("This is item one");
item1->setData("item", Qt::UserRole + 1);
mymodel->appendRow(item1);
QStandardItem *item2 = new QSta... |
69,176,769 | 69,176,856 | Can a pointer be decleared as void storing chars? | char* pointer = new char [5];
strcpy_s(pointer,4, "foo");
I am not fully understanding how pointers work. In my understanding the variable pointer is supposed to store the starting address of the new allocated string of chars. If so why is it important that the pointer is a char since its only storing an address.
why ... | the pointer needs to know the size of its element, thanks to it you can use [] operator to reach a certain element of the array, how else would it know how much memory it has to move to get to the n-th element? If you could declare a pointer to any type as void, then it would have to automatically deduce the type it po... |
69,177,143 | 69,177,826 | Boost serialize boost::array failed | I'm trying the examples of this link: https://theboostcpplibraries.com/boost.serialization-wrappers
But the example that directly serialize boost::array compile failed:
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <sstream>... | The global variable ss raises red flags. Sharing in that way may have unintended consequences:
for one, residu content maybe remain
more subtly, there might not be a flush when required.
Besides that, it looks like you're missing the include for array serialization:
#include <boost/serialization/boost_array.hpp>
Add... |
69,177,272 | 69,177,401 | Simple C++ loop takes up entire RAM | I was doing some coding on C++ just to get used to its syntax (I'm Java developer). However, I've written the code below and it takes up the entire RAM in seconds, the more free RAM you have, the faster program takes it up. When I uncomment the cout method to print current string at the end of every loop, it starts to ... | The reason why this is happening is simply fact that i/o operations are really slow compared to appending list. Therefore this seemed to be work "okay". This loop is just infinite, never stops.
|
69,178,005 | 69,180,533 | Passing std::string as input to getopt() | I have a program that basically looks like this:
#include <iostream>
#include <unistd.h> // getopt
#include <vector>
#include <string>
#include <list>
#include <sstream>
using namespace std;
//a parameter structure to store parameters provided through console
typedef struct pairwise_param {
double alpha;
doub... | Using wordsexp.h solved the issue by parsing the string correctly for getopt().
Essentially:
//create string and pass it to maincomp
std::string cmd = "-a2.3 -b3.2";
//convert string with wordexp
wordexp_t newargv;
newargv.we_offs = 1;
wordexp(cmd.c_str(), &newargv, WRDE_DOOFFS);
//create a new argc
int newargc = ... |
69,178,223 | 69,178,279 | A const member function can not deduce parameter type | Here is the code:
vector<ClientInfo*> OpenRABiz::GetHumans() const {
vector<ClientInfo*> vec;
for (auto &c : clients) {
if (!c.isbot) {
vec.push_back(&c);
}
}
return vec; // RVO - return value optimization
}
In visual c++ 2019, compiler indate it:
error C2664: 'void std::vec... | Your clients is likely a vector of ClientInfo, so in a const-qualified member-functions, the type of client (in the loop) is const ClientInfo&. When you take the address &client, you get a const ClientInfo*, which cannot be converted to a ClientInfo*.
When you remove the const-qualifier, everything works fine because c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.