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,118,745 | 68,118,843 | How to overload operator >> to enter vector values of a class? | I am trying to find a way to let the user define the length of an int vector, which is a private member of a class, and then insert all of the numbers through the console, however, I did not find any overload specifically made for vectors. Here is my code, which gets: "exception: std::out_of_range at memory location." ... | int help{ 0 };
i >> help; //I used help to define the amount of numbers to be added
for (int i{ 0 }; i < help; i++) //exception: std::out_of_range at memory location
i >> l.numbers.at(i);
return i;
Will most definitely cause an out-of-range exception. The std::vector is empty, so it will set the... |
68,118,872 | 68,118,964 | "undefined reference" for lambda function to process multiple template classes | I have an template class like this:
Strip.h
#pragma once
class IStrip
{
public:
int Pin;
void compute();
};
template <int PIN>
class Strip : public IStrip
{
public:
int Pin = PIN;
void compute()
{
}
};
and I manage multiple instances of them like so:
Manager.h
#pragma once
#include "Stri... | You're missing quite a lot. First of all the IStrip class or the Strip class template are not polymorphic. And by passing sm by value to the lambda, you have object slicing.
To make it work, you first of all need to make IStrip::compute a pure virtual function:
class IStrip
{
public:
virtual void compute() = 0;
};
... |
68,119,172 | 68,119,637 | Passing a c library path from a conan package to a source file | I'm using Conan to package an old C library.
The library has a loading process that requires you provide the path to a library from inside a .cpp source file. How can the directory to the conan packaged lib be accessed from inside the consuming source?
So the setup is like:
conan package roughly like:
ole_c/0.0:
... | You can use cmake generator expressions to get the path to a target's library. If you are using conan in TARGETS mode then you could do:
target_compile_definitions(MyApp PRIVATE PATH_TO_OLE_C_LIB=$<TARGET_FILE:CONAN_PKG::ole_c>)
Alternatively you might be able to populate the cpp-info.defines in the conan recipe and m... |
68,119,355 | 68,120,316 | Function reference and pointer | I'm trying to make a cumulative density functions (CDF) for normal distribution by using a well-coded library. The inplementation of that library is irrelevant to my questions. So i only added interface here.
void cumnor ( double *arg, double *result, double *ccum );
Now, my member function interface:
double N(const d... | You can't pass &x to cumnor() because x is a reference to a const double but cumnor() expects a pointer to a non-const double instead. Being non-const gives cumnor() permission to change the value of the double it is given, if it wants to. If that is not actually the case, then it should take a pointer to a const dou... |
68,119,945 | 68,120,077 | How to insert an element to alist in a vector of lists in C++? | I'm trying to create a vector of lists and then insert an element to a specific list in the vector.
That what I was trying to do
vector<list<int>> depth_lists;
depth_lists[0].push_back(1);
It fails with some very long exit code... What am I doing wrong here? I think I maybe had to somehow initialize each list in the v... | You created an empty vector
vector<list<int>> depth_lists;
So you may not use the subscript operator
depth_lists[0].push_back(1);
You could write for example
depth_lists.push_back( { 1 } );
Here is a demonstrative program.
#include <iostream>
#include <vector>
#include <list>
int main()
{
std::vector<std::lis... |
68,119,998 | 68,122,782 | How big would a mat multiply be for it to be more effecient to use th gpu | So I've been messing around with OpenCL kernels and I'm trying to understand GPU acceleration a bit better and I'm curious to find out how one would find the point at which it would be more computationally efficient to use GPU acceleration in place of tradition CPU computing
| There is no one-fits-all sharp threshold to when GPU parallelization is better as it depends on the hardware. The data transfer from CPU to GPU and back causes latency in the range of milliseconds and needs large amounts of data to run efficiently at full PCIe bandwidth. However since compute time for matrix multiplica... |
68,120,074 | 68,121,481 | How to access a private typedef as a parameter in a public function | Title says it all.
typedef string ListElemType;
class inord_list {
public:
void insertafter(const ListElemType&, link);
void insertbefore(const ListElemType&, link);
private:
struct Node;
typedef Node* link;
struct Node
{
ListElemType elem;
link next;
};
link head;
li... |
Whenever I try to use the "link" as a parameter in the above functions it's an error.
As it should be. You can't use a private type as a parameter/return value in a public method. Callers of the method that are outside of the class would not have access to the type, and thus could not call the method.
if I declar... |
68,120,122 | 68,120,863 | How to initialize a const reference member to another member (std vector) in C++ initializer list | I did the following as a cheap way to allow read-only access to a member container _numbers via numbers:
class Foo {
Foo() : _numbers({}), numbers(_numbers) {
// some code that populates `numbers` via `numbers.push_back(...)`
}
private:
std::vector<int> _numbers;
public:
const std::vector<int>& numbers... | const vector<int>& numbers1, numbers2; — Here, only the first variable is a reference. You need & before the second variable to make it a reference as well. Then the code should work.
But I have to say that what you're doing is a really bad idea. You're paying for a convenient syntax with memory overhead, non-assignabi... |
68,120,334 | 68,129,845 | Qml blur effect on listview | i want to add blur effect at the bottom of listview like this:
i wrote this code with Qml but does not work correctly.
could you please tell me where is the problem and how can i fix this ?
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
import QtGraphicalEffects 1.0
ApplicationWindow {
... | It's not perfect, but it works. Quick demo of how to do it:
main.qml
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtQuick.Layouts 1.12
import QtGraphicalEffects 1.0
ApplicationWindow {
id: window
width: 480
height: 520
visible: true
title: qsTr('Blur List')
color: 'black'
ScrollV... |
68,120,431 | 68,227,820 | How to create a QSlider with a non-linear scale? | Is there a simple way to implement a non-linear scale to a QSlider? I want to implement a logarithmic scale to it.
The only workaround I am thinking of is manipulating the value change signals outside of the class.
| I implemented a LogSlider, with a scale factor and it worked well.
class LogSlider : public QSlider {
Q_OBJECT
public:
explicit LogSlider(QWidget* parent = nullptr, scale = 1000) : QSlider(parent) : m_scale(scale) {
QObject::connect(this, &QSlider::valueChanged, this,
&LogSlider::onValueCh... |
68,121,065 | 68,126,586 | a generic builder to create a comparator for arbitrary objects, which can take a arbitrary data member in the object to sort | I need to write a comparator builder which can generate a comparator for std:sort. This builder can deal with any generic objects, and take an arbitrary data member of the object in std:vector to sort. so we need to pass in the class data member pointer to comparator_builder's constructor. The usage and the interface o... | You're already most of the way there with your comparator class:
template <typename ObjectType, typename MemberType>
class MemberComparator {
public:
using MemberPtr = MemberType ObjectType::*;
explicit MemberComparator(MemberPtr ptr) : m_ptr(ptr) {}
bool operator()(const ObjectType& x, const ObjectType& y) con... |
68,121,129 | 68,128,491 | is there a good way to constructs objects with changing parameter types in c++? | Im fairly new to c++ and wonder if there is a better solution to this problem. I currently have an abstract class with multiple diffrent classes (i_c) implementing that interface and constructors of other objects, who use these implemented classes as parameters one at a time. The other parameters stay the same for each... | Here is your code making use of templates:
class parent_robot
{
public:
virtual void move_tcp() = 0;
};
template<class T>
class child_robot
: parent_robot
{
public:
void move_tcp() override;
private:
Eigen::Affine3d x_location_;
};
template<class T>
class gui_object_identical{
gui_object_identical_a:... |
68,121,246 | 68,121,337 | Using a global variable to initialize an identity matrix not working | I would like to use a global variable n = 7 to initialize a 7x7 identity matrix, as shown in the code below:
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
using Eigen::MatrixXd;
int n = 7;
int main()
{
MatrixXd I = Matrix<double, n, n>::Identity();
cout << I <... | As the error message states, you need a compile time constant.
You can make n that by using constexpr
#include <iostream>
#include <Eigen/Dense>
using namespace std;
using namespace Eigen;
using Eigen::MatrixXd;
constexpr int n = 7;
int main()
{
MatrixXd I = Matrix<double, n, n>::Identity();
cout << ... |
68,121,375 | 68,121,671 | How to erase item inside of item in nlohmann::json file C++ | I want to know how I can delete an item within an item in the nlohmann::json C++ library.
Json example file:
{
"Users":{
"User1":{
"Name":"BOB",
"DeleteMe":"IWantToBeDeleted!"
}
}
}
What I want to delete is "DeleteMe":"IWantToBeDeleted!" that is inside of "Users" and "Us... | basic_json::erase only erases from the currently referenced json node -- so if your json object is the outer object, that would be why you can only erase top-level entries. What you want is a way to get the internal node User1 and call erase on the DeleteMe key from there.
You should be able to easily get a reference t... |
68,121,414 | 68,201,077 | C++ download audio/video file from blob URL? | I have an Angular front end with a C++ powered back end. I want the C++ back end to grab a file from a blob URL created by the front end (with URL.CreateObjectURL).
I have tried using URLDownloadToFile:
HRESULT hr = URLDownloadToFile(NULL, theBlobURL, outfilename, 0, NULL);
As well as curl:
CURL* curl... | Remy Lebeau was correct, the Blob URL is private to the browser. It cannot be downloaded outside the browser.
|
68,121,745 | 68,121,837 | Find reverse order of an array in c++ |
Write a program that reads in a sequence of characters until the symbol * is encountered. Use a function that will display the sequence in reverse order. (Make use of arrays).
I have tried this, but I am getting an error:
*** stack smashing detected ***: ./a.out terminated
This as output:
Reverse order: �>
#includ... | You are accessing out of bounds of the array, which is undefined behavior. You are corrupting surrounding memory.
Also, c is uninitialized when you try to read from it for the 1st time, which is also undefined behavior.
And, you are not validating that operator>> is successful before using c afterwards, which is also u... |
68,121,894 | 68,122,601 | Why can't we compare types of function arrays in C++? | When I tried to compare two types of function arrays, I encountered this strange behavior.
I have test code:
using ArrayOfFunctionsT = int (* [])(int);
ArrayOfFunctionsT functions = {};
std::cout << typeid(decltype(functions)).name() << " vs " << typeid(int (*[0])(int)).name() << "\n";
std::cout << std::is_same<declty... | Quick answer: zero-sized array are forbidden by C++ standard. So any result that come afterwards are compiler dependent.
In the comment section, people has mentioned that:
is_same can't work with expressions like int (*[0])(int)
However, that's not the reason here, and is_same does work on expression similar to that... |
68,122,223 | 68,122,224 | How can you `co_await` in a C++/WinRT lambda? | Can you co_await in a C++/WinRT TimerElapsedHandler (or any other lambda in C++/WinRT)?
When I try to compile code like this:
auto pointerExitedTimerHandler = winrt::TimerElapsedHandler([](const winrt::ThreadPoolTimer&)
{
co_await 5s;
// Other stuff...
});
I get an error:
error C7588: A definition of a class ... | You simply need to provide an async return type. For example, -> winrt::fire_and_forget:
auto pointerExitedTimerHandler = winrt::TimerElapsedHandler([](const winrt::ThreadPoolTimer&) -> winrt::fire_and_forget
{
co_await 5s;
// Other stuff...
});
Fire and forget is a simple WinRT wrapper for async functions th... |
68,122,487 | 68,122,511 | Inheritance of Type Members C++ | I'm trying to use a type member of a class in its child, but I'm failing. In particular, I can't understand why this code does not compile:
template <typename T>
class A {
public:
using t = T;
A() {}
};
template <typename T>
class B: public A<T> {
public:
B() : A<T>() {}
... | Since A<T>::t depends on a template parameter, it requires a typename:
typename A<T>::t foo(typename A<T>::t x)
Because it depends on a template parameter, it must always be qualified (i.e. have :: to the left of it), so just the plain t wouldn't work.
typename B::t would also work.
typename A::t wouldn't work because... |
68,122,650 | 68,122,718 | Large array inside a nested namespace c++ | I would like to know if there is a difference in behavior if I create an array inside a namespace vs outside a namespace eg
//file.hpp
static char array[512];
vs
namespace a::b::c
{
static char array[512];
}
It seems when I use snprintf with an array that is inside a namespace I get unexpected behavior.
Essentially t... | All of the printf family have a very specific syntax. If you turn your compiler warnings up, most modern compilers will warn you if you violate it. In particular, %d is the indicator for an integer. You've given it a character. snprintf uses the old C-style varargs syntax, which means it can't validate types at compile... |
68,122,860 | 68,123,477 | Explanation of the usage of std::max in that code? | I am unsure whether or not I better should have posted this question on codereview.stackexchange.com. Anyway, here we go ...
Please consider the following code snippet which is a literal (I have only changed the formatting) excerpt from here and has been printed (in stripped-down form) in the German computer magazine c... | Let's consider what exactly it does:
std::streamoff pos = std::streamoff((uint64_t(lo) + uint64_t(hi)) / 2);
pos = std::max<int64_t>(0, pos);
std::streamoff is some implementation defined signed integer type. Let's consider a case where it is a 64 bit type or smaller: The value of pos will not be changed by the conv... |
68,122,938 | 68,123,005 | How to prelevate an imprecision number of element from a file with fstream? | I should read a text file which contain an imprecision number of lines with names of different car, follow by numbers of cars sold in the last 6 month. I don't know how to read the file without know the precise number of element that is content in it.
The file is like this:
Ferrari 3 7 5 4 1 3
Porsche 1... | You can use std::getline() in a loop, using std::istringstream to parse each line, eg:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream file("nomefile.txt");
std::string line, name;
int sold[6];
while (std::getline(file, line))
{
std::i... |
68,123,026 | 68,123,507 | Make a int returning function behave as an lvalue and rvalue | I hope I am technically accurate in formulating this query. While lvalues and rvalues are new to me as an in-depth topic, I could not help but draw similarities between how some functions tend to behave dually and how it relates to this. I assume lack of proper terminologies is causing my research into this topic futil... | Those are not definitions of functions; they seem to be invocations of member functions.
Are those two different functions? Not necessarily. If that member function is declared like so:
int& index_at(std::size_t row, std::size_t col);
then this same member function could be used on both lines. It is possible to define... |
68,123,391 | 68,123,573 | When is the assert ( ) expression evaluated in a scope? | I was trying to understand the assert() macro in C++ and I am confused as to when the assert statement is checked for its validity.
I created a class Pyramid where I wanted to check if the Class attributes are positive and so I created a try() -> catch() exception handling first and if I enter a negative value for inst... |
When is the assert ( ) expression evaluated in a scope?
assert is evaluated when the execution reaches it. Same as most expression statements (assert itself is a macro, but it will expand into an expression statement).
neither the expression std::cout<<errorText nor the printData() gets evaluated
You've assumed wro... |
68,124,022 | 68,124,097 | When to explicitly specify the template arguments in C++? | For almost 7 months of studying C++, I've been curious about when to explicitly specify template arguments, specifically function templates.
std::forward is one such example, that should be provided with type template argument (std::forward<Type>(arg)).
Usually, the template arguments are deduced through function param... |
when should template arguments be specified explicitly?
When you actually need to specify them explicitly. Otherwise, let the compiler deduce them for you whenever possible.
Sometimes you may need to specify template arguments to resolve ambiguities.
Sometimes you may need to specify template arguments to use specif... |
68,124,374 | 68,126,313 | How to find the Kronecker product row by row between two dimensional matrices? | I have the following Matrices x1 and x2
int x1[3][4] ={
{0, 1, 2, 3} ,
{4, 5, 6, 7} ,
{8, 9, 10, 11}};
int x2[3][4]= {{0, 4, 5, 1} ,
{4, 9, 4, 3} ,
{8, 4, 1, 14}};
I would like to know how to do kronecker product row by row some thing like that:
kronecker_results ={{... | https://en.wikipedia.org/wiki/Kronecker_product
Since both x1 and x2 are 3x4, then final Kronecker product will be a 9x16 matrix.
To get 3x16 matrix, you would have to only Kronecker multiply a single row from x1 with the full x2... and ignore the additional rows from x1. Your final matrix for any single row from x1 wo... |
68,125,241 | 68,125,766 | Using non-const variable as index to constexpr array to pass to template parameter | I have a constexpr size_t array whose members will be passed to the template parameters of a class that gets initialized, iterating over the array to construct and use several differently templated objects. Here's the general idea:
template <size_t N>
class Foo
{
// magic
};
constexpr size_t c_arr[] = { 2, 5, 3, 2... | If you want values to be used as template parameter, use std::integer_sequence
template <size_t N>
class Foo
{
public:
void bar() {}
};
template<std::size_t ...I>
void foo_bar(std::index_sequence<I...>) {
int dummy[] = { (Foo<I>{}.bar(), 0) ... };
// ((Foo<I>{}.bar()), ...); if using C++17 or above
}
int main(... |
68,125,402 | 68,125,678 | I have a problem with a program for a library | I have a class that is creating books, and also a class where it is going to save the books in an array, but I have to make a method that prints all the books that have the same title but of a different year, and it happens to me that this failing from code what it does is that it duplicates some books, is there a way ... | I dont know your native language but if I understand the code correctly:
Assume you have three books with the same title but different publishing dates, lets call the books A,B,C.
When you encounter A in the first loop, you start looping the second loop. When you encounter B, you set primeraVez = false to prevent print... |
68,125,562 | 68,125,600 | what is the the purpose of using ? and : in the following code | I am a complete beginner in C++. i recently came across a piece of code. I don't seem to understand the use of ? and :. can anyone tell me how it works? why we use ? and :
CODE
(j==1 or i==s)?(cout<<"* "):((j==i)?(cout<<" *"):(cout<<" "));
| It is a ternary operator. The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.
Syntax:
The conditional operator is of the for... |
68,125,576 | 68,125,753 | Memoization Approach for Gold Mine Problem on GFG | I am trying to solve the Gold Mine problem on GFG using a memoization based approach of dynamic programming. Here is the code I have written.
int dp[50][50];
int traverse(int x,int y,int n,int m, vector<vector<int>> M){
if((x<n and x>=0) and (y<m and y>=0))
{
if(dp[x][y]!=-1)
... | Use call by const reference for the STL container. You performed thousands of copies of the full, read-only input.
int dp[55][55];
int traverse(int x,int y,int n,int m, const vector<vector<int>>&M){
. . .
}
int maxGold(int n, int m, const vector<vector<int>>&M)`
{
...
}
|
68,126,451 | 68,126,901 | std::basic_fstream<unsigned char> doesn't work on Linux | I'm getting a failure on Linux when calling the read() function on basic_fstream<unsigned char> stream:
basic_fstream<unsigned char> fs;
basic_string<unsigned char> buf(1000, '\0');
fs.open( "/tmp/file.txt", ios::in | ios::binary);
fs.read( &buf[0], 1000);
I traced where it throws: in function __check_facet(const _Fa... | The standard library is not required to provide facets or locales for unsigned char. The standard streams are designed only with char (and wchar_t) in mind.
I would suggest using the standard std::ifstream instead. You can read binary data with it, and store it into an unsigned char buffer. You should consider using th... |
68,126,523 | 68,130,597 | Boost graph - understanding compilation errors and minimal properties | The following code (Snippet 1) compiles fine:
#include <boost/config.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/boykov_kolmogorov_max_flow.hpp>
#include <boost/graph/graph_utility.hpp>
using namespace boost;
typedef adjacency_list_traits<vecS, vecS, directedS> Traits_vvd;
typedef adjacency_l... | The required properties are documented with the algorithm: https://www.boost.org/doc/libs/1_76_0/libs/graph/doc/boykov_kolmogorov_max_flow.html
You can see which arguments are IN/OUT or UTIL, and which of them have defaults (making them non-mandatory unless the default expression is not valid for your graph type).
I've... |
68,127,182 | 68,127,366 | C++ Ternary Operator Calls Copy Constructor Instead of Move Constructor | I'm using VS Code to compile and debug with g++ in Linux.
Needed includes and usings:
#include <string>
#include <iostream>
using namespace std;
Here is my class which is moveable:
class A {
public:
A(const string& strA) : strA(strA) {}
A(const A& a) : A(a.strA) {
}
A(A&& a) : A(a.strA) {
a.... | The "automatic" move in return statement is limited:
From Automatic move from local variables and parameters:
If expression is a (possibly parenthesized) id-expression that names a variable whose type is either
[..]
It is not the case for return ex == "123" ? a : b;.
Then normal way is done, ex == "123" ? a : b retur... |
68,127,699 | 68,127,803 | C++ : Read(Write) from(to) a file if provided otherwise fall back to std::cin (std::cout) | I have this need. Read or write from/to file if provided otherwise fall back to good friends std::cin / std::cout, as in:
// pseudo code for problem statement.
int main(int argc, char* argv[])
{
istream reader;
ostrea writer;
if (argc > 1)
{
// we have path to our file in argv[]
reader = ifstream(in... | You can look toward the following approach:
void read_write(ifstream&, ofstream&); // Overloaded reader-writer
void read_write(istream&, ostream&);
int main(int argc, char* argv[]) {
if (argc > 1) {
auto infile = argv[1];
auto outfile = argv[2]
read_write(infile, outfile);
} else read_... |
68,127,746 | 68,144,520 | How to fix linker error when working with openCV-4.5.2 and visual studio 2019 c++ code? | I'm a trying to get a visual c++ up and running with some source code I found that uses OpenCV. I'm have some experience with c++. I'm getting unresolved external symbol errors and I've spent hours reading every article I can find on here about it, and every answer is... "don't link x86 with x64 libs, or vise versa" or... | Sorted by not using the opencv 4.5.2 eXe. I had to use manually install. Now everything works fine. If anyone needs help. Let me know. Happy to help
|
68,128,394 | 68,128,563 | Pointers as parameters to functions | I have a program here:
#include<iostream>
using namespace std;
void f1(int* x){
for (int i = 0; i < sizeof(x); i++) {
cout<<x[i]<<endl;
}
}
void f2(int* x) {
cout<<x<<endl;
}
int main() {
int a=3;
int a1[3]={2,3,1};
f1(a1);
f2(a);
}
The function f1 allows me to pass an array as the argument to fu... | The f2() (as well as the f1()) waits for a pointer to int. While you pass it an int, the a.
The error invalid conversion from 'int' to 'int*' means that a pointer to an int is not the same as an int. A pointer represents an address in memory of the computer, an int is a variable with integral numeric value, there's no ... |
68,128,568 | 68,148,749 | dlsym() + RTLD_NEXT doesn't work as expected on Ubuntu 20.04 | I'm faced a strange runtime behavior on Ubuntu 20.04 (gcc v 9.3.0) when using dlsym() call.
Please, see below a simple example:
file test.cpp:
#include <iostream>
#include <dlfcn.h>
#include <execinfo.h>
#include <typeinfo>
#include <string>
#include <memory>
#include <cxxabi.h>
#include <cstdlib>
extern "C"
{
v... | The "app protection" component of the Citrix ICA client installs the library /usr/local/lib/AppProtection/libAppProtection.so and adds an entry for it to /etc/ld.so.preload, causing it to be loaded into every dynamically-linked process. Among other things, this library replaces the dlsym function with its own. (If you'... |
68,128,608 | 68,129,321 | How does realloc behave in C++ regarding extra Space? | Let's suppose I have allocated a block of size 40 like this:
int *x=malloc(40);
Now when I call realloc like this:
realloc(x,100);
what will happen to the other 60? Here are my suggestions.
A) Will be set to 0
B) Will Contain garbage from what malloc returned with a new allocation of 100
C) The first 40 are copied no... |
Here are my suggestions
Why are you speculating about something you can just look up?
For example, the POSIX documentation is here and says the last sixty bytes will be indeterminate.
You can look up the documentation for any platform if you want to know how that platform will behave (and don't care about portability... |
68,129,082 | 68,129,771 | In unordered_multimap, will find() return the first element with the key? | I understand that in the iterator sequence of a std::unordered_multimap, equal keys are grouped together. Is find() guaranteed to return the first element with the key, or can it return any element with the key? Is the only reliable way to get all elements with the key equal_range?
I am wary of equal_range() because it... |
In unordered_multimap, will find() return the first element with the key?
It's not guaranteed.
If we assume each bucket is a linked list of nodes, find and equal_range are probably doing the same linear scan within the bucket to find the key. That means that find probably does give the first element.
If an implementa... |
68,129,211 | 68,129,593 | Does passing by const reference really save the memory cost when it has to convert the type? | There are many existing questions about const reference (reference to const). But when there is an implicit conversion, const reference also causes a new address. I wrote this example bellow:
int i = 42;
double d = 4.2;
const int& ri1 = i;
const int& ri2 = d;
&ri1 and &i would print the same address, ho... | It is helpful to think this way:
We would not want to bind a (plain) & reference to an object if this binding will cause this object to change. E.g. from 3.1415 to 3, like here:
double pi = 3.1415;
int& r = pi; // Imagine, now both r and pi are 3...
We can't change the type of the r to double (otherwise, that would b... |
68,129,293 | 68,129,409 | How to resolve warning "ignoring return value of function declared with 'warn_unused_result' attribute" | I'm writing test automation in QT. I'am using QTest::qWaitFor to wait until the event loop switches to another tab in UI.
QTest::qWaitFor([tabs, ¤tIdx]() {
currentIdx = tabs->currentIndex();
return currentIdx == 1;
}, 5000);
Each time I'am using such construction following warning appears:
ignoring retur... | Issue is not with lambda, but your usage:
You should use/check return value of qWaitFor (to know if timeout happens):
if (QTest::qWaitFor([tabs, ¤tIdx]() {
currentIdx = tabs->currentIndex();
return currentIdx == 1;
}, 5000)) {
// OK.
// ...
} else {
// timeout.
// ...
}
|
68,129,470 | 68,440,142 | How to add Id to "QDomElement" tags in kml file using Qt application | I am trying to add ids to the QDomElements in cpp. I successfully genearte a kml file. I want to add the ids to the kml tags like Document, Placemark in incremental way. How can I add ids to the tags in kml file.
QDomProcessingInstruction header = createProcessingInstruction(QStringLiteral("xml"), QStringLiteral("v... | To add Id into "QDomElement" tag add line where you want to add tag for QDomElement
wpPlacemarkElement.setAttribute(QStringLiteral("id"), QString::number(i));
// i is index of for loop
// add this line into for loop
|
68,129,511 | 68,132,128 | Unexpected Segmentation fault while debugger shows namespace without issues | This one should be an easy fix, or so I thought.
Error
Segmentation error while initializing my world.
A function is called to move a Vehicle, this checks if the location it would move to is valid, and there I need to reach back to the World to see its boundaries. This pointer to the World is not initialised correctly.... | Solution was said in the comments by Botje:
" Not sure if it is the cause of your problem, but your Vehicle::Vehicle(World * w) constructor does not fill in any of the fields. It creates a temporary Vehicle and then throws it away."
I just copied the content of the other constructor to actually construct the object.
Th... |
68,129,761 | 68,129,812 | Elegant way to defining the various operations and costants | I'm creating a C++ wxWidgets calculator application. I need a way of easily defining the various operations and costants that are usable in the program.
Right now, in my main frame class, I have these arrays declared privately:
const wxString ops[5] = //operations that require a number before and after
{
L"+",
... | Seems like a classic case of map use. You can look toward this:
std::map<std::string, std::function<double(double, double)> ops;
Then populate it:
double add(double, double);
ops.insert({"+", add}); // Maps "+" to the pointer to add()
ops.emplace("-", subtract); // Or even like so
So, then you can directly call on a ... |
68,129,901 | 68,130,372 | Subtraction of unsigned values in return statement of a function that return signed type | I've run into code that simplified looks like this
__int64 fun(unsigned __int64 x, unsigned __int64 y)
{
return x - y;
}
In Visual Studio it works fine even when y>x and we have proper negative value. But is it a UB or valid situation and all other compilers will handle this also properly?
| It is never UB. In the last C++ standard it is always well-defined:
the result is the unique value of the destination type that is congruent to the source integer modulo 2N, where N is the width of the destination type.
In some previous standards, it could have been implementation-defined:
If the destination type is... |
68,129,983 | 68,130,108 | Why write a "class" in the declaration of a class object? | I don't usually write this way but I've seen one code base where it's almost everywhere, e.g:
class prettyClass
{
// just class stuff
};
int main()
{
class prettyClass obj; // class?
return 0;
}
| In C, the tags of structures live in a different namespace to other identifiers. So unless one introduces an alias, they must write struct T for the type name. In C++ (where class and struct are of the same underlying concept) it was made so that the tag is automatically introduced as a regular identifier.
However, the... |
68,130,241 | 68,131,898 | How to create static objects in constructor initializer list | I'm sorry for the long description, I tried to reduce the example as much as possible to illustrate my problem. I have the following code:
#include <concepts>
#include <type_traits>
template<typename T>
concept NumericPropertyValue = (std::is_integral_v<T> && !std::is_same_v<T, bool>) || std::is_floating_point_v<T>;
... | I'm acutally not sure if this is valid or undefined behaviour, but I post it here as an answer because it is to long for a comment.
You could have a static variable in an immediate invoked lambda, that returns a reference to that static local variable.
struct SomeType
{
SomeType()
: p1([]() -> auto& {
... |
68,130,295 | 68,130,406 | Make it possible to use imports of the whole project in the catalog CMake | I want to make a small application using imgui
To run the test window I use the opengl glfw backend
The problem is that the files in the lib/ imgui_gl directory of my project can't access the headers that the file at the root of the project has access to
This is what my CmakeList file looks like
cmake_minimum_required... | You need to tell CMake to link imgui-gl with the imgui::imgui target so it knows where to find imgui.h too:
target_link_libraries(imgui-gl PUBLIC imgui::imgui)
As modern CMake best practice, you may also want to make its include directory part of the interface:
target_include_directories(imgui-gl PUBLIC "${LIB_FOLDER}... |
68,130,770 | 68,130,855 | Why relational operator not working in pointers and arrays | Why while(p != p+sz) is an error in the following code :-
#include<iostream>
using std::cout;
using std::endl;
int main(){
int arr[] = {1,2,3,4,5};
int sz= (sizeof(arr)/sizeof(arr[0]));
int *p = arr, *l = &arr[sz];
while(p != p+sz){
*p = 0;
p++;
}
for(auto i: arr){
cout<<i<<endl;
}
ret... | You will never reach p + x be incrementing the p itself, it will always be exactly x steps from p. You loop puts the pointer out of its bounds and then dereferences it.
You should pre-compute the value using p and then use it:
// ...
auto limit = p+sz; // Pre-compute the limit
while (p != limit){
*p = 0;
p++;
}... |
68,131,116 | 68,131,154 | C++ bool gets random/wrong value? | While debugging my code I have noticed that something strange is going on, So I have added more lines and got confused even more:
#include <iostream>
#include <memory>
struct Node
{
size_t size = 0;
};
class MallocMetadata {
public:
size_t size; /** Effective allocation - requested size **/
bool is_free;
... | It looks like the part node->size - size - sizeof(MallocMetadata) is calculated in unsigned integer.
When calculation of unsigned integer is going to be negative, the maximum number of the type plus one is added and the result wraparounds.
Therefore, the value looks like being big value (128 or more), making the expres... |
68,131,269 | 68,131,639 | Fallthrough in pattern matching | Recently there was a need to write a matching pattern for catching errors, which it actually copes with. But the only thing it lacks in comparison with the same switch is the opportunity to fallthrough. All my attempts to implement this feature have been unsuccessful. Initially, I thought about something like this:
mat... | You might check return type of your "case":
template <typename T, typename Pack, typename... Tail>
bool invoke(T v, Pack&& pack, Tail&&... tail) {
if (pack.v == v) {
auto rv = (pack.fn(), detail::Void{});
if constexpr (std::is_same_v<Fallthrough, decltype(rv)>) {
static_cast<void>( // To... |
68,132,332 | 68,137,128 | Displaying RAM in a rounded integer as a string, including a suffix "GB" | I have 32 GB RAM. The variable ram_in_gb returns 31.917182922363281. I want to round it to 31.9. I expect the buffer to return 31.9 GB string. There was an easy way to do that using wvprintf, sprintf or something like that. I don't remember how I used to do it in the past, so here is my question.
// Usage
wchar_t ram[6... | Although it's 'old' and very "C-Style", you can use the std::swprintf function for this, using the precision field of the %lf format specifier set to 1 (or how ever many decimal places you want to show). You should pass the buffer length as a parameter to your get_ram() function, as the swprintf call needs that:
#inclu... |
68,132,395 | 68,137,116 | Setting minimum and current values on QSpinBox calls valueChanged slot automatically leading to unwanted behavior | I've noticed that setting the minimum and current values allowed for a QSpinBox automatically calls the valueChanged slot. Interestingly, setting the maximum value doesn't result in a slot call. This leads to some unwanted behavior in my simple GUI program, resulting in redundant API calls, sometimes bottlenecking the ... | as I suggested, it is better to 1st setup the object and finally connect the signals and slots
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow)
{
ui->setupUi(this);
//1st set the object up
ui->spinBox->setMinimum(10);
ui->spinBox->setMaximum(20);
ui->spinBo... |
68,132,492 | 68,133,697 | i have problem with recursive function with pointer input | So I'm trying to make an function to fill 1 matrix in spiral order
it kinda look like this
1 2 3
8 9 4
7 6 5
i'm trying to fill the outside first then use same kind of recursive function to fill no smaller inside but i only got 1 inside :
1 2 3 4
12 1 1 5
11 1 1 6
10 9 8 7
here the code that i use
#include <iostream>... | Here's one way to do it with std::array instead. Maybe you could adapt it to your need.
template <size_t N>
using squareArr = std::array<std::array<int, N>, N>;
template <size_t N>
void spiral(squareArr<N>& mat) {
if (mat.empty()) return;
// Counter
size_t cnt{0};
// Limits of the current circle
... |
68,132,857 | 68,133,028 | C++ How can I write a method that takes two matrices and calculates the number of rows and columns | I am writing a matrix handling class to get some practice with the language.
My first method is this:
template<typename T>
T* matrixClass<T>::CreateMat(unsigned int nRow, unsigned int nCol, T& num)
{
matrixClass::m_nRows = nRow; //number of rows
matrixClass::m_nCol = nCol; //number of columns
matr... | The typical shape of these kinds is something like
template <class T>
class Matrix {
private:
unsigned int m_nRows, m_nCols;
T* m_Data;
public:
Matrix() = delete;
Matrix(unsigned int nRow, unsigned int nCol, T* src = nullptr);
Matrix(const Matrix& orig);
Matrix(Matrix&& orig);
Matrix& operator=(const... |
68,133,255 | 68,133,374 | Why "using namespace std;" gives different result when dealing with doubles in C++? | Today, I was trying to answer this post (regarding checking whether a triangle can be constructed), when I encountered a weird result.
With the test of 15.15 35.77 129.07, this piece of code:
#include <iostream>
using namespace std;
const double e = 0.000001;
void f(double a, double b, double c)
{
if (abs(180 - (... | You do have a name conflict: int abs(int) versus double std::abs(double).
With using namespace std;, abs(180 - (a+b+c)) finds both and std::abs is a better match.
Without using namespace std;, abs(180 - (a+b+c)) only finds the former and a conversion to int is necessary, hence the observed behaviour.
What you really wa... |
68,133,471 | 68,133,579 | Initialize array of structs - c++ | I am trying to initialize an array of struct in C++.
This is my struct:
typedef ap_fixed<16,1> ap_fixed_data_type;
typedef struct {
ap_fixed_data_type real_part;
ap_fixed_data_type imaginary_part;
} my_data_struct;
And this is my array of structs:
static my_data_struct IFFT_output[1024];
I would like to ini... | This looks like C to me. If you want to use C++ you can have:
using ap_fixed_data_type = ap_fixed<16,1>;
struct my_data_struct
{
my_data_struct()
: real_part(/*initialization code here*/)
, imaginary_part(/*initialization code here*/)
{
// more initialization code here
}
ap_fixed_dat... |
68,133,817 | 68,160,047 | Why does my metal material looks completely black on meshes? | I was working on my ray tracer written in C++ following this series of books: Ray Tracing in One Weekend.
I started working a little bit on my own trying to implement features that weren't described in the book, like a BVH tree builder using SAH, transforms, triangles and meshes.
NOTE: The BVH implementation is based o... | I finally figured it out thanks to the tips that @Wyck gave me.
The problem was in the normals, I noticed that the Metal::scatter method received a normal that was almost zero. So that's why it was returning black.
After some logging, I found out that the Instance::intersects_ray method was not normalizing the transfor... |
68,133,908 | 68,133,979 | Why do while(std::getline) loops work even though std::getline doesn't return a bool? | I've seen many loops like this to read streams:
while(std::getline(iss, temp, ' ')) {
...
}
But I never understood why it worked. In the documentation for std::getline, it says that it returns the stream, and I don't understand how that is translated into a bool value. Is it reading the eof flag or something? If s... | std::getline inherits std::basic_istream, that inherits std::basic_ios, that implements std::basic_ios<CharT,Traits>::operator bool.
while requires a bool resulting expression, thus
while(std::getline(iss, temp, ' ')) {
...
}
is attempted by the compiler under the hood like as
while(static_cast<bool>(std::getline(... |
68,133,928 | 68,136,029 | SFINAE not always works in C++? | I'm using C++17. I made following code that is supposed to use SFINAE to test if lambda is compilable or not (lambda is always syntactically correct but may be uncompilable e.g. due to absence of some methods used in body):
Try it online!
#include <type_traits>
#include <sstream>
#include <iostream>
#include <tuple>
t... | I think problem is that you try SFINAE based error in body of lambda.
And if I understand this is far to late to recovery from error.
Base idea of SFINAE is to remove incompatible function from overload set, not to to recover from compilation failures, line is bit blurred,
but probably best rule of thumb is that error ... |
68,134,339 | 68,134,492 | How can I call a method of derivitive class within base's class constructor using a pointer to function? | Disclaimer: I am a C developer and it's my first time that I'm trying something like this in C++. I have zero experience with the language.
I have a class Bob that has a pointer to a function myFunction as a private member.
I want to inherit the class Bob and pass a method of the derived class to the pointer function u... | The using FuncHandler = void (*)(int x); is a convenient name for a function pointer.
Alice's void foo(int x); is not a function, it's a member function. A member function is a different kind of thing than a freestanding function.
Fortunately, in this particular case, the code does not need to access the function as A... |
68,134,422 | 68,134,626 | Auto deduce template types (w/ lambda) | I've created the following helper function:
template<typename K1, typename V1, typename K2, typename V2>
[[nodiscard]] extern std::map<K2, V2> transform(const std::map<K1, V1> &map, std::function<std::pair<K2, V2>(K1, V1)> &&function) {
std::map<K2, V2> transformedMap{};
for (auto const &[k, v] : map) {
... | Template deduction can't be done with std::function using lambdas (see also C++11 does not deduce type when std::function or lambda functions are involved).
However you don't really need std::function here at all; you could just take function as a deduced template type-template argument, and then you can constrain it, ... |
68,135,620 | 68,135,762 | C++ templated ring buffer implementation: how to declare and initialize it separately? | I found this implementation of a ring buffer with a mutex on github. I paste the code for you to read:
#include <cstdio>
#include <memory>
#include <mutex>
template <class T>
class circular_buffer {
public:
explicit circular_buffer(size_t size) :
buf_(std::unique_ptr<T[]>(new T[size])),
max_size_(... | You've declare ring on the stack with automatic storage duration. It's not a pointer:
circular_buffer<uint16_t> ring;
But then you try to construct it dynamically on the heap with new, which expects ring to be a pointer type (e.g. circular_buffer<uint16_t>* ring; )
There is no need for dynamic allocation in your sampl... |
68,135,862 | 68,197,070 | Missing DLL in Release but not in Debug | I am porting an old MFC application from Visual Studio 2008 to Visual Studio 2019.
In the process, an old DLL library has been incorporated into the source code to remove the library building step in development.
Now, this program runs and functions perfectly when debugging in the default Debug configuration; however, ... | All the speculation can be avoided, if you install Dependency Walker https://dependencywalker.com and see exactly what is missing where and what the differences of the release and the debug builds are.
|
68,135,889 | 68,136,449 | How to give acess to the components of the fmx to a function in firemonkey C++? | I Basically want to change the state of a component, for that, I was doing something like this
void desenharpilha2(TImage *b1, TImage *b2, TImage *b3,TImage *b4, TImage *b5)
{
b1->Visible = False;
b2->Visible = False;
b3->Visible = False;
b4->Visible = False;
b5->Visible = False;... | Make desenharpilha2() be a member of the FMX Form class that owns the controls you are interested in, eg:
class TMyForm : public TForm
{
__published:
TImage *b1;
TImage *b2;
TImage *b3;
TImage *b4;
TImage *b5;
...
public:
...
void desenharpilha2();
};
...
void TMyForm::desenharpilha2()... |
68,136,266 | 68,136,314 | What is the most efficient way to execute code if a while loop runs at least once? | I have a while loop, and I want some line of code to be run if the while loop runs at least once. If the while loop does not run, I want to skip this line of code.
while(condition) {
doSomething();
}
doSomethingElse();
/* Only run doSomethingElse() if the while loop ran
at least once */
I could set a bool to false ... | It seems you mean
if ( condition )
{
while(condition) {
doSomething();
}
doSomethingElse();
}
Or
if ( bool b = condition )
{
while( b) {
doSomething();
b = condition;
}
doSomethingElse();
}
or
if ( condition )
{
do {
doSomething();
} while ( condition );
... |
68,136,476 | 68,136,520 | GCC converts reference to temporary when doing static_cast to void pointer reference | GCC produces warning when compiling the following code:
void* const & cast(int* const &ptr)
{
return static_cast<void* const &>(ptr);
}
The warning is "returning reference to temporary" (coliru).
Clang compiles the code without warnings (coliru).
Which compiler is right? And why is reference converted to temporary... | Clang 12 here gives me a similar warning. The one you linked to is probably outdated.
The code is broken, you return a dangling reference.
Unlike reinterpret_cast, the static_cast will refuse to reinterpret the reference. Instead it will construct a temporary of type void *1 from the original pointer, and form a refere... |
68,136,830 | 68,190,903 | Can you have 2 identical COM objects? | A general question that could help answer another question I asked before. I believe that COM objects only return a pointer to the created object. So when I try to initialize a COM object twice, do I make two COM objects in my app, or do I make two different pointers to the same object? or perhaps there are two copies ... |
My question is what happens when I run this block twice?
In this specific case, executing the code twice will produce two distinct WebView2 instances. Both instances are then assigned to the same static variable, causing one instance to be irrevocably leaked.
Being an XY Problem this information isn't terribly useful... |
68,137,196 | 68,137,345 | Why does not `std::set<T>::end()` compare equal to `std::set<T>::iterator{}`? | Compile this code :
#include <set>
#include <iostream>
int main(int argc, char * argv[]){
std::set<int> test;
std::cout << (test.end() == std::set<int>::iterator{}) << std::endl;
std::cout << (test.begin() == std::set<int>::iterator{}) << std::endl;
std::cout << (test.begin() == test.end()) << std::endl;
r... |
The domain of == for forward iterators is that of iterators over the same underlying sequence.
So... one can compare iterators from the same sequence with ==.
However, value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type.
So... one can compare two... |
68,137,253 | 68,137,494 | Need help in writing a function for Pisano Period in C++ | int PisanoLength(int m){
std::vector<int> v;
v.push_back(0);
v.push_back(1);
int i;
for(i = 2; ; i++){
v[i] = v[i - 1] + v[i - 2];
int a = v[i - 1] % m;
int b = v[i] % m;
if( a == 0 && b == 1)
break;
}
return (i - 2);
}
Hello, I am new to C++ a... | There are a couple of errors.
One, as already noted, is the access out of bounds of the vector v inside the loop.
The other, sneakier, is that the module is applied after the elements are inserted, while applying it before storing the values avoids integer overflows.
#include <vector>
#include <cassert>
int PisanoLeng... |
68,137,278 | 68,137,312 | static_cast VS reinterpret_cast when casting pointers to pointers | Given the following conditions:
struct A
{
int a;
};
struct B
{
int b;
};
int main()
{
A a {1};
A* p = &a;
Does casting with static_cast and with reinterpret_cast via void* give the same result? I.e is there any difference between the following expressions?
static_cast <A*> ( static_cast ... |
is there any difference between the following expressions?
static_cast <A*> ( static_cast <void*> (p) );
reinterpret_cast <A*> ( reinterpret_cast <void*> (p) );
No.
Are the following expressions the same?
static_cast <B*> ( static_cast <void*> (p) );
reinterpret_cast <B*> ( reinterpret_cast <voi... |
68,137,307 | 68,137,365 | Extern Variable - Multiple Files | When I redefine an extern variable within another file with a different type, the VS compiler is not giving an error message. As far as I know, it should raise an error since it was globally defined as an extern in another file. What is the reason for this behavior?
source1.cpp
extern int x;
source2.cpp
int x = 5;
te... | One Definition Rule
One and only one definition of every non-inline function or variable that is odr-used (see below) is required to appear in the entire program (including any standard and user-defined libraries). The compiler is not required to diagnose this violation, but the behavior of the program that violates i... |
68,137,402 | 68,140,460 | mmap() Allocation Fails With Large Numbers? | On macOS Big-Sur With 32GB of Ram of which 24+ are free I ran the following program:
void *void_new_block = mmap(nullptr, sizeof(MyClass) + 300000, PROT_READ | PROT_WRITE, MAP_ANONYMOUS, -1,
0);
if (void_new_block == (void *) (-1)) {
std::cout << strerror(errno) << std::endl;
return ... | According to the documentation:
Conforming applications must specify either MAP_PRIVATE or MAP_SHARED.
Linux has a similar restriction:
This behavior is determined by including exactly one of the following values in flags
MAP_SHARED
MAP_SHARED_VALIDATE
MAP_PRIVATE
|
68,137,744 | 68,137,871 | Error when using stream insertion on parameter of type wstringstream in GCC but not MSVC | I have a header that I've put together to assist with logging in an application using MSVC v141 (Visual Studio 2017). Since these logging utilities are useful, I wanted to bring it into a project I've just started that is using CMake and MinGW/GCC. The header itself should be standalone, it just performs some magic to ... | operator<< returns a reference to the std::basic_ostream object it is called on, ie (in this case) it returns std::wostream&, not std::wstringstream& like you are expecting. You can't initialize a const std::wstringstring& from a std::wostream&, hence the error message.
Since your LogInfo() macro is creating a new sco... |
68,137,888 | 68,137,928 | Char array gets cleared after function gets() on C++ | I'm trying to learn C++. Sometimes I get confused by C style strings and its functions. I've been using
char var[1];
fflush(stdin);
gets(var);
to write a string into a char array. I don't know if thats the most efficient way but thats how I've been taught.
Now, I'm making a console program in which I read some variabl... | Don't use gets. It is dangerous. It shouldn't be used at all. It has been removed from both C and C++ standards. Don't use gets.
I have a char array, estudios[1]
strcmp(estudios, "N") != 0
A character array of length 1 can only contain the null terminated string of length 0. The string "N" contains two characters: ... |
68,138,320 | 68,138,371 | "no suitable constructor exists to convert from "void () to "std::function<void ()>" error when trying to pass a function as argument | I have an input class that has a method that is supposed to take function as an argument.
#include "pixelGameEngine.h"
#include <functional>
class Input
{
public:
Input() = default;
Input(const Input&) = delete;
Input& operator=(const Input&) = delete;
public:
static void OnDPress(olc::PixelGameEngine*... | DoIteration is not a function. It's a method defined on the TriangleProcessor class. The usual std::function constructor you're trying to invoke is for producing std::function instances from callable objects or function pointers. DoIteration has an implied this argument.
Now, you're running this inside of Run, which as... |
68,138,481 | 68,138,494 | class template with operator overloading | I'm trying to define a class template and an operator overloading:
template<class T>
class complex{
public:
T x,y;
complex(T a, T b): x(a), y(b) {}
complex<T> operator+ (const complex<T>& c){
complex<T> s{x+c.x, y+c.y};
return s;
}
};
int main(){
complex<int> c1{1,2};
comple... | complex<T> s;
This attempts to default-construct an instance of complex<T>.
The problem with that is there is no default constructor for this instantiated template class. The only constructor you defined in your template requires two parameters, and they are completely absent here.
You can add some reasonable, default... |
68,138,668 | 68,140,213 | C++ Why is my program getting the error free(): double free detected in tcache 2 in GDB | So I am having to do this exercise for a course in Udemy and I finished it. But running in on my own machine in GDB I get the error above in the title. I tried checking the values of the pointers for the points prior and after destruction and the values of start behaved strangely on the destructor both of line and copy... | When run, your program will create 3 Line objects:
line in main (denoted hereafter by main::line)
copy in main (denoted hereafter by main::copy)
copy in deep_copy (denoted hereafter by deep_copy::copy)
Since deep_copy::copy is a static object, it remains in memory after its creation till the end of the program run.
C... |
68,138,684 | 68,138,712 | C++: Assigning derived class pointer to base class pointer | Not very familiar with C++, so apologies for the potentially nooby question (though, I couldn't find an answer to this, despite semi-similar questions).
In a codebase I'm working on (sorry, can't share exact code), there's a Base class and a Derived class. I have a pointer to the derived class, d.
At some point, I set
... |
What's super weird is that the pointers end up with different values!
This is actually quite normal. b is a pointer to the base sub object. There's no guarantee that the base sub object is stored at the beginning of the enclosing derived object. In fact, it typically isn't if the class has virtual functions because l... |
68,138,854 | 68,140,459 | Library includes WinRT brocken | I am trying to compile this project: https://github.com/bucienator/ble-win-cpp
After cloning the repository, I got the error "wait_for" is not a member of "winrt :: impl". Using NuGet, I added the Microsoft.Windows.CppWinRT package to the project. But after that my imports of all libraries broke:
#include <winrt / Wind... | Not sure how this used to compile but it's 3 years old so it's possible it compiled with an older C++/WinRT.
The "wait_for" issue is mentioned here: https://github.com/microsoft/Windows.UI.Composition-Win32-Samples/issues/47 and my solution is to add the Microsoft.Windows.CppWinRT package.
Then you will have other issu... |
68,139,306 | 68,139,336 | Size of an array inherited virtually from two classes | Consider the following program:
#include<iostream>
using namespace std;
class base {
int arr[10];
};
class b1: virtual public base { };
class b2: virtual public base { };
class derived: public b1, public b2 {};
int main(void)
{
cout<<sizeof(derived);
return 0;
}
According to me, the array a... | It is probably size of v-table for keeping virtual function addresses. If you check b1 or b2, it is 48 bytes, probably a pointer to v-table(pointer on 64 bit system is 8 bytes). same thing happens for next inheritance increasing size by 8 more.
Side note: I think it is v-table because if you compile your code as a 32-b... |
68,139,406 | 68,139,478 | Default argument with template in C++ | I'm designing an interface, by which users can define a class that tells what they want to do.
The code is something like the following,
#include <stdio.h>
class Dummy{
public:
void do(){ printf("do nothing\n"); }
};
class Task{
public:
void do(){ printf("do something\n"); }
};
template <class TASK>
void fun... | The main issue is this func argument:
TASK &task = Dummy()
It will not work unless it is const. This happens because non-const lvalue reference to type cannot bind to a temporary.
But if you can use const there, you can easily solve your problem:
class Dummy{
public:
void doit() const { printf("do nothing\n"); }
}... |
68,139,697 | 68,142,859 | Boost::qi parse string | I need to parse "title" from the next hls tag
Pattern of the tag:
#EXTINF:<duration>[,<title>]
For example of real tag:
#EXTINF:10,Title of the segment => I need "Title of the segment" phrase
#EXTINF:20,Title => I need "Title" phrase
#EXTINF:12 => I need "" phrase
I wrote the next code
double duration;
std::string t... | You are using namespaces too much. Also, ADL pulls in std::ref for std::string argument regardless, unless ref is parenthesized or namespace qualified.
Over-use of using namespace is is never a good idea (see e.g. Why is "using namespace std;" considered bad practice?) and in this case the message spells out the confus... |
68,139,713 | 68,139,733 | "Case label value has already appeared in this switch" when no duplicate cases can be found | I am working on programming the game 2048 in C++ as an exercise to get familiar with the language. Originally, the code wasn't throwing any errors but I was getting some logic errors in the final product so I thought that the problem could be that I was using the logic gates incorrectly. I looked it up and apparently t... | You should look toward this approach:
case 'A': // If it is A, fall through
case 'a': // If it is a, pick this case
// Do something
break;
// Other cases...
This way, the choice will fall through.
On why your form of the condition does not work:
Condition - any expression of integral or enumeration type, or ... |
68,139,780 | 68,140,750 | OMP data dependency array in a struct | I am new in parallel programming with OpenMP and I am just learning how task and data dependency work.
I develop a simply matrix multiplication (using blocks) program where I define a struct as follow:
struct matrix {
int ncols;
int nrows;
double* mat;
};
Now, for each matrix I do a malloc to obtain a line... | Based on Section 2.19.11 and Section 2.1 of the OpenMP 5.1 specification:
The syntax of the depend clause is as follows:
depend([depend-modifier,] dependence-type: locator-list)
[...]
A locator-list consists of a comma-separated collection of one or more locator list items
[...]
The list items that appear in the ... |
68,140,038 | 68,140,206 | I keeping the error "'std::logic_error' what(): basic_string::_M_construct null not valid" when i am trying to execute my code | I am making a cypher code and when I am trying to execute it I get the "std::logic_error' what(): basic_string::_M_construct null not valid". what is wrong with the code.
#include <iostream>
using namespace std;
string cipher(int key,string text);
string decipher(int key,string text);
int main(int argc, char** argv... | string cipher(int key,string text) {
...
return 0;
}
a return statement applies the appropriate constructor of the return type, if the returned value is not of the correct type. In this case std::string::string(const char*) is used and the null pointer is passed causing the issue. You need to return the result... |
68,140,195 | 68,140,219 | C++ Floating point errors in a loop vs in a single expression | (Disclaimer: I understand that floats can't represent tenths precisely.)
I was messing around in C++ with single-precision floats (to test out rounding errors), and I came across this weird behavior.
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
// set number of sigdigs in output
cout << ... | 0.1 is a double, not a float. So when you add seven of them in an expression, the operations are carried out using double-precision arithmetic and then the final result is converted to single precision. In the loop, you discard the extra precision after each addition. Try it with 0.1f and you’ll get identical results.
|
68,140,200 | 68,189,778 | QWebChannel fails with condition (JS to C++) | Related to this answer : https://stackoverflow.com/a/62210448/16304747
I have tried the example and everything works fine. But I've found something interesting. If I had a condition, the QWebChannel seems to fail (JS to C++).
Here is an example (based on the previous post source) :
QWebEngineView * browser = new QWebEn... | Ok I answer my own question, it was a scope problem. Here is the correct code :
bool testwebchannel_main = true;
if ( testwebchannel_main )
{
QWebEngineView * browser = new QWebEngineView;
browser->resize(QSize(800,600));
browser->show();
browser->load(QUrl("http://www.wikipedia.org"));
QWebChanne... |
68,140,203 | 68,140,371 | How to hide the main tool bar | How can I hide the Main tool bar and make the Render Widget fullscreen.
This is the current image of how it looks like , I want to remove the top tool bar and show the widget which has been promoted to opengl fullscreen.
this is the current code.
void Renderer::FullScreen()
{
if (!fullScreen)
{
widge... | calling the method setVisible(bool) should be more than ok
example:
ui->mainToolBar->setVisible(false);
|
68,140,308 | 68,141,293 | Why my C++ program is not running correctly when I call these two function together? | So I created this program to write vectors of integer into a binary file, then retrieve the data again back.
//vec.cpp
#include <iostream>
#include <vector>
#include <fstream>
template<typename T>
void writeKey(std::string filename, std::vector<T> arr)
{
arr.insert(arr.begin(),(T)arr.size());
std::ofstre... | As already mentioned in the comments by @fabian you are treating your arr.size() as an int (T) when it is actually from type std::size_t. The problem is that std::size_t is 8bytes long (if you are running your program on a 64bit machine) and int only 4bytes.
First, you are converting your std::size_t to an int in the l... |
68,140,506 | 68,155,522 | Compiler error on including a file that it is there | I'm having an issue trying to make Assimp work in an engine I'm doing. I'm trying to add it as a submodule and build it with premake, and I managed to properly include it as a project in the solution, but I'm having an error that I cannot understand.
The error is that some files in assimp are giving me a "cannot includ... | The issue was solved by including in the project many files I didn't include
|
68,140,746 | 68,141,232 | How to modify JSON values in file using json.hpp | I am using the following library to work with JSON stuff : https://github.com/nlohmann/json
I have a json configuration file, and some of the contents in it are as follows:
"mqtt_config": {
"host": "my_mqtt_broker.com",
"password": "admin",
"port": 8883,
"tls": true,
"username":... | Seems you have misunderstood the API, infile["mqtt_config.port"] = 1883; this statement will add a key with string mqtt_config.port
It can be fixed by
infile["mqtt_config"]["port"] = 1883;
Online demo
|
68,140,769 | 68,154,283 | how to create custom boost accumulator for financial ohlcv data | I've the following problem. I've a set of OHLCV (Open, High, Low, Close, Volume) data for a symbol, with the following structure:
struct OHLCV {
double Open{0.0};
double High{0.0};
double Low{0.0};
double Close{0.0};
double Volume{0.0};
};
every data cover a time frame of 1 hour. I need to take many of them ... | Interesting question. It looks clearly like the Sample concept is extensible with custom types, but I don't immediately see the mechanism(s). For one thing, if you could replace OHLCV witf valarray<double> you might be home free:
enum { Open, High, Low, Close, Volume };
using OHLCV = std::valarray<double>;
E.g.:
#inc... |
68,140,823 | 68,235,187 | Showing up a widget inside a widget with animation when button pressed in Qt | I've got a window like that:
If I press the blue button, another widget should be shown with animation and the final view should look like that:
As you realized, the buttons in a layout. I'm trying to make that by changing the minimum size of the blue widget, hiding 2 date pickers and labels. But it's too hard and ug... | I managed with 3 widgets, one QTabWidget and one QToolButton. I put QTabWidget into a widget, then wrote styles for both of them. Then I added a widget, changed it's background color to dark blue, then it's size same as toolButton's. I used QPropertyAnimation for animating the dark-blue widget. When the toolButton pres... |
68,140,866 | 68,144,715 | How to fix c++ indentation in emacs? | I have been trying to setup a c++ environment in emacs, and one of the main problems which I have faced has been trying to get the indentation the way I like it:
By default emacs will make private: and public: be indented to the beginnning of the line when I am making a class:
class Main {
private:
public:
};
I would ... | I solved this by creating my own c-style and customizing the offset for the access-label and label syntactic symbols:
(c-add-style "my-c-style" '((c-tab-always-indent . t)
(c-basic-offset . 4)
(c-offsets-alist (access-label . 0)
... |
68,140,932 | 68,140,998 | Why const by-value structural binding allows the user to modify referenced variable? | I am rather confused with structural binding. Even if I use const and by-value (without &) structural binding as in this example:
#include <iostream>
#include <tuple>
int main()
{
int x = 0;
std::tuple<int&> p(x);
const auto [a] = p;
a++;
std::cout << x << '\n';
}
It still modifies x and prints 1... | See the example on cppreference:
The portion of the declaration preceding [ applies to the hidden
variable e, not to the introduced identifiers.
int a = 1, b = 2;
const auto& [x, y] = std::tie(a, b); // x and y are of type int&
auto [z, w] = std::tie(a, b); // z and w are still of type int&
assert(&z == &a); ... |
68,140,984 | 68,141,653 | Click for "more items..." option on context menu in QT C++ | I have implemented a context menu project in QT by using C++ . I want to have maximum of 5 elements in the context menu to be shown at first. But it has a total of 15 elements and I want user to click on "More items..." or some kind of "Down" arrow button so that the context menu gets expanded to show more than 5 eleme... | First of all, I would suggest you to not use macros SIGNAL and SLOT or if you want to use them - always check connection result. Your intension was to connect to clicked signal of QAction, but there is no such signal.
If you will use function pointer instead of SIGNAL - you will get compilation error which is always b... |
68,141,651 | 68,141,726 | Trying to find an element while iterating through a vector C++ | I'm new to programming, and i'm practicing programming and I am having trouble overcoming this problem.
I'm making a program where the user has to input a student roll number and then the value gets input into a function where the function iterates through the vector and checks if the roll number equals to any of the e... | If you insist on not using an algorithm (suppose it's an exercise):
#include <vector>
#include <iostream>
std::vector<int> rollNumbers = { 1000, 1001, 1002, 1003, 1004, 1005 };
bool CheckRollNumber(int n, const std::vector<int>& rollNums) {
for (const auto& i : rollNums) {
if (i == n) {
std::c... |
68,141,748 | 68,142,072 | C++, Check if Instance comes before Another in memory? | I have 2 pointers to nodes in C++:
MallocMetadata *first_node, MallocMetadata *second_node
How can I check if the first_node comes first in memory before second_node (Both in heap and by first I mean lower address).
Is it true to use: if(first_node < second_node) ?
Let's suppose I want to check if first_node's place... | You can use reinterpret_cast for converting your pointer to std::intptr_t or std::uintptr_t, and then do whatever you want with it, for example:
if(first_node_intptr < second_node_intptr) {...}
// or
if(first_node_intptr % 8 == 0) {...}
But you should remember that:
If the types std::intptr_t and std::uintptr_t exist... |
68,142,356 | 70,525,881 | CMake Dependency Management | I am looking for some insights in proper CMake dependency management. I've come across ExternalProject and FetchContent and both don't completely fulfill my needs. Let me explain in detail:
My project has the following structure:
main_project/
├── CMakeLists.txt
├── external/
│ ├── submodule1/
│ ├── submodule2/
│ ... | Quick update: It seems that Hunter has a git submodule mode: https://hunter.readthedocs.io/en/latest/user-guides/hunter-user/git-submodule.html
Thus it actually fits my use case perfectly.
Have this is in your CMakeLists.txt
include(your/local/path/to/HunterGate.cmake)
HunterGate(
URL "https://github.com/cpp-pm... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.