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 |
|---|---|---|---|---|
68,354,057 | 68,356,206 | std::tm to std::time_t conversion gives error for a specific date before 1970 (c++) | I'm currently trying to store birth dates via time_t. For that purpose, I'm also using std::mktime and std::tm. However, when I try to convert a specific date from std::tm to std::time_t, it returns -1, which indicates that the conversion was not successful. I know that Unix timestamps should store the number of second... | If you're interested in storing dates as a count of days using the date1 library, here's what it would look like:
#include "date/date.h"
#include <cassert>
#include <chrono>
#include <iostream>
int
main()
{
namespace chr = date;
// namespace chr = std::chrono;
int year = 1914;
int month = 1;
int day ... |
68,354,435 | 68,398,127 | Build large sparse matrix from several smaller sparse matrices | I am using the Eigen library to solve a FEM problem in which I use several similar sparse matrices for the different kinds of derivatives I calculate. To build the sparse matrix to solve the system I would like to use the comma initializer, but that is not supported for sparse matrices (https://eigen.tuxfamily.org/dox/... | The problem comes from the fact that the matrices I used in the Kronecker product were of type SparseMatrix<int> and SparseMatrix<complex<double>>. There are no operator overloads for int and complex<double>, so by making both matrices of compatible types, the code compiles and runs as expected.
|
68,354,790 | 68,354,854 | guessing game while loop not looping | #include <iostream>
using namespace std;
bool play_game(int n) {
int guess;
bool noguesses = false;
int numofguesses = 0;
cout << "Welcome to my number guessing game\n";
while (n!=guess && !noguesses)
{
if (numofguesses < 6)
{
cout << "\n";
cout << "Enter... | Remove return false;
if (numofguesses < 6)
{
cout << "\n";
cout << "Enter your guess: ";
cin >> guess;
cout << "\n";
cout << "You entered: " << guess;
numofguesses++;
return false; //Remove this line
}
|
68,354,929 | 68,366,630 | Indices Problem with a Batch Renderer (OpenGL) | I'm trying to implement batch rendering for 3D objects in an engine I'm doing, and I can't manage to get the indices fine.
So in a 3D Renderer class I have a Renderer3DData structure that looks like the next:
static const uint MaxQuads = 20000;
static const uint MaxVertices = MaxQuads * 4;
static const uint... | I finally solved it (I'm crying, I've been with this a lot of time).
So there was a couple of problems:
First: The function s_3DData->IBuffer = IndexBuffer::Create(indices, s_3DData->MaxIndices); that I posted was doing the next:
glCreateBuffers(1, &m_BufferID);
glBindBuffer(GL_ARRAY_BUFFER, m_BufferID);
glBufferData(G... |
68,354,973 | 68,355,051 | Implementing square() without using the multiplication operator | Task:
Implement square() without using the multiplication operator; that is, do the
x*x by repeated addition (start a variable result at 0 and add x to it x times).
Then run some version of "the first program" using that square().
Solution #1:
#include <iostream>
int square(int x){
int result = 0; // same o... | Solution #1
You don't return result, thus you calculate it but never return it
i.e.
#include <iostream>
int square(int x){
int result = 0; // same output of we declare result without initializing
for (int i = 0; i < x; i++) {
result += x;
}
return result;
}
int main()... |
68,355,352 | 68,355,558 | How to use template for implementing STACK using LINKEDLIST in cpp | So i am trying to create a c++ file which implements stack and all its functions(push,pop,getTop,etc). I want to use Template so that i can make this Stack class for multiple datatypes. I am using linked list to store the data. Here is some example of stack i have implemented using linked list.
#include<iostream>
using... | I suggest making the Node into an inner class of Stack. There's no need for users to be able to see it.
#include<iostream>
#include<utility>
template<class T>
class Stack {
struct Node { // inner class
T data;
Node *next;
};
Node* top = nullptr;
size_t m_size = 0;
public:
Stack()... |
68,355,477 | 68,355,540 | How to capitalize the first letter of each name in an array? | Here is the question:
Create a function that takes an array of names and returns an array where only the first letter of each name is capitalized.
example
capMe(["mavis", "senaida", "letty"]) ➞ ["Mavis", "Senaida", "Letty"]
And the code I wrote to answer this question:
#include <iostream>
#include <string>
#include <ve... | To change the input argument, we have two choice: make the argument mutable reference, or add a return type, here I choose the first one.
putchar can be used to print only one character, it recommended to use cout to print a string, possible solutions:
with traditional loop: capme
with range for-loop since c++11 : ca... |
68,355,573 | 68,355,679 | Is a typedef to self allowed over template parameters | I was reading someone else's code when I came across this piece (stripped to MWE):
template<typename R> class Test {
public:
typedef R R;
};
Here there is a typedef of the template parameter to itself, and it made GCC and clang (with or without -std=c++2a) complain:
test.cc:3:19: error: declaration of 'ty... | No. The name of a template parameter is not allowed to be redeclared.
The name of a template parameter is not allowed to be redeclared
within its scope (including nested scopes). A template parameter is
not allowed to have the same name as the template name.
template<class T, int N>
class Y {
int T; ... |
68,355,586 | 68,367,885 | Meson creates build files which will not compile | I am trying to port an existing code tree to the meson build system on a centos 7 machine. Meson configure works fine, but when I try to compile, it fails. The code is proprietary, so I have created an example that illustrates the problem (accurately enough, I hope.) I am not at liberty to restructure the directory ... | I see right off the bat an issue that might just be an issue with your example, and not with your actual code: Meson considers the meson.build file with the project() call to be the "root" of the source directory structure. You cannot ask it to include files outside of the root. It would be about like cp /../foo . on a... |
68,355,670 | 68,356,079 | Dynamic type cast to the variable type | Suppose, I have a class, like:
struct A
{
uint8_t f1;
int16_t f2;
};
And I need to set it's members values from a memory buffer data, like:
uint8_t * memory=device.getBufferedDataFromDevice();
A a;
a.f1=*((uint8_t*)&memory[someAddress]);
a.f2=*((int16_t*)&memory[someOtherAddress]);
But I'd like to make it more f... | You can have a code similar to this:
template<typename T>
void mymemcopy(T* a, void* b) {
memcpy((void*)a, b, sizeof(T));
}
template<typename T>
constexpr void mymemcopy(T** a, void* b) {
*a = static_cast<T*>(b);
}
constexpr void mymemcopy(int* a, void* b) {
*a = *(int*)b;
}
constexpr void mymemcopy(unsi... |
68,355,698 | 68,369,462 | Fast solve a sparse positive definite linear system with Eigen3 | I need to solve a linear system with a sparse symmetric and positive definite matrix (2630x2630) millions of times. I have ploted the matrix in Mathematica an it's shown bellow.
I have chosen the Eigen3 lib with the LLT decomposition to solve the linear system, which compared to others methods like LU is much faster.... | You have a sparse matrix, but you're representing it in Eigen as a dense matrix. The matrix file that you have is also dense, it would be more convenient to use if it was stored in sparse form, the Market format for example.
If I change the matrix to a sparse one, and use
SimplicialLLT< SparseMatrix<double> > solver;
V... |
68,356,212 | 68,356,247 | What's the best style of Inheriting from two brothers in C++? | I need to implement several modules, like below,
#include <stdio.h>
class Base{
protected:
int data;
};
class ModeA : public Base{};
class ModeB : public Base{};
class ModeHybrid: public ModeA, public ModeB{
public:
void func(){printf("%d\n", this->data);}
};
int main(){
ModeHybrid mh;
mh.func();
}
wh... | There are at least three ways to fix this.
The first is virtual inheritance, which has overhead. In it, you only have one Base.
class ModeA : public virtual Base{};
class ModeB : public virtual Base{};
it does mean that the most-derived class you instantiate must construct Base.
Another approach is template based, wh... |
68,356,531 | 68,374,004 | Can latest version VSCode debug C++ with C++ extension and MSVC? | After updating VSC to new version(1.58.0), it nether InternalConsole nor ExternalConsole can run .EXE file automatically which is compiled successfully by cl.exe. I have configured the .JSON file while it worked well for previous version VSC. The JSON file code is below.
// lauch.json
"version": "0.2.0",
"symbolsearchp... | I have solved this problem. When user try to run or debug their program this question which VSC could not run .EXE file automatically will encounter before the extension of VSC (Windows debugger C++) not installing completely. After updating VSC, please wait for its installing completely.
For more C++ compiler configur... |
68,356,675 | 68,356,755 | c++ auto variable(map) is assigned garbage value | I tried assigning 'a' variable as follows:
for (auto& a : getMap()[1])
which assigned a garbage value to a. But if I use it after declaring the variable first as shown below, it works normally.
auto vv = getMap()[1];
for (auto& a : vv)
Why is it a problem if I use it right away without declaring a variable?
#incl... | Until C++17 (details that changed since then don't change the answer) the range based for loop was equivalent to (taken from cppreference):
{
auto && __range = range_expression ;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) {
range_declaration = *__begin;
... |
68,356,870 | 68,463,452 | Kaleidoscope tutorial cannot find header `ExecutorProcessControl.h` | To follow Kaleidoscope tutorial part 4, I downloaded the header file KaleidoscopeJIT.h. But once I include it, I get the following error
$ clang++ -g main.cpp kaleidoscope.cpp `llvm-config --cxxflags --ldflags --system-libs --libs core orcjit native` -O3 -o kaleidoscope
In file included from kaleidoscope.cpp:18:
././in... | Make sure you pull the correct files. You are using llvm-10 so you need to use the kaleidoscope tutorial from that version.
|
68,356,950 | 68,357,042 | C++ variadic template with tuple as template parameter | I would like to have something like this (warning: invalid code):
template<std::tuple<typename T, typename... Args>>
class nDimensionalPoint
This way, I could work with n-dimensional points one dimension at a time.
Of course, I could avoid the std::tuple part by declaring
template<typename T, typename... Args> and sim... | You might declare it as partial specialization as
template<typename>
class nDimensionalPoint;
template<typename T, typename... Args>
class nDimensionalPoint<std::tuple<T, Args...>> {};
then use it like
nDimensionalPoint<std::tuple<int, char>> dp ...;
|
68,356,963 | 68,357,334 | Trouble appending to a vector C++ | I am having some trouble/error appending to a vector in C++. My code is:
std::vector<int> maps(const std::vector<int> & values) {
for(int i = 0; i < std::vector.size(); i++){
values.pushback(maps[i] * 2);
}
return values;
}
My goal is to have a base list that holds some numbers, then create a new list con... | According to your question. This is what you want.
std::vector<int> maps_double(const std::vector<int> & values) {
std::vector<int> doubles;
for(int i = 0; i < values.size(); i++){
doubles.push_back(values[i] * 2);
}
return doubles;
}
But in your code, you are doing several things wrong.
for(int i ... |
68,358,020 | 68,358,690 | How to update with custom stm32 board with my owm software | I'am working with nucleo board since a while. Now I'd like to create my own board build with an stm32, but I'd like my clients to be able to update it's own board.
So let me explain my idea, first of all I create a software for my client (c++) this software will just update the board with a small GUI very simple. My id... | If I'm not mistaken, STM32 parts with USB hardware have system bootloader supporting DFU mode, except the very old models like STM32F103.
Please see AN2606 from ST and inspect the flow charts related with your STM32 device. For STM32F4 series, HSE needs to be present for USB bootloader (not sure if they are all same). ... |
68,358,294 | 68,358,421 | What is the lifetime of reference member default initializer in C++? | Please consider this short code example:
#include <iostream>
struct A
{
A() { std::cout << "A() "; }
~A() { std::cout << "~A() "; }
};
struct B { const A &a = A(); };
int main()
{
B x;
std::cout << ". ";
auto y = B();
std::cout << ". ";
auto z = B{};
std::cout << ". ";
}
GCC prints h... | Lifetime extension is not guaranteed since the code is ill-formed.
[class.base.init]/11:
A temporary expression bound to a reference member from a default
member initializer is ill-formed. [Example 8:
struct A {
A() = default; // OK
A(int v) : v(v) { } // OK
const int& v = 42; // OK
};
A a1; ... |
68,358,452 | 69,262,919 | QAudioInput: failed to open audio device | I'm try to use Qt Multimedia to open microphone and access data. I followed the official example Audio Input Example and get the following code(Just a test program, I will inject into my other project when it's okay).
Environment: Windows 10 20H2. Qt Creator, MinGW 64-bit or Microsoft Visual Studio 2019, MSVC2019 64-bi... | 16bit audio must be signed integer.
DataFormat.setSampleType(QAudioFormat::SignedInt);
|
68,358,538 | 68,359,796 | strong typedef of std::string | Motivation (Question background)
I use std::string for many meanings.
For example, address and name (in practice more meanings).
Let's say the address and name have a default value.
void set_info(std::string address, std::string name) {
// set address and name
}
void set_info(std::string address) {
// set addre... | You won't need to wrap every operation of std::string because you won't need to use them. All that the caller has to do is initialise the argument with a correct type with a value for the internal string:
struct address_type {
std::string value;
};
struct name_type {
std::string value;
};
struct info {
in... |
68,358,938 | 68,389,920 | How to set ceph dout level? | I am learning bluestore of ceph. I am trying to use the ceph_object_store to test bluestore. But I see lots of unrelated log output. But I can't see any output related to the benchmark. I found the benchmark uses dout(0) to print log. So how could I close the unrelated log output and set the benchmark to print?
Those ... | You can set the Ceph subsystem log levels to 0 and just set the log level on the needed subsystem. The full list and how to set is documented here:
https://docs.ceph.com/en/latest/rados/troubleshooting/log-and-debug/#ceph-subsystems
|
68,359,002 | 68,375,822 | How to get core dump file in docker while running ctest? | I try to run my tests in parallel using ctest in docker environment.This is the command that I execute;
ctest -R MyTest -j 10 -VV --stop-on-failure --output-on-failure --repeat-until-fail 1000
While running the tests, I get a segfault sporadically.
Test #1463: MyTest.case1...***Exception: SegFault 0.15 sec
What I wa... | Fortunately, I found gtest-parallel library in order to able to run my tests in parallel and to get a core dump file. It has limited options, though. Nevertheless, helps me to get what goes wrong. Btw, this is how I run my tests using this library.
./gtest-parallel MyTests --gtest_filter=Fixture1.* --output_dir . --rep... |
68,359,330 | 68,415,412 | gdb (MinGW) doesn't break on failed asserts (VSCode config) | I'm trying to debug a program, in VSCode, which violates an assert, but doesn't break and doesn't allow me to inspect the callstack or anything. Instead the program just exits with exitcode 3 and prints out the following text:
Assertion failed!
Program: C:\Users\Sewbacca\Projects\Practice\CppTest\build\Test.exe
File: ... | I found a solution:
gdb breaks on failed asserts, when adding the following code to setupCommands in launch.json:
"setupCommands": {
...
{
"text": "set breakpoint pending on",
"description": "Ensures that a breakpoint for abort will be set!",
"ignoreFailures": true
},
{
"text... |
68,360,168 | 68,360,580 | How unused default member initializer can change program behavior in C++? | Please consider this short code example:
#include <iostream>
struct A
{
A() { std::cout << "A() "; }
~A() { std::cout << "~A() "; }
};
struct B { const A &a; };
struct C { const A &a = {}; };
int main()
{
B b({});
std::cout << ". ";
C c({});
std::cout << ". ";
}
GCC prints here ( https://g... | C c(...); is syntax for direct initialisation. Overload resolution would find a match from the constructors of C: The move constructor can be called by temporary materialisation of a C from {}. {} is value initialisation which will use the default member initialiser. Thus, the default member initialiser isn't unused. ... |
68,360,220 | 68,360,718 | how to reverse a stack using recursion in C++ | I am trying to reverse stack without using extra space through recursion. But unable to find my error.
Here is my code. It is printing the same stack again.
#include<iostream>
#include<stack>
using namespace std;
void insert( stack<int>& k , int j){
k.push(j);
}
void reverse(stack<int> &s){
if(s.empty()){
... | Your insert() function is incorrect since you only push temp into the stack and once the stack is empty the value of temp will be 5 so 5 is pushed then 4 and so on. Hence the stack is filled in the same order. This insert() should work.
void insert( stack<int>& k , int j){
if(k.empty()){
k.push(j);
... |
68,360,727 | 68,360,802 | How to call a constexpr function which returns void by a constexpr expression? | The call to test failed to compile but test1 succeeded
constexpr void test(int n)
{
return;
}
constexpr int test1(int n)
{
return n;
}
int main()
{
constexpr test(5); // Failed
constexpr (test)(5); // Also failed
constexpr auto n = test1(5); // OK
return 0;
}
I could misuse something or it ... | Your are using the wrong syntax. The compiler gets confused because it expects that you want to declare a variable called test and complains that you cannot do that without declaring its type. This is what the compiler expects:
constexpr int test(5); // OK
constexpr int (test_x)(5); // also OK
And this is what you... |
68,361,267 | 68,362,641 | Pytorch C++ (Libtroch), using inter-op parallelism | I am working on a machine learning system using the C++ API of PyTorch (libtorch).
One thing that I have been recently working on is researching performance, CPU utilization and GPU usage of libtorch. Trough my research I understand that Torch utilizes two ways of parallelization on CPUs:
inter-op parallelization
intr... | Questions
difference between these two
As one can see on this picture:
intra-op - parallelization done for single operation (like matmul or any other "per-tensor")
inter-op - you have multiple operations and their calculations can be intertwined
inter-op "example":
op1 starts and returns "Future" object (which is... |
68,361,335 | 68,363,327 | Why doesn't setPos() work when using addPolygon() method? | Consider this class called Hex to draw a hexagon :
// Hex.h
#include <QGraphicsPolygonItem>
#include <QPointF>
#include <QVector>
#include <QImage>
#include <QBrush>
#include <QPen>
class Hex : public QGraphicsPolygonItem {
public:
// constructor
Hex(QGraphicsItem* parent = NULL);
// getters/setters
... | setPos () does not modify the QPolygonF but moves the item in scene coordinates, instead QPolygonF are drawn with respect to the internal coordinate system of the item. Therefore, if you want to observe the initial behavior, you have 2 options:
Move the QGraphicsPolygonItem:
QGraphicsPolygonItem *p0 = scene->addPolygo... |
68,361,700 | 68,368,314 | How to Scroll Parent wxScrollWindow from Inside Child wxScrollWindow in wxWidgets | Hi i am using wxScrollWindow and have 2 wxScrollWindows. Both of them works correctly individually.
First wxScrolledWindow scrolls horizontally, and the second scrollWindow scrolls vertically.
First wxScrolledWindow has the second scrolledwindow embedded inside it.
Screenshot for illustration purposes is attached belo... | I have resolved the issue by writing my own custom event class which derived from wxEvent and everything is working now as expected. That is, I am able to control the scrolling of the parent scrollwindow(horizontal) from within the child scrollwindow(vertical).
|
68,361,759 | 68,364,113 | Assign value to the first m elements of an array of size n in C++ | I have an array declared in the global scope (outside the main() function) of size n, and inside the main() I need to assign it the first m (m < n) values. How do I approach this?
#include <iostream>
using namespace std;
int array[50];
int main()
{
array = {1,2,3,4,5}; //can not execute, error
return 0;
}
... | If you are trying to initialize the array with some initial values, you have to do this immediately with the initialization, not after the initialization.
#include <iostream>
using namespace std;
int main(){
int array[50] = {1,2,3,4,5};
return 0;
}
But, if you really need to copy values, the easiest way is to co... |
68,362,450 | 68,362,585 | how to use a pointer to member function inside a static member function in c++ | I'm actually trying to use a pointer inside a static function which is in the same class as the functions that i'm trying to use inside the pointer.
I'm actually asked to use the class like this :
class Factory {
public:
Factory() = default;
~Factory() = default;
static IOperand* createOpera... | No matter where you use the member function pointer to call a method, you need an object to do so. In your "This is how I would do if this function wasn't static" version you call the method on the current object this. In the static method, you need a different object of type Factory, because there is no this in the st... |
68,362,894 | 68,363,784 | OS X console app - cannot read the arguments | On a simple application for the console I can not read the arguments
int main(int argc, char ** argv) {
if (argc > 1)
strcpy(path, argv[1]);
printf("arguments %d\n", argc);
....
Always argc is 1
Runing the application from the console it's like this:
open mytestconsoleapp --args arg1 arg2 arg3
Always argc... | You can use this if you're actually writing C++ and not C.
static std::string path;
int main( int argc, char* argv[ ] ) {
// With either solution you should make sure that the passed in
// argument isn't gigantic.
if ( argc > 1 ) {
path.assign( argv[ 1 ] );
std::cout << path << '\n'
... |
68,363,216 | 68,363,852 | Reducing duplication of template parameters in C++ | This is not a major code breaking issue, I'm just wondering if I'm missing some neat trick.
If I am writing a templated class, I may start like this:
// some_header.h
template <typename TypeParameter, size_t max_array_size>
class TemplatedClass
{
std::array<TypeParameter, max_array_size> MyTemplatedArray;
public:
... | First a non-answer:
Suppose, /*do something*/ depends on the template parameters. In that case, having to fix the signature is the smaller issue. You need to fix the implementation.
The other case is that /*do something*/ does not depend on the template parameters. Then you can move the methods to a non template base c... |
68,363,342 | 68,364,631 | Using whole stack memory | Hello I heard that in c++ stack memory is being used for "normal" variables. How do I make stack full? I tried to use ton of arrays but it didnt help. How big is stack and where is it located?
|
Hello I heard that in c++ stack memory is being used for "normal" variables.
Local (automatic) variables declared in a function or main are allocated memory mostly on stack (or register) and are deallocated when the execution is done.
How do I make stack full? I tried to use ton of arrays but it didnt help.
Using t... |
68,363,515 | 68,365,655 | GDB print variable in readable format (using << operator) | GDB is a nice tool but in the way I have been using it so far, it turns pretty useless as soon as one is working with more complex data structures because simply using print on them just fills then entire screen with unreadable details about that class.
However I usually have a custom operator<< defined for my classes ... |
it appears to me as if there must be a more convenient way of getting GDB to print variables in a readable format.
Yes: you implement a python pretty-printer for them. Documentation.
I would like to avoid having to rewrite a pretty-printer for all my classes when I already have done that in code.
The problem with c... |
68,363,557 | 68,363,696 | Nested type binding in concept fails on GCC and clang but not msvc | This code:
template<typename T, template<typename> typename Pred>
concept sats_pred = static_cast<bool>(Pred<T>::value);
template<template<typename...> typename A, template<typename> typename Cond>
struct is_container_of_helper {
template<sats_pred<Cond>... Ts>
void operator()(const A<Ts...>&) const
{}
};
... | Change last part of your code like this:
template<typename T, template<typename...> typename Contained, template<typename...> typename Container>
concept is_container_of = is_container_of_if<T, Container, is_a<Contained>::template type>;
And it compiles in clang and gcc. is_container_of_if needs a template for last te... |
68,363,717 | 68,365,590 | MSVC behaves different about default constructor of closure type in C++20 | The standard says
The closure type associated with a lambda-expression has no default constructor if the lambda-expression has a lambda-capture and
a defaulted default constructor otherwise. It has a deleted copy assignment operator if
the lambda-expression has a lambda-capture and defaulted copy and move assignment
o... | The standard is pretty clear here. In [expr.prim.lambda.closure]/13:
The closure type associated with a lambda-expression has no default constructor if the lambda-expression has a lambda-capture and a defaulted default constructor otherwise.
This rule is based on the lexical makeup of the lambda, not the semantic ana... |
68,364,226 | 68,364,647 | Why is there a memory leak in my program? | I have implemented a singly-linked-list where there is a SinglyList class, and struct node, node *head as private members of the class; and wrote a destructor to delete it. I used CRT library to check for memory leaks using _CrtDumpMemoryLeaks() method. When I debug the code, it shows in the debug console that memory l... | You print the leaks before the list gets deleted. Try this instead:
#include"SinglyList.hpp"
#include<crtdbg.h>
int main()
{
{
SinglyList nums{};
nums.Append(10);
nums.Append(20);
nums.Append(30);
}
_CrtDumpMemoryLeaks();
return 0;
}
Then, you'll show the actual leaks ... |
68,364,460 | 68,364,561 | How can I change the pointer in shared_ptr without losing the ability to delete the memory? | I faced a problem with std::shared_ptr. I have a code:
void Receive(const std::shared_ptr<char[]>& data, uint32_t length) {
this->next->Receive(data + 2, length - 2);
}
I need to increment shared_ptr by 2 without losing the ability to delete the memory.
I don't want to copy data, because the data is already in memor... | Yes, that's what the aliasing contructor of std::shared_ptr is for. It keeps the same control block, but it allows you to use another pointer.
The signature is
template< class Y >
shared_ptr( const shared_ptr<Y>& r, element_type* ptr ) noexcept;
In your case that would be
void Receive(const std::shared_ptr<char[]>& da... |
68,364,773 | 68,364,959 | Scary warnings in ancient code converting wstring to string | An old method contains code like the following (anonymised):
std::wstring wstr = ...;
std::string str(wstr.begin(), wstr.end());
Previously this all compiled without warnings but as we update to C++17 and VS2019 (v142) and tidy project settings, it now gives these big scary warnings:
C:\Program Files (... | The issue is that you are converting from a 16 bit string to an 8 bit string. Since 16 bits hold more data than 8, data will then get lost. If you are converting between UTF-16 and UTF-8, you need to do it properly with a conversion library.
C++ does provide conversion library in the form of: codecvt (Deprecated in C++... |
68,364,810 | 68,366,195 | Initial value of reference to non-const must be an lvalue when passing opencv Mat to a function | I have an Mat. I want to update the mat based on certain regions defined by a Rect. When I pass it like the code shown below I get the error mentioned.
void temp2(Mat &A){
//this function updates the value of A in the region defined by the rect.
for(i = 0 to A.rows){
Vec2f *p = reinterpret_cast<Vec2f * >(A.ptr(i))... | Doesn't this work for you?
/* Renamed arg to reflect what's happening.
Let it be A if you so wish but it's not
the original A from temp().
*/
void temp2(Mat &extractedFromA){
// Do stuff
}
void temp1(Mat &A){
Point a(0,0), b(10,10);
Rect t(a,b);
Mat extracted = A(t);
temp2(extracted);
}
You ar... |
68,365,124 | 68,365,319 | Variable initialization { } vs = | Okay, I just had a weird problem. This example requires the nlohmann json library, but someone can probably just explain this.
#include <nlohmann/json.hpp>
using JSON = nlohmann::json;
int main(int, char **) {
JSON json { JSON::object() };
json["foo"] = "bar";
}
As compared to:
#include <nlohmann/json.hpp>
us... |
Can someone explain the difference between the two initialization types? Clearly, they aren't 100% interchangeable.
For one, this is correct. There are many different types of initialisation and the two you gave here aren’t equivalent.
However, the way you’ve written them they’d not be equivalent for any type;
Type t... |
68,365,389 | 68,365,602 | How can I print what is happening in my program in debug mode | I'd like to print what's happening in my program in debug mode, but nothing should be print in release to not waste performance. My program is in C++
I'd like to see colors on what's printed. For example, if something happened that I know can lead to a major bug, I'd like to print a big red warning where I describe wha... | The closest thing to a "standard" mechanism for this would be to use the NDEBUG macro, which drives the behavior of assert().
#ifndef NDEBUG
std::cerr << "I only print in debug\n";
#endif
Most build systems like CMake will define NDEBUG when creating Release builds, so there's no additional work to do in those cases.
... |
68,365,472 | 68,365,576 | (C++) Trying to populate array with random numbers in given range, populating with the same number over and over | I'm trying to populate a simple array in C++ using a function that generates random numbers within a given range. For whatever reason it is giving me the same random number for each element. I think the problem has something to do with where I'm seeding the random variable.
Any ideas?
#include <iostream> // for user in... | As mentioned in comments, you need to call srand(time(0)); only once, just call it at start of main().
The reason is that rand() itself is just a pseudorandom generator (a simple LFSR in a lot of cases) based on its starting seed. if you reseed algorithm with same number, you will get similar sequence of number from it... |
68,365,813 | 68,365,880 | What is/does `bool c2s(int)` in Hoard? | In the source of geometricsizeclass.cpp of Hoard (the memory allocator) there a not defined function bool c2s(int).
What is it, what does it do ?
I'm trying to compile hoard as a library in VS2019, ignoring the Makefile.
| It's there in the header file:
/// Quickly compute the maximum size for a given size class.
static unsigned long c2s (int cl) {
static size_t sizes[NUM_SIZECLASSES];
static bool init = createTable ((size_t *) sizes);
init = init;
return sizes[cl];
}
|
68,366,136 | 68,366,537 | How do you manage pointers to base classes that are both extended in a derived class? | Recently, I have been abstracting and cleaning up a project of mine to get it ready for new features. I came across a design problem when I realized that I wanted to manage pointers to a graphics context and a window as abstract classes. I have searched for answers but haven't found anything satisfying yet. I have a si... | Use a shared_ptr to manage ownership of the derived class. Then use std::shared_ptr's aliasing constructor to share ownership of the derived instance through a pointer to one of the base classes. Here's what that might look like:
class base_a {
public:
int x = 1;
};
class base_b {
public:
int y = 2;
};
class ... |
68,366,593 | 68,387,007 | Regex - capture each argument in seperate capture group: [cmd arg1 arg2 arg3...] | I am trying to create a regex for detecting some commands in a text file.
These commands have the format: [cmd arg1 arg2 arg3...] and can be positioned anywhere in the file. Multiple commands may be on the same line. They are always in [] brackets and the first word should consist of only alphabetic characters, which c... |
... but I wondered if there is a solution that uses only one regex.
No, this is not possible in RegEx alone. The approach you have is a suitable workaround.
|
68,367,075 | 68,367,188 | `default` constructor with uninitialized member in constant expression | The following minimal example is rejected by both Clang and GCC for not initializing the array data-member:
class vector3
{
public:
constexpr vector3() = default;
private:
float m_data[3];
};
constexpr auto vec = vector3{};
Which yields the reasonably straight-forward error:
<source>:4:15: error: explicitly d... | Yes, it's true that in C++20, the rules were changed so that a constexpr constructor is no longer required to initialize all non-static members and base class subobjects.
Prior to C++20, we have the interesting situation that your constructor cannot be declared constexpr, but objects of the vector3 type can still be us... |
68,367,135 | 68,367,341 | Should I use an Object Oriented workflow for Vulkan core? | Despite beeing written in C++, the famous vulkan tutorial stick everything in one class with functions using class members like global objects. I understand why such a tutorial don't enforce an object oriented workflow to focus on the API mechanics and let engine programmers setup their own workflow. But even CLion com... | Vulkan has pro and cons versus OpenGL, it is not a replacement. Both libraries are in active development by Khronos, and will continue to do so.
Cons are obvious: Vulkan is much more wordy to do even basic things. From resizing a window requiring reconstructing all (most) your objects, to extremely limited number of ac... |
68,367,258 | 68,367,316 | class TC_JOIN (NAME) {} | I found the following code here:
class Cipher {
...
};
#define TC_TRIAL(NAME, BLOCK_SIZE, KEY_SIZE) \
class TC_JOIN (Cipher,NAME) : public Cipher { \
...\
}
TC_CIPHER (AES, 16, 32);
I am aware that this is a macro and that (NAME, BLOCK_SIZE, KEY_SIZE) are additional parameters, but after the preprocessor replaces a... | TC_JOIN is defined in VeraCrypt/src/Platform/PlatformBase.h:
#define TC_JOIN_ARGS(a,b) a##b
#define TC_JOIN(a,b) TC_JOIN_ARGS(a,b)
It concatenates the two parameter.
When you are not sure what a symbol means, then search for its definition. I saw that Cipher.h (the header you quote from) includes Crypto/config.h and P... |
68,367,610 | 68,367,878 | How to write vector<uint_8> to a file in c++? | I have vector<uint_8> data filled and want to write this data into a file using c++? Tried out but didn't find any reference.
const std::vector<uint8_t> buffer; // let's assume that i'ts filled with values
std::ofstream out("file.txt", std::ios::out | std::ios::binary);
out.write(&buffer, buffer.size());
but not succ... | You can cast the data pointer as recommended by others:
#include <vector>
#include <fstream>
int main()
{
std::vector<uint8_t> temp;
temp.push_back(97);
temp.push_back(98);
temp.push_back(99);
const std::vector<uint8_t> buffer(temp); // let's assume that i'ts filled with values
std::ofstream ... |
68,367,859 | 68,367,991 | Why exactly are void* bad in C++? What alternatives are there? | I'm working on a project to implement this Multi-Join algorithm. The code I had in mind looks something like this:
template <typename A, typename B, typename C>
vector<tuple<A,B,C>> multi_join(vector<pair<A,B>> R1, vector<pair<B,C>> R2, vector<pair<A,C>> R3)
{
void* existing = new vector<tuple<>>;
void* p1, p2,... | At any and all lines in your code, the type of existing is known and fixed.
auto va1 = propose<A>(R1, std::vector<std::tuple<>>{}); // Returns vector<tuple<A>>
auto va2 = propose<A>(R2, std::vector<std::tuple<>>{});
auto va3 = propose<A>(R3, std::vector<std::tuple<>>{});
auto AIntersect = intersect(va1, va2, va3);
au... |
68,367,903 | 68,644,926 | light view matrix in stable cascaded shadow mapping | I have recently implemented cascaded shadow maps and make it stable by following this post. Now everything works, except that when I move directional light to the top mid of the world, the shadow suddenly turns all dark. With some debugging I find that the light view matrix is causing the problem.
This is how I compute... | "Making it stable" is not applicable to a light source whose direction changes. The stability refers to the camera movement while the light source is stationary. Consequently you can choose any orthogonal up vector as a function of the lightDirNorm, and it will keep your shadows stable.
I'd also suggest staying away fr... |
68,368,421 | 68,368,443 | Using template base class template constructor in derived class | i know that you can use constructors from a base class in a derived class like
class A {
public:
A() {};
}
class B : public A {
public:
using A::A;
}
Furthermore you can use a constructor from a template base class like
template<typename T>
class A {
public:
A() {};
}
template<typename T>
class B : publi... | Two things:
template<typename T2> A() {} is unusuable as a constructor, since there is no way to deduce T2.
You can only inherit all constructors at once. You can't choose specific ones.
Other than that, using A<T1>::A; is correct.
|
68,368,504 | 68,368,543 | stack use after scope: a valid report, or a false positive? | I have found a stack-use-after-scope error in our code-base (g++ -fsanitize=address), and would like to know if that's a valid concern, and I should go and fix every occurrence of such pattern, or is it a false positive from address sanitizer?
Minimal and simplified example is as follows:
#include <string>
#include <st... | Yes, the error is correctly reported (Although BAM!!! seems to be misplaced). This line:
auto cs = str.substr(2).c_str();
declares cs as pointer to character buffer, which is removed once the temporary returned by str.substr(2) is destroyed (which happens in the end of the expression).
|
68,368,581 | 70,571,282 | What is std::expected in C++? | In one of the most respected stackoverflow answer I found an example of std::expected template class usages:
What are coroutines in C++20?
At the same time I cannot find any mentioning of this class on cppreference.com. Could you please explain what it is?
| Actually, the best way to learn about std::expected is a funny talk by the (in)famous Andrei Alexandrescu: "Expect the Expected!"
What std::expected is, and when it's used
Here are three complementing explanations of what an std::expected<T, E> is:
It is the return type of a function which is supposed to return a T v... |
68,368,679 | 68,368,727 | C++ function does not update variable |
I am currently coding a function, that has to update the value of a boolean.
For some reason though, it does not do this. Let me show you a simplified version:
main.cpp
#include <iostream>
#include "header.h"
int main(){
bool limit = true;
test(limit);
if (limit == false){cout << "hi";}
}
header.h
void test(b... | When you declare the function test as
void test(bool x);
the parameter bool x is passed by value. That is, the computer makes a copy of the variable that you pass to test. So when test updates such a variable, you are just modifying a temporary variable, with no effect on the bool limit that you pass to it from main.
... |
68,369,571 | 68,369,706 | How to output the same number of 0's for whichever x = to | For e.g. X=12 need to get the same number of 0's added to the end of the below var
The output should look something like allHeKnows = 1000000000000
For any X = single digit will display the correct output, however
Not sure how to reset, or what condition to add that in order for any X >= 10 to display the int allHeKnow... | One problem that I see initially is that once you get past 10 digits you surpass the max int value allowed by c++. You would be better off converting to a string if you are trying to reach those higher numbers.
|
68,369,577 | 68,370,838 | How to control the ABI for unions? | I am working on a SIMD wrapper for C++, the base type looks like the following union:
union u{
__m128d sse;
double c[2];
};
In the following, I want to look at the ABI for Linux.
e.g.
__m128d f(__m128d a, __m128d b){
return b;
}
compiles to
f(double __vector(2), double __vector(2)):
vmovaps xmm0, xmm... | Take a step back for a moment, and compare this:
union u{
__m128d sse;
double c[2];
};
double getx(u a){
return a.c[0];
}
u add(u a, u b) {
return { _mm_add_pd(a.sse, b.see) };
}
with this:
double getx(__m128d a){
return a[0];
}
__m128d add(__m128d a, __m128d b) {
return _mm_add_pd(a, b);
}... |
68,369,665 | 68,370,002 | Changing constexpr to consteval results in unintelligible error message in MSVC. Compiler bug or questionable code? | I have the following template / compile-time utility helper functions. It works fine in all three compilers (MSVC, GCC, clang) when everything is constexpr, but changing a few bits to consteval results in an odd error in MSVC. I want to migrate all my constexpr machinery to consteval as much as possible, and this probl... | The same error occurs with all the guts removed.
#include <optional>
[[nodiscard]] consteval std::optional<size_t> index_for_type() noexcept
{
return 1;
}
static_assert(index_for_type() == 2);
This leaves me to believe that Microsoft's std::optional is simply not consteval-ready yet.
|
68,369,666 | 68,370,108 | Why does std::optional have a special equality operator for operand of the type std::nullopt | The class template std::optional has the conversion constructor
constexpr optional(nullopt_t) noexcept;
So a question arises why is there declared the special single equality operator in the C++ Standard
template<class T> constexpr bool operator==(const optional<T>&, nullopt_t) noexcept;
when std::nullopt is used onl... | You are looking at the C++20 draft. Drafts no later than N4820 had all the equality operators. They were later removed [likely] because of the introduction of rewritten candidates.
|
68,369,923 | 68,369,977 | Using abstract virtual function in c++ Interface implemented by other parent class | Im trying to define an interface (abstract class) which will "automatically" register any instance created to a global map, where the key is an uint8_t and the value is a pointer to the interface class.
All classes that will implement this interface already have a method to retrieve a unique id with a getId() method. I... | Virtual dispatch doesn't start using the derived-class function overrides until construction completes: at the time you hoped getId() would use the derived-class override, only part of the abstract base class had been constructed - the derived object didn't exist to have its functions called.
You can have derived class... |
68,371,086 | 68,372,449 | Rapidly adding int to vector and clearing causes access violation | This is some code that is designed to be run inside a .dll. If I remove either of my calls to NumberSystem::AddZero or NumberSystem::Clear, the code executes without crashing. I have been stuck for 5 hours. I am sure that something just went right over my head. Any help is appreciated!
Code:
#include <iostream>
#includ... | Your code reuses same Numbers variable from multiple threads.
I mean, DllMain callback is called multiple times with different dwReason parameter values.
You can prevent that with something like:
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID pReserved)
{
// Checks reason for being invoked.
if (... |
68,371,168 | 68,371,845 | How can I get around the use of VLAs? | I have made some code and need to make the length of an array the same as a user input:
#include <iostream>
#include <string>
using namespace std;
void abrev(string word) {
int lastChar = word.length();
if (lastChar > 10) {
cout << word[0];
cout << lastChar - 2;
cout << word[lastChar -... | It's mostly duplicated, to resolve the error, it's easy to fix it with std::vector
Since the function abrev doesn't change the argument, it's better to use a const reference.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void abrev(const string& word) {
int lastChar = word.length();
... |
68,371,252 | 68,371,336 | Why is there such a massive difference in compile time between consteval/constexpr and template metafunctions? | I was curious how far I could push gcc as far as compile-time evaluation is concerned, so I made it compute the Ackermann function, specifically with input values of 4 and 1 (anything higher than that is impractical):
consteval unsigned int A(unsigned int x, unsigned int y)
{
if(x == 0)
return y+1;
else... | In the template version of A, when a particular specialization, say A<2,3>, is instantiated, the compiler remembers this type, and never needs to instantiate it again. This comes from the fact that types are unique, and each "call" to this meta-function is just computing a type.
The consteval function version is not op... |
68,371,261 | 68,371,650 | Wrong result on modular arithmetic on ARM (Apple M1) with clang -O3 optimization | I am pulling my hair out for the last couple of days with this "innocuous" piece of code (minimal reproducible example, part of a larger modular multiplication routine):
#include <iostream>
#include <limits>
using ubigint = unsigned long long int;
using bigint = long long int;
void modmul(bigint a, bigint b, ubigint ... | UPDATE: As @harold pointed out in the comment section, negq and subq from 0 is exactly the same. So the my discussion related to negq and subq below is incorrect. Please disregard that part, sorry for not double checking before posting answer.
About the original question, I recompile a slightly simpler version of the c... |
68,372,237 | 68,372,702 | How to make dynamically created arrays as static? | i want to make dynamically created array as static ,doing which i will be able to access them and modify their values ,
below code runs fine but the function disp() is printing some garbage values,
but i have modified the array in push() ,but the changes are not getting reflected
using namespace std;
#include<iostream>... | As already mentioned in comments, with every while loop you create a new Stk object. So every time you push a value, while loop creates a new Stk object containing some garbage value.
So All you need to do is to move Stk <int >s; out of while loop. Then all your changes will be reflected.
And if you want a new object y... |
68,372,289 | 68,373,342 | Why multiset keeps separate instances of repeated elements instead of their count? | I recently found out that multiset<T> implementation in STL actually keeps different copies of the same repeated elements in the tree.
My expectation before was for it to internally use a map<T, int> and just keep the count of the repeated elements.
What is the scenario where this implementation can be beneficial compa... | By default std::multiset uses operator< to decide if two elements are equivalent (note: equiavent not equal!). Now consider this element type:
struct foo {
int x;
int y;
bool operator<(const foo& other) { return x < other.x; }
bool operator==(const foo& other) { return (x==other.x) && (y==other.y);
};
... |
68,372,623 | 68,373,211 | Compiling with MingW in CMD shows libisl-21.dll was not found | I was trying to compile a .cpp file using command-line, but I am encountering an error.
I have installed MinGW properly from the official installer.
Also, I sat the path to the bin folder of MinGW which is in C drive.
Now when I try to compile file with command:
g++ demo.cpp -o demo.exe
I get a "CC1plus.exe - System e... | libisl-*.dll is part of the MinGW-w64 distribution.
I'm not sure older MinGW also provides it, but you should use MinGW-w64 anyway (e.g. from https://winlibs.com/ or installed via MSYS2's pacman) as it's much better maintained and supports newer Windows versions (including 64-bit).
Your problem is that g++.exe depends ... |
68,372,830 | 68,378,282 | How to modify node element with boost::property_tree and put_value(const Type &value) | I am fairly new to boost::property_tree and I am having a little trouble with what should be a simple task.
I have a default xml file of which is to be copied and made unique with parameters passed into via the ptree & modelModifier(...) function below. All I want to do is parse the xml into a ptree, and then modify th... | Firstly, your code has UB, since modelModifier doesn't return a value.
The C-style cast in (std::string)it2.second.data() is extremely dangerous as it risks reinterpret_cast-ing unrelated types. There is no reason whatsoever for this kind of blunt casting. Just remove the cast!
Also, ptreeIterator should probably take ... |
68,373,078 | 68,373,412 | Debug Assertion failed with msvc2019 and qt 6.1, refered a nonexist file | When I debug my application I got a Debug Assertion Failed output,
Debug Assertion Failed!
Program: C:\WINDOWS\SYSTEM32\MSVCP140D.dll
File: D:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE\vector
Line: 73
Expression: vector iterator not dereferencable
For information on how your program can cause an asser... | The system installed file C:\WINDOWS\SYSTEM32\MSVCP140D.dll was compiled with the vector included on a D: drive
So the failure is within the DLL, and not on your drive. I believe the file is a support file for C++ code for Visual Studio 2015, and was built by the vendor (Microsoft), on 'D:'
The D at the end MSVCP140D ... |
68,373,184 | 68,373,293 | Having trouble with C++, can't cout << 100000 * 100000 correctly | I can't print 100000 * 100000 when I use COUT in C++. The output was 1410065408 instead of 10000000000. How can I fix that?
Thanks!
| The value is truncated since 10000000000 is larger than the default interger type int max value (std::numeric_limit<int>::max()) ,
hex(10000000000) = 0x2540be400
hex(1410065408) = 0x540be400
You can see that the first byte is truncated.
To fix it:
100000LL * 100000
or cast it
static_cast<int64_t>(100000) * 100000
|
68,373,598 | 68,373,791 | unable to modify a vector of const wchar * | I have a function that converts a list of strings to a vector of const wchar_t *.
void convertListtoVector(std::vector<const wchar_t *>& messageInserts)
{
std::list<std::wstring> Inserts;
Inserts.push_back(L"str1");
Inserts.push_back(L"str2");
Inserts.push_back(L"str3");
std::list<std::wstring>::it... | Your vector stores a pointer to string whose lifetime is managed by std::list. When list as local variable is deleted, all managed strings are also deleted, and you left with dangling pointers in vector.
You have to make a deep copy of strings content of list:
void convertListtoVector(std::vector<const wchar_t *>& mess... |
68,373,918 | 68,375,546 | Deleting elements from std set while iterating leads to endless loop | The following code produces the following output and ends up in kind of an endless loop with 100% cpu load.
#include <iostream>
#include <set>
class Foo{};
void delete_object_from_set(std::set<Foo *>& my_set, Foo* ob)
{
std::set< Foo *>::iterator setIt;
std::cout << "Try to delete object '" << ob << "'..." ... | Hokay, so you asked how this could loop infinitely without continuously triggering the "Check object" print.
The quick answer (that you already got from others) is that calling operator++ on my_set.end() is UB, and thus able to do anything.
A deeper dive into GCC specifically (since @appleapple could reproduce on GCC, ... |
68,373,965 | 68,376,081 | How to convert a public key in PEM format to a CNG key blob? | I need to verify the signature of a message using Windows' Cryptography API: Next Generation. I have the message, its signature, and a public key in PEM format, plus a prototype implementation that exhibits the desired behavior.
There's one issue with the code that I need to fix: Converting the public key into a key bl... | for convert PEM public key to CNG - generic steps is next:
CryptStringToBinaryA for convert string to binary
CryptDecodeObjectEx with X509_PUBLIC_KEY_INFO - convert binary
to CERT_PUBLIC_KEY_INFO
CryptImportPublicKeyInfoEx2 - import CERT_PUBLIC_KEY_INFO to CNG
example of code
inline ULONG BOOL_TO_ERROR(BOOL f)
{
... |
68,374,227 | 68,374,292 | Why are C++ objects destroyed when initialized inside function? What can I do to prevent it? | Here, when I push to the stack, why are the objects being destroyed?
#include <iostream>
#include <stack>
class One
{
private:
int i;
public:
One(int i) {this->i = i;}
~One() {std::cout << "value " << this->i << " is destroyed\n";}
};
int main()
{
std::stack<One> stack;
stack.p... | One(1) and One(2) construct two temporary objects, which are passed to push and then copied (moved) into stack. Temporaries are destroyed after the full expression immediately.
If you want to avoid constructing temporaries you can use emplace instead.
Pushes a new element on top of the stack. The element is constructe... |
68,374,372 | 68,374,477 | Strange template class conversion through the base class pointer | Why this code is valid in C++:
class Base
{
public:
Base() = default;
// base class stuff...
};
template<typename NumericType>
class Numeric : public Base
{
public:
Numeric() : m_value() {}
void setValue(NumericType value) { m_value = value; }
NumericType value() const { return m_value; }
privat... | See static_cast from cppreference:
If new_type is a reference or pointer to some class D and expression is lvalue of its non-virtual base B or prvalue pointer to it, static_cast performs a downcast. (This downcast is ill-formed if B is ambiguous, inaccessible, or virtual base (or a base of a virtual base) of D.) Such... |
68,374,446 | 68,375,116 | How to implement inheritance for Lua classes whose __index is a function? | By this tutorial, Lua can implement inheritance by assigning a metatable to the derived class table whose __index points to the base class table, like this:
BaseClass = {}
function BaseClass:foo()
end
DerivedClass = {}
setmetatable(DerivedClass, {__index=BaseClass}) -- set inheritance here
derived_instance = {}
setme... | Well that __index function would have to return BaseClass.foo if someone indexes DerivedClass.foo.
If __index is a table you basically do this:
getmetatable(DerivedClass).__index:foo()
which boils down to BaseClass:foo()
If __index is a function you do this:
getmetatable(DerivedClass).__index(DerivedClass, "foo")()
S... |
68,374,621 | 68,374,869 | Confused on Neural Net gradient descend part in c++ code | I was planning to make my own neural net lib in C++, and I was going thru other people codes to make sure I am on right track... Below is a sample code, that I am trying to learn from..
Everything in that code made sense, except for the gradient descend part, in which he literally updating weights by adding with positi... | Yeah, this is indeed confusing but I think that the crux in this line. (I may be wrong but if you say that the training is working then the only line which could possibly alter the signs should be this.)
eta * neuron.getOutputVal() * m_gradient
where neuron.getOutputVal() provides the direction to the update.
|
68,374,625 | 68,375,616 | Cast away volatile from fundamental type in C++ | What is the proper syntax (if there even is any) for casting away volatile from a fundamental type?
Suppose I have the following code:
void Bar(const int& x) {}
volatile int foo;
int main() {
Bar(const_cast<int>(foo)); // (1)
Bar(const_cast<int&>(foo)); // (2)
Bar(const_cast<int&&>(foo)); // (3)
Bar... | The following casts are valid according to C++11, and should perform the desired operation by passing a reference to a temporary to the function:
Bar((int)foo); // (4)
Bar(static_cast<int>(foo)); // (5)
As per section [expr.static.cast] of the standard (5.2.9 in C++11, specifically paragraph 4), (5) is va... |
68,375,055 | 68,375,087 | Is there any alternative for type alias in C++0x? | I want to create an alias arr for std::array<T, 32>.
template<typename T>
using arr = std::array<T, 32>;
However, it does not work on GCC 4.4.6 which supports only C++0x(without type alias).
I think it is a very bad idea to use GCC 4.4.6 now, however, I want to know if there are some ways to simulate type alias.
The f... | Before alias templates were a thing, it was common to write this instead:
template<typename T>
struct arr {
typedef std::array<T, 32> type;
};
Instead of arr<T> you would have to use arr<T>::type and typename arr<T>::type when T is a template parameter.
|
68,375,293 | 68,375,507 | Is it Okay to do new inside a function and return the pointer to it? | Is the following code snippet correct, or what could be wrong with it?
As I know, memory allocated with new, will not be erased unless there is a delete so returning its pointer should be fine?
// Example program
#include <iostream>
#include <string>
int* a()
{
int* aa = new int(1);
*aa = 44;
return aa;
}
... | It's not ideal. Who is responsible for deleting the pointer? You don't delete it anywhere in the example, so there is a memory leak.
Typically, if you need dynamic allocation, then you should return a smart pointer instead. That said, its usually also best to avoid unnecessary dynamic allocation. There's probably never... |
68,375,456 | 68,378,353 | gtkmm: Cannot create Gtk::Switch | Using Gtkmm 2.24.5, I'm trying to create a window with a single Gtk::Switch with the following code:
#include <gtkmm.h>
#include <gtkmm/switch.h>
class SimpleWindow : public Gtk::Window
{
public:
SimpleWindow();
private:
Gtk::VBox m_VBox;
Gtk::Switch m_Switch;
};
SimpleWindow::SimpleWindow()
{
set_tit... | The problem was, that I used gtkmm 2.24.5, while Gtk::Switch was introduced with gtkmm 3.0. Somehow my pkg-config eclipse plugin also included gtkmm 4.0, so the explicit include of gtkmm/switch.h prevented a compiler error at the m_Switch declaration.
Switching to a clean project with gtkmm 4.0 the new minimum working ... |
68,376,012 | 68,376,058 | Binding errors in functions with pointer parameters | When writing a code this way...
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node(int data) {
this->data = data;
}
};
void display(const Node* &p){
cout<<p->data<<endl;
}
int main(){
Node *p = new Node(10);
display(p);
return 0;
}
I get the followi... | p is a Node * and can't be bound to const Node* & directly. It needs to be converted to const Node* firstly, which is a temporary, i.e. an rvalue, and can't be bound to lvaue-reference to non-const.
Changing to Node* & fixes the issue, p could be bound to Node* & directly without any implicit conversion.
BTW temporarie... |
68,376,560 | 68,376,645 | C++ give me strange result | I have a very strange result running the following C++ code:
#include <iostream>
using namespace std;
int main()
{
int c[]={49,46,48,46,51};
int p=0;
for(int i=0;i<5;i++)
p =p*100+c[i];
cout << "Hello World! p=" <<p<< endl;
return 0;
}
Hello World! p=651517355
However, the expected re... | On many platforms (including yours, it would appear), both int and long int are 32-bit integers, which cannot hold the value 4946484651. (The Standard mandates only that long int be no shorter than int and at least 32 bits wide.)
You need to use long long int for p or, better still, use the explicit int64_t type:
#incl... |
68,376,737 | 68,377,892 | Chrono C++ timings not correct | I'm just comparing the speed of a couple Fibonacci functions, one gives an output almost immediately and reads it got done in 500 nanoseconds, while the other, depending on the depth, may sit there loading for many seconds, yet when it is done, it will read that it took it only 100 nanoseconds... After I just sat there... | I don't know what compiler you are using and with which compiler options, but I tested x64 msvc v19.28 using /O2 in godbolt. Here the compiled instructions are reordered such that it queries the perf_counter twice before invoking the fibonacci(int) function, which in code would look like
auto start = ...;
auto stop = .... |
68,377,321 | 68,377,570 | Using auto to a variable assigned ot a function that return const ref | const className& f();
If I have a function that return const ref. And use it's value to assign to a variable using auto
auto v1 = f();
auto& v2 = f();
const auto& v3 = f();
decltype(auto) v4 = f();
As far as I understand all those three option will be same. But should I still prefer to write like for v3 to be explici... |
If I have a function that return const ref. And use it's value to
assign to a variable using auto
I believe you meant to initialize the variables with the function f:
auto v1 = f();
auto& v2 = f();
const auto& v3 = f();
As far as I understand all those three option will be same.
No, they are not the s... |
68,377,378 | 68,381,523 | Proper way to add enum class to metaObject Qt 5.15 | I'm tinkering a bit with Qt's meta-object system, and I've come across an issue with adding enum class to a meta-object. I have a struct that contain some variables, one of which is an enum class.
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <QObject>
enum class CarType {
NO_CAR = 0,
SLOW_CAR,
FAST_CAR,
... | If you don't want to add your enum to a class with Q_OBJECT or Q_GADGET, then the other way to do it is to put your enum inside a Q_NAMESPACE. You can't actually use Q_ENUM with Q_NAMESPACE, but you can use Q_ENUM_NS instead. I haven't tested this myself, but it should work:
namespace MyNamespace
{
Q_NAMESPACE
... |
68,377,418 | 68,377,602 | Compare templates itselves and not instantiated template-types | My goal is to be able to compare templates i.e. write something like this
template<typename T>
struct template_type;
template<template <typename...> typename TTmpl, typename ...Ts>
struct template_type<TTmpl<Ts...>> { using type = TTmpl; }; // [1] this isn't valid C++
template<typename TRng, typename T>
auto find(TRn... | I am not sure if I understand what you want, also because I would use a different solution for your motivating case (sfinae on the presence of member find). Anyhow, this is how you can check if a given type is an instantiation of a template, provided the template has only type parameters:
#include <iostream>
#include <... |
68,377,435 | 68,377,705 | What is a member enumeration in context of templates? | The C++20 standard (N4892) states:
The declaration in a template-declaration (if any) shall
[...]
(2.2) — define [...] a member enumeration, [...]
(13.1.2)
What is meant by a member enumeration in this context? I looked through the standard but could not find a definition of this term, only usages of it. In 13.9.2.3.... |
However, I was unable to create a member enum template in MSVC:
Because this was not meant. There are no enum templates in the now existing C++ standards. Think instead of a forward-declared scoped-member-enum of a class template:
template <typename T>
class Foo { enum class bar; };
template <typename T>
enum class ... |
68,377,742 | 68,378,305 | SLOT for statusbar->messageChanged() QT | I've problem with QT statusbar. I want to recive and process changeMessage from statusbar, bo I have problem with slot. How I should write correct slot or how to use connect function correct, with which I've problem too.
file.cpp
connect(statusbar, SIGNAL(messageChanged(const QString &message)), this, SLOT(func1(const ... | If you are using Qt5 you don't need the SIGNAL and SLOT macros in the connect.
connect(statusbar, &QStatusBar::messageChanged, this, &file::func1);
This will fail at compile time and give you an error message if the signatures are incompatible.
Edit:
As @G.M. stated in the comments
QMetaObject::connectSlotsByName: No ... |
68,378,087 | 68,380,438 | Integrate Google Crashpad with Linux application | I'm trying to integrate Google's Crashpad into my application running on Ubuntu.
As per it's overview design
I create one handler process on ubuntu by following this link
Now for the client process, I should register it with the handler via a socket connection.
Linux/Android
On Linux, a registration is a connected soc... | Unless you have a special use case that isn't listed here you shouldn't have to do anything with sockets manually. Just create a new instance of CrashpadClient at the entry point of your program and call StartHandler.
Here's a snippet from BugSplat's myUbuntuCrasher sample:
// Start crash handler
CrashpadClient *client... |
68,378,413 | 68,379,478 | Hex to String with a bit of trick | First of all, yes I know about FAQ Converting.
But I don't need that kind of type-conversion (I hope!).
We have:
#include <iostream>
#include <bitset>
#include <string>
#include <sstream>
struct My_Data{
uint16_t data;
};
using namespace std;
int main()
{
My_Data data{ 0x12 }; // data = 0x0012
stringstream ss;... | The easiest method to make a std::vector<std::uint8_t> from an std::uint16_t in hex representation with width 4 and zero padded would be something like so
#include <sstream>
#include <string>
#include <iomanip>
#include <vector>
#include <cstdint>
std::vector<std::uint8_t> make_hex_vector(std::uint16_t val)
{
std:... |
68,378,708 | 68,378,732 | a nonstatic member reference must be relative to a specific objectC/C++(245) | I have the following class declaration:
#ifndef ANIL_GRAPH_H
#define ANIL_GRAPH_H
#include <cstddef>
#include <iostream>
#include "anil_cursor_list.h"
namespace anil {
class graph {
private:
// Data:
cursor_list** vertices; // An array of cursor_lists whose ith element contains the neighbors of ver... | You should make it static constexpr
The issue is, without static you define a instance-specific variable that is not accessible without having a class instance.
|
68,379,058 | 68,379,294 | Why can't I convert a lambda with a non-copyable class parameter to a std::function? | Consider the code below which fails to compile:
#include <mutex>
#include <functional>
class t{
std::mutex m;
};
std::function<void(t test)> func = [](t test) {return;};
The following error is generated :
error: conversion from '<lambda(t)>' to non-scalar type 'std::function<void(t)>' requested
Can you explain... | The diagnostic is super misleading. While it is obvious that mutex is not copyable, there is no copying of mutex requested in the provided snippet!
The immediate cause of issue is the fact that std::function<> templated constructor (one which would be called when std::function is created from the lambda) is SFINAE-rest... |
68,379,890 | 68,380,095 | auto and auto& and const | auto x1 = exp1;
auto& x2 = exp2;
Do I understand correctly that variables declared with auto (x1) will never be const, even if exp1 is const (for ex. a function that returns const). When with auto&(x2) will be const if exp2 will be const. Even if auto is a pointer.
auto it = find(cont.cbegin(), cont.cend(), value);
H... |
Do I understand correctly that variables declared with auto (x1) will never be const
Correct.
When with auto&(x2) will be const if exp2 will be const.
A reference is never const; references cannot be cv qualified. x2 could be a reference to const.
auto it = find(cont.cbegin(), cont.cend(), value);
Here despite I ... |
68,379,917 | 68,380,292 | Store text based columns data into array C++ | I’m trying to store data from a text file into an array in order to use it afterwards. The problem is when there is a header for each data, how can skip a line in the middle of the text or to take it separately?
#include <iostream>
#include <fstream>
main() {
double tab[100][6] = {0};
int i =0, j;
std::s... | You can try marking each header in the text file as comments by putting a # at the beginning of each header.
Now read the text file like this:
#include<sstream>
...
...
std::ifstream file {"test.txt"};
std::string line;
std::istringstream iss;
double tab[100][6];
int i=0, j;
...
while (getline(file, line))
{
if (!(... |
68,380,141 | 68,380,896 | How to implicitly convert `basic_string` to deduced `basic_string_view` template? | I am writing a generic algorithm that can work with strings or string segments of any character type -- and so I have decided to work with std::basic_string_view with deduced template arguments for CharT and Traits. However, I have quickly discovered that this doesn't allow for passing std::basic_string objects in, sin... | The simplest thing is to make it a more general template
struct my_algorithm {
template <typename StringView>
auto operator()(StringView&& sv) -> void {
using Traits = typename std::remove_cvref_t<StringView>::traits_type;
using CharT = typename std::remove_cvref_t<StringView>::value_type;
/* ... ... |
68,380,280 | 68,380,652 | Return unique_ptr with abstract class inside | I am trying to encapsulate details of the Engine implementation class. To do that I am returning std::unique_ptr of abstract class (IEngine in my case) instead of Engine. But I could not do that due to the compile error. I could return raw reference and it works but is that possible with unique_ptr? Thanks in advance.
... | std::unique_ptr<IEngine> is a different type to std::unique_ptr<Engine>, so you are asking to return a reference to a temporary object.
std::unique_ptr uniquely owns the object it points to, so even if you removed the reference, it would be incorrect to create a std::unique_ptr<IEngine> from the existing std::unique_pt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.