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,521,262 | 68,523,744 | Visual Studio UWP App target version: Missing new Windows builds (v2009 and higher) | Today I was just testing around with VisualStudio (C++) and wanted to try an UWP App project (with DirectX12). On creating the project I got asked for the target Windows version and minimum supported Windows version for this UWP app. However the newest target version I can select is Windows 2004 (build 19041).
The own ... | Based on the webstie-Windows 10 SDK, there is a note: Windows 10, version 21H1 is a scoped set of features for select performance improvements and quality enhancements. Developers should be aware of this release, but no action is necessary at this time.
A new Windows SDK will not be issued to accompany this version of ... |
68,521,370 | 68,521,574 | C++ concept checking in incomplete-class context | Please consider a C++20 concept program:
struct A {};
template<typename T>
concept DerivedOnceFromA = requires(T t) { { static_cast<const A&>(t) }; };
template<DerivedOnceFromA T>
struct B {};
struct C : A
{
B<C> foo();
};
Here the concept DerivedOnceFromA checks that T can be statically cast to A. B is templat... | Legal? Yes, it's in scope. But you can't glean much of anything useful about it.
[class.mem.general]
6 A complete-class context of a class is a
function body ([dcl.fct.def.general]),
default argument,
noexcept-specifier ([except.spec]), or
default member initializer within the member-specification of the class.
7 A ... |
68,521,432 | 68,521,464 | Declaring static and non-static variables inside loops | I want to use a variable inside a loop, but I don't want it to be re-declared on every iteration. Obviously I can declare it outside of the loop but I wondered what would happen if I declared it as static inside the loop.
To test this I declared both a static and a non-static variable inside a while loop and printed th... | The non-static variable gets created and destroyed on each iteration of the loop.
It just so happens that it gets created, every time, on the same memory address.
However, relying on this, and relying on the variable's contents getting preserved across loop iterations will be undefined behavior.
|
68,521,476 | 68,559,977 | Why is this maze generation algorithm producing one way roads? | I'm trying to write an algorithm to create mazes. The algorithm (DFS) looks like this:
Start at a random cell.
Mark the current cell as visited, get a list of the neighbors. For each neighbor, starting with a randomly selected neighbor:
If that neighbor hasn't been visited, remove the wall between this
cell and that ... | The algorithm produces a one way path as further generation of other paths is not included.
It needs to further produce dead ends after the first on is created. In the algorithm I implemented, I did not account for further generation of other paths;
So when a dead-end is reached, it needs to backtrack through the path ... |
68,521,585 | 68,521,692 | inserting in a vector of vector string from vector of vector pair<int,string> | vector<vector<pair<int,string>>> v(mxfreq+1);
for(it=m.begin();it!=m.end();it++)
{
v[it->second.second].push_back(make_pair(it->second.first,it->first));
}
vector<vector<string>> v1;
for(int i=mxfreq;i>=0;i--)
{
string t=to_string(i);
if(v[i].size()>1)
{
sort(v.begin(),v.end());
}
... | To implement the "simple" solution using range-based for loops nested inside each other, it could be done something like:
// Make sure the destination vector have enough memory allocated
v1.reserve(v.size());
for (auto const& v_pairs : v)
{
// Create a temporary vector for the string
std::vector<std::string> v... |
68,522,130 | 68,522,368 | Why is an intermediate result cast to long before it is assigned to an int? | In many of the coding streams and solutions in Codeforces and Codechef I have seen that when the number is bit large and we need to assign it to int then instead of casting it to int we cast it to long
int maxAreaOfCake(int h, int w, vector<int>& hCuts, vector<int>& vCuts)
{
hCuts.push_back(0);
hCuts.push_back(... | The line in question is
return (int) ((long)horizontal%MOD * (long)vertical%MOD)%MOD;
The casts to long make sure that the expression (long)horizontal%MOD * (long)vertical%MOD is a multiplication of two long values. C and C++ compute the result of arithmetic operations as the "largest" type of their operands; if you mu... |
68,522,152 | 68,522,454 | How can I define a concept that is satisfied by an arbitrary std::vector? | I would like to have a concept requiring an arbitrary vector as the return type:
template<typename T>
concept HasVector = requires (T t) {
{ T.vec() } -> std::same_as<std::vector<int>>; //works
{ T.vec() } -> std::same_as<std::vector<foo>>; //want to put something arbitrary in here
}
Such that we would have so... | We start by writing a variable template to check if a type specializes a template:
template <typename T, template <typename...> class Z>
inline constexpr bool is_specialization_of = false;
template <template <typename...> class Z, class... Args>
inline constexpr bool is_specialization_of<Z<Args...>, Z> = true;
Which ... |
68,522,387 | 68,522,422 | What does Object.Function()()(param,param) mean? | I am reading some C++ code that was designed and written by a lot of programmers that I would consider better than myself. I encountered this line:
rawReceive.Signal()()(*this, completedData);
What is the triple set of brackets mean? I made a small test program, and that doesn't compile. Is there some trick I don't un... | These kinds of mysteries are solved one step at a time:
rawReceive.Signal()
This calls the Signal() method of whatever rawReceive is.
()
Signal() must be returning some unspecified callable object. That is: an object that itself implements an operator() overload. Perhaps it's a std::function. The o... |
68,522,443 | 68,523,276 | QVariant::fromValue(QMap<QString, int>) returns an empty map | I have a function, which parses the file and fills a QMap<QString, int> with entries and returns a QVariant with value of that map:
QVariant FileParser::parseFile(QString filePath)
{
QMap<QString, int> toReturn;
... (parse the file and fill the map)
return QVariant::fromValue(toReturn);
}
When i check the ... | There is a mismatch where you put QMap<QString, int> into the variant, but tried to get QMap<QString, QVariant> back from the result. Either build QMap<QString, QVariant> in parseFile and put that into the variant, or use QVariant::value to extract the correct type on the caller side, i.e.:
qDebug() << words.value<QMap... |
68,522,609 | 68,522,864 | Is it possible to wrap C-style callbacks so that you can use C++ lambdas with them? | I am in the unfortunate position where some C++ code needs to talk with external libraries written in C. To be specific, the Enlightenment suite, which is used, amongst other places, to handle GUIs on certain smart watches.
As an example, let's take the function ecore_timer_add():
EAPI Ecore_Timer * ecore_timer_add (d... | Just add another level of indirection:
auto f = [=]() { /* ... */ };
ecore_timer_add(interval, [](void *data) { return (*reinterpret_cast<decltype(f)*>(data))(); }, &f);
Be wary of lifetime issues here (might want to stuff the capturing lambda f into a std::function and store it in a container somewhere so you can mai... |
68,522,624 | 68,525,266 | Border of the button with the icon | In the constructor, I set the style for the form and buttons:
{
ui->setupUi(this);
this->setStyleSheet("QWidget {background: rgb(49, 54, 59); color: rgb(220, 221, 218); selection-color: lightyellow; selection-background-color: darkcyan;}"
"QPushButton::hover {color: darkcyan; border: 2px... | Referring to Qt's box model, the gap between the border and the icon is the padding.
In the stylesheet, you can set the padding to 0 as followed padding: 0px;
|
68,522,725 | 68,522,777 | Do move constructors and move assignment operators make sense in classes that don't hold pointers as member variables and don't manage resources? | In the articles and books I have read so far, there are only move operations done in classes that hold pointers. Those operations fundamentally work by swapping pointers and setting the old pointers to nullptr. But what happens when std::move() is called on a class without any pointers using the default assignment oper... | An explicit move constructor or a move operator can be specified for any class, whether it has pointer members or not. It is true that move constructors and operators are usually used with classes that have pointers of some kind. But that's only because in these cases there's a way to effect a move that avoids the more... |
68,522,806 | 68,522,830 | Initialization of static bool with lambda and constexpr-if gives adress error | I was trying to implement a certain type trait, but faced this following error.
Here is a simple program that shows the behavior:
#include <iostream>
template<typename T>
struct my_floating_point // just to make a case
{
// static constexpr bool value = std::is_floating_point_v<T>;
// THIS WORKS
static co... | []()
{
// ...
}
A lambda expression evaluates to an instance of an anonymous type. That's what a lambda really is: an object whose type is unspecified. Attempting to assign an instance of this object to a bool is not valid C++.
The good news is that this anonymous type has an operator() overload, that j... |
68,522,958 | 68,523,159 | What information does dwExtraInfo hold for the PMOUSEHOOKSTRUCT? | LRESULT CALLBACK LowLevelMouseProc(_In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
BOOL fpassmove = FALSE;
if (nCode == HC_ACTION)
{
switch (wParam)
{
case WM_MOUSEMOVE: // how do i catch a dx instead of a cursor points?
... | Could not find any documentation on dwExtraInfo directly, but found something related: https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmessageextrainfo:
Return value
Type: LPARAM
The return value specifies the extra information. The meaning of the
extra information is device specific.
One ex... |
68,524,164 | 68,524,208 | cannot assign to array of pointers in c++ | I need to keep an array of pointers in c++. I have a Set which keeps objects of my class. Then I need to iterate over the set and keep the pointer of each item in array. array is 2D by the way. so What I need in summary is :
pointers[1][4] = PinterToAnItem; the reason is I need to delete the item later, So I want to ke... | pointers[(*id).movieId][(*id).shopId] = &(*id);
tries to store in pointers a pointer to a Movie, pointing into the setMovie.
Now consider what happens, after you do this. What if you did:
pointers[42][43]->priceId = 44;
That would possibly invalidate the set (you could have twice the same Movie). That is why the set ... |
68,524,332 | 68,524,537 | Can someone explain the difference between these two codes ? Code is to find the sum of deepest leaves in tree | This is a Leetcode question
int deepestLeavesSum(TreeNode* root) {
int res=0;
int i;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
for(i = q.size()-1,res=0;i>=0;i--){
TreeNode* temp = q.front();
q.... | In the second, you have defined both i and res as local variables in the loop:
for(int i = q.size()-1, res = 0; i >= 0; i--)
This hides the int res = 0; definition at the top of the function. And so when the loop exits, res is still zero.
In the first example, you reset res to zero every time around the while-loop. ... |
68,524,764 | 68,531,049 | How to construct a boost::beast::http::message from std::string? | Is that possible to construct a boost::beast::http::message (specifically I have to construct a boost::beast::http::response<bb_http::string_body>) from std::string, std::string_view or other raw buffer?
Maybe there is some kind of parser? From what I see in Boost.Beast samples, we can either:
receive a response from ... | You can manually invoke the parser, e.g. with this simple skeleton function:
http::response<http::string_body> do_parse(std::string_view input)
{
beast::error_code ec;
http::response_parser<http::string_body> p;
// read headers
auto buf = boost::asio::buffer(sample);
auto n = p.put(buf, ec);
as... |
68,525,164 | 68,566,540 | Windows/C++: why are loaded module memory bytes changing at run-time? | I'm trying to detect whether a loaded module is being patched at run-time by a malicious process. In this case the module is an EXE being run.
My detection scheme is as follows:
MODULEINFO mInfo;
GetModuleInformation(myProc, myInstance, &modInfo, sizeof(MODULEINFO));
//
char* hash1 = hashBytes(mInfo.lpBaseOfDll, mInf... | Paul Sanders' question pointed me in the right direction.
The .data segment of the module was changing during runtime, so excluding that segment from my hash keeps the result the same.
|
68,525,329 | 68,525,779 | C++ class needs to have variable number of references to objects of another class | Let's say I have a C++ class (class A) which needs to have references to variable number of instances of another class (class B). The needed number of references is known at compile time. As far as the usage I would like to have the ability to pass the references to the B type objects to the A type object at compile ti... | The references should probably be (smart) pointers or std::ref objects. I use regular pointers for brevity. Depending on how exactly you want to pass them to the constructor, you can do this:
template <std::size_t nobj> class A
{
std::array<B*, nobj> bs;
public:
// 1 Pass as separate arguments
template <t... |
68,525,924 | 68,526,108 | discount value cannot calculate after case commad | I have some problem with my homework. So this is how it looks like
#include<stdio.h>
int main()
{
char code;
int price,discount;
float total;
printf("Please input price: ");
scanf("%d",&price);
printf("Please input discount code: ");
scanf(" %c",&code);
switch(code)
{
case 'a... | There would be different possibilities.
scanf(" %c",&code);
switch(code)
{
case 'a':
case 'A':
printf("Your discount code is 25 percent\n");
discount = 25;
break;
or you change the input to lower case before or in the switch!
switch( code | 0x60 ) // make it to lower case
with this you don't... |
68,526,152 | 68,526,228 | c++ static_assert fails on both branches of an 'if constexpr statement' | I'm trying to determine at compile time if a specific type is of type std::pair.
When I compile the code below, I get the assertion fail on both branches (that is, both "HERE1", and "HERE2").
If I remove the static_asserts and uncomment the prints, I get what I expect:
That is "HERE1" for is_pair_type<T::value_type>, a... | Constexpr if is supposed to work with template:
Outside a template, a discarded statement is fully checked. if constexpr is not a substitute for the #if preprocessing directive:
void f() {
if constexpr(false) {
int i = 0;
int *p = i; // Error even though in discarded statement
}
}
And
Note: ... |
68,526,284 | 68,526,651 | How to avoid clang-tidy warnings about uninitialized variables | I am looking for the best way to avoid cppcoreguidelines-init-variables warnings with clang-tidy.
std::istringstream in(line);
float x, y, z, rotx, roty, rotz;
in >> x >> y >> z >> rotx >> roty >> rotz;
-> variable 'x' is not initialized, variable 'y' is not initialized, ...
double min_intensity, max_intensity;... | In general you should initialize variables always because reading from an uninitialized variable is undefined behavior.
When extraction from the stream fails then since C++11 a 0 is assigned. However, this is only the case as long as the stream is not in a fail state. Hence, when reading x fails then x will have a valu... |
68,526,360 | 68,526,548 | Can decltype make less recompilation | I'm working on a cpp project, let's say there is such a piece of code:
// header1.h
struct Test {
int a;
bool func(int b) { return a < b; }
};
// header2.h
#include "header1.h"
void myfunc(int aa) {
Test t;
t.a = aa;
bool res = t.func(3);
// something else
}
// header3.h
#include "header1.h"
v... | No, if you change header1.h you have to recompile everything that includes header1.h.
The reason is: how could the compiler generate the code for myfunc without knowing the type of its argument, or without knowing the Test type that you use inside myfunc?
If you change the struct Test, altering the type of its members,... |
68,526,590 | 68,526,999 | const pointer vs pointer: C++ | I'm new to C++ and am attempting to figure out what I'm supposed to do.
Is there a difference in performance between the following options:
const DATATYPE* name
vs
DATATYPE* name
| In this case there shouldn't actually be any performance gain, because the keyword const in your example only tells the compiler that the pointer access will be limited to read-only access (this could only increase performance e.g. in cases with mutex-protected or atomic pointers). But the pointer itself is going to be... |
68,528,561 | 68,528,633 | how to define two dimensional string , not a char vector in C++ | i want to define the two dimensional string , not a char vector in C++ Like this :
vector<vector<char>> vect
{
{"Simple", "Simple", "Simple"},
{"Simple", "Simple", "Simple"},
{"Simple", "Simple", "Simple"}
};
Thanks
| In your declaration the type does not match the initializer. You either want a 2d vector of strings:
std::vector<std::vector<std::string>> vect
{
{"Simple", "Simple", "Simple"},
{"Simple", "Simple", "Simple"},
{"Simple", "Simple", "Simple"}
};
Or a 2D vector of characters, ie a 1D vector of str... |
68,528,591 | 68,528,696 | Fix warning "unused conversion function" in derived class | Originally the base class B was derived from class A. But as C derives from both A and B I got into a nasty diamond shaped inheritance and thus removed the inheritance in B opting for a conversion function to A.
Now I'm getting warnings for classes of typ C, due to conversion to base classes never being used. How can I... | Given an instance of C, your compiler is perfectly capable of converting it to a reference to A, without needing this conversion function. The implicit conversion will be used, and this operator overload will never be used, that's literally what the compiler diagnostic says.
If your goal here is to have B's methods obt... |
68,529,128 | 68,531,911 | Using packed bitfields for non-power-of-two byte integral members of a structure | I have some binary data that contains structures that are defined as follows:
s1:
a - 1B
b - 4B
c - 2B
d - 8B
s2:
a - 1B
b - 3B
c - 2B
d - 6B
It uses Big Endian byte order.
I parse s1 with the following code:
#include <endian.h>
#include <stdint.h>
#include <string.h>
struct [[gnu::packed]] s1 {
uint8_t a;
... |
Is the code above correct in both C and C++ (GNU dialects)? Or does it rely on Undefined Behavior?
Well, it's UB according to the standard.
According to GNU, all these details are "Determined by ABI".
According to Agner Fog's summary of x86 calling conventions [pdf],
Objects of structures and classes are stored by p... |
68,529,289 | 68,529,507 | Rcpp: "overloaded function with no contextual type information" for R::dbeta | I have C++ code with the Rcpp package included.
Within a function I have the following loop:
for(int i=0; i<N; i++){
double yi = y[i], xi = X_chain[i];
double numerator = R::dbeta( yi, alpha_par, beta, log=false );
double denumerator = R::dbeta( xi, alpha_par, beta, log=false );
double alpha = std:... | I am not sure I am reproducing the same issue as you have when just running R::dbeta(0.5, 1.0, 1.0, log = false) but I don't think you should name parameters in C++. E.g. simply doing R::dbeta(0.5, 1.0, 1.0, false) works for me.
|
68,529,601 | 68,530,258 | Nodejs c++ addon: Not able to access Array elements | I want to access the elements of an array that is passed in a function as an arg from the js side.
The code is like this:
void Method(const FunctionCallbackInfo<Value> &args){
Isolate* isolate = args.GetIsolate();
Local<Array> array = Local<Array>::Cast(args[0]);
for(int i=0;i<(int)array->Length();i++){
... | Hard to answer without knowing which exact version of v8 you're targeting, but in the current doxygen documentation there are two overloads for v8::Object::Get:
MaybeLocal< Value > Get (Local< Context > context, Local< Value > key)
MaybeLocal< Value > Get (Local< Context > context, uint32_t index)
So I think y... |
68,529,662 | 68,529,709 | May I call std::terminate directly? | I have a non-void function which returns a value to be used as an input of a class constructor, but there is a possibility for that value not to be available, so I want to return the value in case of success or just terminate (std::terminate()) the application in case of failure before the function return.
Since std::t... |
... I obliged to throw an exception and let the runtime decide whether the program is terminated or not?
It is up to you. If you want to be able for an exception to be caught somewhere up the call stack then you should throw an exception. In cases you want to terminate because there is no way to recover then calling ... |
68,529,796 | 68,530,056 | Google test save one argument into another argument | Is possible to save one argument from a mock function call into another ? for instance argument 1 into argument 4 ?
EXPECT_CALL(mock_, up_func(_, _, _, _)).
.WillOnce(DoAll(SaveArg<1>(Argument4), Return(LSUCCESS)));
| You can do that either with Invoke
EXPECT_CALL(mock_, up_func(_, _, _, _))
.WillOnce(
WithArgs<0, 3>(
Invoke([](auto in, auto& out){out = in; return LSUCCESS;})
)
);
Or using a helper variable
int helper;
EXPECT_CALL(mock_, up_func(_, _, _, _))
.WillOnce(
DoAll(
SaveArg<0>(&helper),
... |
68,529,875 | 68,535,941 | filesystem error: cannot copy: File exists | I have a .txt file in folder A and I'm trying to copy it to folder B using this code,
#include <iostream>
#include <filesystem>
int main() {
try {
std::filesystem::path src("C:\\Projects\\test.txt")
std::filesystem::path dst("C:\\Projects\\Notes");
std::filesystem::copy(src, dst, std::file... | Turns out I have to give the file name and it doesn't automatically copy the file into the folder like with high level languages.
So,
std::filesystem::path dst("C:\\Projects\\Notes");
becomes
std::filesystem::path dst("C:\\Projects\\Notes\test.txt");
|
68,531,344 | 68,553,466 | Compile error inside boost: "use of undefined type 'boost::mpl::bool_<true>" | I am getting this strange error when compiling a large CPP file, at this line:
#include <boost/regex/v4/regex.hpp>
Error C2027 use of undefined type
'boost::mpl::bool_'
C:\github\microsoft\vcpkg\installed\x86-windows\include\boost\regex\v4\basic_regex_parser.hpp 59
In bool_fwd.hpp I see:
typedef bool_<true> true_;... | This isn't supported, see same issue in https://github.com/boostorg/regex/issues/145
|
68,531,392 | 68,531,743 | insertion function to insert elements in a linked list at tail | I want to implement insertion of element at tail of linked list, I want to do it using member function, currently I'm able to do it by creating a function outside of struct, please help me what should be modified to implement it as member function.
my conventional approach:
#include<iostream>
using namespace std;
struc... | This is a working example. The idea is that, from the member function, you recursively call node::Insert until you reach the last element, and then only there you create the next one.
#include <iostream>
struct node{
int data;
node *next = nullptr;
node *Insert(int v);
};
node *node::Insert(int v)
{
i... |
68,531,827 | 68,531,934 | Instance a variable declared in the header file without default constructor | I've just started to learn C++ using Visual Studio 2019.
I'm trying to move the variable declaration from a class method to the header file. Originally, this is my class:
The header file:
#pragma once
#include <string>
class MyClass
{
public:
MyClass();
~MyClass();
bool Connect(std::string host, std::st... | In your .h file, the compiler doesn't know what the TelnetClient type looks like, as you are only forward declaring it, so you can't declare any instances of TelnetClient in your header, only TelnetClient* pointers and TelnetClient& references. You would need to move the #include "TelnetClient.h" statement from your .c... |
68,531,989 | 68,532,312 | Cout doesn't display all fields (C++, MySQL) | I have a function:
int main()
{
MySQL::Connect("127.0.0.1", 3306, "root", "", "player");
MySQL::ExecuteQuery("select * from player");
while (row = mysql_fetch_row(res))
{
std::cout << row[2] << "\n";
MySQL::SetDatabase("account");
MySQL::ExecuteQuery("select * from account"); /... | Your two calls to ExecuteQuery share state, namely the "currently active query" and the buffered resultset you downloaded with mysql_result_row.
This is called a non-reentrant function.
Some options:
have a dedicated connection for each query
Do a single query that somehow combines the results (ie JOIN the players and... |
68,532,134 | 68,532,335 | My implementation of the grid traveller problem only works for small grids | I am attempting this problem at 38:39 into this free code camp video: https://youtu.be/oBt53YbR9Kk?t=2361
The question is as follows:
Say that you are a traveller on a 2D grid. You begin in the top
left corner and and your goal is to travel to the bottom right corner.
You may only move down or right.
In how many ways ... | The problem is in your comparison operator overload:
x + y < rhs.x+rhs.y
This check is not enough since it just compares the sum of coordinates. You should write one that checks the coordinates in a certain order:
x < rhs.x || x == rhs.x && y < rhs.y
Otherwise, for example, grids with coordinates (1, 5) and (2, 4) ar... |
68,532,268 | 68,532,776 | Is it possible to access other array elements than the given by the index from the for loop using target? | I understand well, I think, why it is possible to access A[i] rather fast using all the threads in a GPU. In the following 0<=A[i]<N.
However, what about the locks and B[x] in the following code? Will two access to lock[1] and lock[2] not block for each other so I don't get any parallelizing at all?
const int N=10000;
... |
Will two access to lock[1] and lock[2] not block for each other so I don't get any parallelizing at all?
Locks are independent. A thread holding one lock locked will not prevent other threads from acquiring different locks.
Even so, if your code has to make use of locks to function correctly then that will slow it, ... |
68,532,667 | 68,576,918 | Static wxRichTextControl? | I want to create an Help page for my wxWidgets application, which consists of only text of various fonts, sizes and colors. I tried achieving that with wxStaticText's and sizers but I was having trouble so I switched to a wxRichTextCtrl, which I like to use. The problem is, the text should of course be non-modifiable. ... | The best solution for "rich" static text is wxHtmlWindow: this allows you to just define your help contents in terms of simple HTML which is usually more than enough.
|
68,533,579 | 68,535,721 | How to approach reporting errors in an interpreter? | For learning purposes I'm writing an interpreter of arithmetic equations in C++. When the user enters incorrect input, I'd want something like this to appear: (> is user input)
> 4+2*6+#-1
Lexer error: incorrect character '#' at position 7
What is the best way to approach that? Should I use exceptions, and if yes then... | The trick is to maintain source location data all the way, through all the compilation passes. This way you can report
syntax errors, which are the most trivial, you have all the source location data handy at this stage, along with (depending on a parsing technique you're using) hints of what you'd rather expect at th... |
68,534,053 | 68,534,153 | Setting a default value for a bool | I am working on a Queue class using threads in C++ (Windows 10 Visual Studio).
In my constructor, I start by setting a boolean error value to false. Immediately after, I attempt to initialise the critical section. If the there is a problem, the bool is set to true, otherwise it stays as false. I check this value in the... | A much better approach is to prevent the queue from existing at all if the critical section cannot be created. This establishes a tighter class invariant for the Queue class, which simplifies its implementation.
This is done by throwing an exception:
Queue() {
// check init
if (!InitializeCriticalSectionAndSpi... |
68,534,223 | 68,534,481 | initializing a two dimensional vector from a 2 dimensional array in C++ | I have this code:
int a[4][4]=
{
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
}
And I want to initialize B which is defined as below:
vector<vector<int>> b;
I know that I can do this with two loops (and possibly with one loop as documented here: https://stackoverflow.com/a/4092996/654019
But is there... | You could use for_each if you just want to avoid writing a loop and let the algorithm do it for you: https://godbolt.org/z/jxT8vfhPr
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
int a[4][4] = {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};
s... |
68,534,267 | 68,550,550 | how to compile an app that can be run on Windows system using cmake | I use cmake to help to complie a appliction with MinGW32 on Windows 8.1 x64 system.
The goal is to make a application can be run in windows from Windows XP to Windows 10 .
Using the combination of static and dynamic compilation ,Since some dll cannot find static libraries。
some major code
SET(toolchain_lib "E:/mingw... | /SUBSYSTEM:WINDOWS,5.1 is not a GCC flag.
You probably want to use something line -D_WIN32_WINNT=0x0501 to specify Windows XP compatibility (see: https://learn.microsoft.com/en-us/cpp/porting/modifying-winver-and-win32-winnt?view=msvc-160)
|
68,534,309 | 68,535,647 | Move the position of a Gtk::Widget inside the Gtk::Grid | I want to move the location of two widgets inside a grid. How can I do it? What I have got so far:
pWidget1->unparent();
pWidget2->unparent();
pGrid->attach(*(pWidget1), 0, 5);
pGrid->attach(*(pWidget2), 0, 7);
show_all();
Sadly, this code does not do what I want: the location ... | The following example, written in Gtkmm 3.24, creates a window in which three buttons coexist inside a Gtk::Grid. clicking the Switch button will swap both A and B inside the grid. The key idea here is to
Gtk::Grid::remove the widgets to move.
Gtk::Grid::attach them to their new locations.
Here is the code:
#include ... |
68,534,495 | 68,536,744 | how to make my executable not rely on sfml dll files [c++] [minGW] [g++] | Perhaps I can "create" these necessary files by having them linked to the exe, and store them in a temp folder when the program launches, and if that's possible how please? I've tried messing around with compiler options but nothing seems to work.
| In order your executable to not rely on DLL files, you should link them statically. SFML gives you that option by using their "sfml-xxx-s-d.lib" (for Debug) and "sfml-xxx-s.lib" (for Release) libraries, as stated in the documentation.
If you want to get rid of these DLLs and have SFML directly integrated
into your exe... |
68,534,699 | 68,534,853 | Which operators are automatically defined for scoped enumerations? | For unscoped enumerations, the answer is "most of them" because of the implicit conversions to the underlying integral type. However, scoped enumerations do not have this implicit conversion. Instead, some but not all of the operators available for unscoped enumerations are defined for them.
#include <iostream>
enum c... | The relational operators are opted in via [expr.rel]
The usual arithmetic conversions are performed on operands of arithmetic or enumeration type. If both operands are pointers, pointer conversions and qualification conversions are performed to bring them to their composite pointer type. After conversions, the operand... |
68,534,725 | 68,535,680 | function template won't compile in VS2019 express | I have a project with quite a lot of function templates that I wrote back in Visual Studio 2017, and it always worked fine. Now I have to build it in VS2019, because I need to include the lib in another project that is written in VS2019, and the thing won't build.
There is one function template it seems to take issue w... | There is a circular dependency problem.
In Oparse.h, you first include OpModel.h that requires_ModelPtr in implementation of Serialize , but_ModelPtr is only defined later in the header.
You need to forward declare the template method.
In OpModel.h, write this instead:
namespace Oparse
{
template<typename T> class ... |
68,534,795 | 68,535,116 | How to iterate over a subset of row-aligned pixels | I have a buffer of BGRA data from a PNG that's row-aligned.
unsigned int *data_; // bgra buffer described by
// image_.ximage_->width and
// image_.ximage_->height
I'm interested in sampling a subimage within the image. The subimage is defined by an origin and height and wi... | Hard to say what's faster or slower without testing, but a flat index would do the trick:
for (uint idx = 0; idx<reg.height*reg.width; idx+=step) {
uint i = idx%reg.height + reg.x, j = idx/reg.width + reg.y;
img(i,j) = 'X';
}
Testable here: https://godbolt.org/z/7jjGWj8rn
|
68,534,952 | 68,538,869 | Advice needed: does it make sense to include fmt lib in header-only library? | I'm currently ending the development of a C++ header-only template library for grid-based quantum computations and I'm considering replacing an old logging module that I've wrote nearly at the beginning.
I know that it sounds a little bit weird to have a header-only library printing stuff to stdout (and files), but I m... | I wouldn't if I were you.
A header-only library implies being minimalistic. fmt is the opposite of that.
A header-only library implies being user-friendly. Forcing a large dependency on a user isn't very friendly.
If you've gone that far without needing better logging tools, chances are, the tools you are using are al... |
68,536,114 | 68,536,839 | Raw Input - recive WM_INPUT while window/program is in background | I am trying to monitor and printout the RAWINPUT from a mouse sent to the foreground window, or just all RAWINPUT from the mouse in general.
the global hook LowLevelMouseProc does not work for me because it returns a MOUSEHOOKSTRUCT that does not give me the dx and dy.
The Raw Input API mentions that for WM_INPUT recei... |
But I have no idea how to receive WM_INPUT while the program is in the background.
You need to specify the RIDEV_INPUTSINK flag when registering the device, per the RAWINPUTDEVICE documentation:
dwFlags
Type: DWORD
Mode flag that specifies how to interpret the information provided by usUsagePage and usUsage. It can ... |
68,536,752 | 68,536,942 | Reading a csv file and storing the data in an array using C++ in Visual Studio Code | I have a csv file called "input.csv" (UTF-8, no CR, LF only). It looks like
it has 51 rows and 3 columns. I have to read the csv file and perform some mathematical operations on the data. I have tried couple of codes to read the csv file in c++ but none of them seem to work. I tried these link
How to read a csv file ... | The first issue is that you are reading floating point numbers into integer vector, so that is going to lose information.
// std::vector<int> m_data; // Don't need this if you know
// there is always three values.
// std::string m_line; // Don't need this.
... |
68,536,935 | 68,541,790 | Initializing a multi-dimensional array in C++ 20 using an expression list | Is it correct such an initialization of a multi-dimensional array in C++ 20 using an expression list?
int a[][3]( 1, 2, 3, { 4, 5, 6 } );
At least the C++ compiler of MS VS 2019 does not compile such a declaration
This declaration
int a[][3]( 1, 2, 3, 4, 5, 6 );
is not also compiled while this declaration
int a[][3](... | Rereading the provided quote especially its this part
the ith array element is copy-initialized with xi for each 1 ≤ i ≤ k
It seems that such an initialization like this
int a[][3]( 1, 2, 3, { 4, 5, 6 } );
is indeed incorrect because the element of the array a is in turn an array of the type int[3] and to initialize... |
68,537,413 | 68,540,362 | C++ SymGetLineFromAddr has error code 126 | I wrote a wrapper around some WINAPI functions. However, SymGetLineFromAddr always fails and has a error of 126. After doing some research, it seems like it is because SymInitalize is either not being called or failing. Debugging shows that SymInitalize is in fact, not failing. What's even more confusing is that SymFro... |
SymFromAddr works perfectly fine.
It works because it doesn't truncate its pointer argument:
SymFromAddr(process, (DWORD64)(ptr), 0, symbol);
// ^^^^^^^^^ preserves 64 bits of information
Contrast that with the call to SymGetLineFromAddr:
SymGetLineFromAddr(process, (DWORD)(ptr), &tmp, line)
// ... |
68,537,891 | 68,537,975 | Illegal instruction signal for arrow parquet. How to build with Conan without AVX2 | I'm using conan to build a library that uses arrow parquet. I built arrow myself because I couldn't find versions in conan center that included parquet:
In my conanfile.txt
[options]
arrow:shared=True # I tried both shared and static
arrow:parquet=True
arrow:with_snappy=True
conan install .. --build=arrow
It builds ... | In arrow, the level of SIMD instructions used is controlled by these cmake options
define_option_string(ARROW_SIMD_LEVEL
"Compile-time SIMD optimization level"
"SSE4_2" # default to SSE4.2
"NONE"
"SSE4_2"
... |
68,538,346 | 68,538,420 | OpenGL clear color alpha channel not working | I am making a game in OpenGL and C++ and I want to add a little red tint to everything. I decided to do this by clearing the screen red after rendering everything but making the alpha channel a low number Here is what I tried
:
// inside main function (called once)
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_... | When you clear the framebuffer, you clear the framebuffer. You aren't doing a rendering process (which is the only time that blending matters). You're setting the value of every pixel in the framebuffer to a specific value. Just like when you set a block of memory to a value, you're setting that memory to that value.
I... |
68,538,421 | 68,538,589 | Pointer Ownership in the Win32 API | I'm trying to understand how the Win32 API handles Pointer ownership.
The concrete example i am looking at right now is the ownership of pointers to strings that i pass to the API and that i get from the API.
Take for example the SetWindowText function. It takes an LPCSTR, a pointer to a null terminated widestring.
Ano... | The general answer is: Read the documentation for the function in question. If it doesn't say anything about taking ownership, then it's a good bet that it doesn't take ownership and you need to deal with the memory.
Although it's been a while since I did much significant work at the level of the Windows API, I recall ... |
68,538,584 | 74,420,388 | VSCode debugger freezes | I am trying to debug a C++ file in VSCode. The debugger works fine while it is in the main() function, but as soon as it enters a function, the debugger freezes and the control panel no longer works(except the stop button). In the left bar, it shows the loading icon next to "Local" variables, which loads perpetually.
I... | I 've met this situation exactly before.
just change configurations [type] from "cppdbg" to "lldb" in launch.json solve this problem.
hope it helps you.
|
68,538,728 | 68,539,892 | threadprivate with initialization of function-scope static variables | I am testing out how threadprivate clause works in openMP. I set up the following simple test case
#include <iostream>
#include <omp.h>
void func(){
static int some_id = omp_get_thread_num();
#pragma omp threadprivate(some_id)
#pragma omp critical
{
std::cout << "id:" << some_id << std::endl;
std:... | I think this is a bug in the implementation. The OpenMP API specification requires that the some_id variable is initialized by each of the threads:
Each copy of a block-scope threadprivate variable that has a dynamic
initializer is initialized the first time its thread encounters its
definition; if its thread does no... |
68,539,554 | 68,539,597 | The difference between passing double pointer and pointer as an argument |
pass * as a function parameter
#include <iostream>
class A {
public:
A() {}
};
class B : public A{
public:
B() {}
};
void foo(A* a) {
a = new B();
}
void ff() {
A a;
foo(&a);
}
pass ** as a function parameter
#include <iostream>
class A {
public:
A() {}
};
class B : public A{
public:... | Passing double pointer and just a pointer are not the same
void foo(A* a) {
a = new B();
}
Change an input pointer to another value. The result will not reflect in the callee ff().
It's merely change the argument.
void foo(A** a) {
*a = new B();
}
Change a pointer to another pointer and change the value, which... |
68,539,811 | 68,540,901 | sorting two dimensional array... exception occurred (C++) | while solving problem, Sorting two dimensional arrays was needed. I used merge sort, and set
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
using namespace std;
int*sorted[1000];
void merge(int** list, int left, int mid, int right);
void merge_sort(int** list, int left, int right);
int main(... | In your case it isn't really sorting 2D array, just array of pairs of ints.
You compare them by the second element. Another thing, you really don't want to use malloc nor new in this case. So, let's go through your solution improving it slowly.
Remove unnecessary mallocs.
malloc is a remaining C function, that should... |
68,540,061 | 68,571,558 | How to get number of used columns in a row in QXlsx | I have an excel file that I'm trying to parse in Qt Framework using QXlsx library. I'm Stuck on calculating the number of last Used column in a row, because each row has a different number of used columns. see the picture below as an example.
I have already tried the following code
QXlsx::Document doc("data.xlsx");
in... | So after searching and asking for help the way to get the last column in QXlsx library as suggested in this replay is to check for non-empty cell in reverse in each row and break the loop if i found the last non-empty cell. As following
QXlsx::Document doc("data.xlsx");
QVariant cell;
int number;
int lastColumn = doc.d... |
68,540,816 | 68,540,921 | What is the status of C++20 coroutines support in Clang? | According to cppreference.com ( https://en.cppreference.com/w/cpp/compiler_support#C.2B.2B20_features ) Clang has partial support of C++20 coroutines since version 8:
But if in Clang trunk (which is upcoming version 13) I write
#include <coroutine>
it results in the error( https://gcc.godbolt.org/z/rTfjbarKz ):
/opt/... | Note that the first error is in the GCC standard library, and from that it can be deduced that the -fcoroutines option is for GCC not Clang.
To build with the Clang libc++ you need to add the option -stdlib=libc++ instead. But that will lead to the <coroutine> header file not being found instead.
Since Clang coroutines... |
68,541,276 | 68,541,670 | How delete item and itemWidget correctly from QListWidget | i dont understand how correctly delete item and itemWidget from QListWidget.
I should at first delete itemWidget, then item
lstWgt->removeItemWidget(item);
delete item;
Or i can
auto *pItem = lstWgt->takeItem(2);
delete item;
| As far as I understand the Qt documentation and by my Qt 4&5 experience, both should be correct, however your last delete should be the Pointer you get returned by takeItem so delete pItem instead of delete item in your second snippet.
|
68,541,794 | 68,542,220 | How to sort an array(in ascending order) based on the ranks of each element which is in the another array? | Let two arrays
arr = [1,5,6,3,10]
rank = [100,0,1,100,2]
Based on the rank array (Which holds the ranks of the mirror elements in the arr) the result should be
[5,6,10,1,3]
The first element in the result is 5
(The index of 5 in arr is arr[1] and the index of 0 in rank is
rank[1]. This is how we have to take rank... | The short answer is: std::sort.
The long answer depends on how you store the values and the ranks, whether you can afford to copy them, and whether you also need the ranks sorted. For the following I assumed that you do not need the ranks sorted and the sorting is done on the original container of values. It is not the... |
68,541,837 | 68,541,946 | Vertex Buffer Abstraction in OpenGl | I have been trying to write some classes to abstract OpenGl. So far I have written a VertexArray class that uses template functions which are working fine so far. However I have encountered problems with my VertexBuffer class that I have not been capable of fixing.
C++ and OpenGl are still fairly new to me so the solut... | You have to store vb in some kind of smart pointer or add move semantics to VertexBuffer.
vb = VertexBuffer(&vertices[0], sizeof(Vertex) * vertices.size());
^^^ [1]
in [1] temporary VertexBuffer is created, then by operator =, the member ID is copied in shallow way into vb and finally at the end of expression tem... |
68,541,925 | 68,567,779 | How to embed opencascade V3d_View in gtkmm widget | I'm trying to port the code from https://github.com/eryar/occQt to gtkmm, by creating a custom widget and overriding the Gtk::widget::on_realize() method like
void OccView::on_realize() {
// Create Aspect_DisplayConnection
Handle(Aspect_DisplayConnection) display_connection = new Aspect_DisplayConnection();
... | I haven't used GTK since university, so my experience is pretty basic here.
There are two basic approaches for embedding OpenGL-based viewer into GTK:
Ask OCCT to create OpenGL context for a native window taken from a normal Widget or entire window.
Wrap existing OpenGL context created by GUI library itself, e.g. Gtk:... |
68,542,084 | 68,544,620 | initialise failing for const unordered_map < std::string, int[4] > (clang 12 / c++20) | I guess I am doing something wrong with the initialisation here, and would like to know what, and why! (I'm not worried about using int[4] here - it's a const map which will be script-generated).
#include <unordered_map>
#include <string>
int main() {
const std::unordered_map<std::string, int[4]> m {
{ ... | You may not use arrays as element of a map, nor as element of any other standard container.
This is because Arrays are not first class constructs in C++. They are not Copy Constructible nor Assignable which are requirements for values of std::map.
You can however have an array as member of a class and such wrapper clas... |
68,542,235 | 68,542,804 | how many bits is allocated for an integer when allocating on heap | So I have been tinkering with C++ lately and I allocated memory for an integer like this:
int* p = new int;
As I thought, an integer is usually 4 / 3 bits depending on the system architecture,
but when printing the size of the memory that this pointer allocates:
cout << sizeof p << " is the size of an int" << endl;
//... | The number of bits occupied by an int is CHAR_BIT*sizeof(int).
#include <climits> to get the constant CHAR_BIT defined.
Though in the modern world you're very likely to find CHAR_BIT is 8 except some specialised hardware. On some digital signal processing devices it may even be 64.
I think you may have confused 'bit' (... |
68,542,266 | 68,542,556 | Are the same type variables in struct guaranteed to be in contiguous in memory wothout any padding? | I am currently working with Vulkan and want to create reliable way to enymerate through all physical device features without needing to call them by name. Currently I am getting pointer to struct and enumerating in loop like in array:
VkPhysicalDeviceFeatures Features{};
uint32_t size = sizeof(VkPhysicalDeviceFeatures)... | It is not guaranteed that the structure members are continuous in memory. you can enclose the structure definition by #pragma() statements.
#pragma pack(1)
typedef struct m_struct {
uint32_t a;
uint8_t b;
int32_t c;
} M_STRUCT;
#pragma pack() // restore the default packing
In the example above, the struct... |
68,542,352 | 68,542,919 | would sending a const to a function that gets a non const param be considered an error? | let's say we have this function
void something(int a)
{}
and in main function we do this
int main()
{
const int a=7;
something(a);
}
would that be considered an error?
| No.
When you call the function, a copy of the parameter is made:
const int x = 0;
something(x);
It is similar to
const int x = 0;
int y = x; // completely fine, no error
Further, consider that when you pass by value, using const on the argument only matters inside the function:
void something(const int... |
68,542,388 | 68,542,576 | When submitting to Codeforeces output isn't the same as in the console | I'm trying to solve this problem: (https://codeforces.com/contest/1363/problem/A), and in my console when I give it the Input of the first example it outputs the right answer. but when submitting the code it says that my output was wrong and I dont know what's the problem.
this is my code:
#include <iostream>
#include ... | The behaviour can be different, because your code has Undefined Behaviour - variable c2 in function solve can be used uninitialized.
|
68,542,633 | 68,543,208 | illegal glutInit() reinitialization attempt: How can I de-initialize glut? | I implemented a class function that call glutInit() if the class is activated. Like this:
void myViewer::Activate() {
int argc = 1;
char* argv[1] = {const_cast<char*>("none")};
glutInit(&argc, argv);
}
void myViewer::Deactivate() {
...
}
How can I "de-initialize" the Glut component? Calling the activation func... | The Initialization section of the documentation clearly states:
The primary initialization routine is glutInit that should only be
called exactly once in a GLUT program.
You are also not using glutInit as specified. Trying to provide fake arguments is asking for trouble. They want the original (argc, argv) for a reas... |
68,542,964 | 68,543,764 | how many channels does a bayer image have? | i am working on bayer images. i use basler camera and i get bayerBG8 image from it. in pylon i can directly converted to RGB, but i want to save the bayer image so i need to specify its channels to define a mat file. when i use 1 channel for it i get gray scale image and if i choose more than on channel, images repeate... | Bayer filter is a technique to use a single-channel image sensor to receive color image by defining which pixel should represent which color, so a bayer image should have one channel.
|
68,543,775 | 69,207,957 | Using BOOST_STACKTRACE_USE_BACKTRACE on Windows with MinGW64 | I am building a Qt application using Windows and MinGW64. I need to use Boost Stacktrace to generate stack traces like the Linux build of the application already does.
The corresponding switch BOOST_STACKTRACE_USE_BACKTRACE (as described in https://www.boost.org/doc/libs/1_65_1/doc/html/stacktrace/configuration_and_bui... | I solved this problem (and some more issues) by switching to MSYS2 UCRT. MSYS2 provides a precompiled libbacktrace package.
|
68,543,799 | 68,543,901 | c++ passing an object as function parameter to a function expecting an std::optional | I have a function func(std::optional<A>& a) and I want to call it using an instance of A like in this code:
#include <optional>
#include <iostream>
class A
{
public:
explicit A(int a) : m_a(a)
{}
~A() = default;
int get() { return m_a; }
A(const A&) = delete;
A(A&&) = delete;
A& operator... | If another layer of indirection is not a problem you can use a std::optional<std::reference_wrapper<A>> :
#include <functional>
//....
void func(const std::optional<std::reference_wrapper<A>>& a)
{
if (a.has_value()) {
std::cout << a->get().get() << std::endl;
} else {
std::cout << "no value"... |
68,544,396 | 68,551,529 | Only accepting numeric input from user | I am currently trying to accept only numeric input from the user in my program.
I have done a lot of research but all the example code given can still accept the input such as 10abc.
This is a feet to meter converter.
include <iostream>
using namespace std;
bool isNumber(string feet){
for (int i = 0; i < feet.leng... |
So, is there any method that only accept pure numeric and also include decimal point?
The function std::strspn will return the length of the string that contains only characters that are found in another string. So, if you want to allow both decimal digits and decimal points, you could use the following for input val... |
68,545,505 | 68,545,541 | C++: Why is the time shown by __TIME__ earlier than doing ctime(&time(NULL))? | I have the following code in C++:
#include <iostream>
#include <ctime>
int main()
{
time_t t = time(NULL);
cout << ctime(&t) << __TIME__;
return 0;
}
The output that I got was something like this:
Tue Jul 27 19:04:33 2021
19:04:31
In fact, all of my runs showed that the time displayed by __TIME__ is 2-3 s... | __TIME__ is a preprocessor macro that gets replaced by the current time when you compile the code.
time() from ctime returns the current time when you execute the program.
You will notice that when you run the same program again (without recompiling) the time from __TIME__ will not change.
|
68,545,557 | 68,546,170 | Static local variable and auto | In the code snippet below, is the local variarble result1 static? Is the keyword static mandatory do declare a static local variable or would auto suffice?
static int ExpensiveInit() {
...
}
class Foo {
void Bar() {
auto result1 = ExpensiveInit();
static int result2 = ExpensiveInit();
...
}
}
| You declare a class attribute static when you want all instances of your class to share the same value of this variable, it is useful to count how many instances of a class you have for example.
Therefore by stating
static int count = 4;
As an attribute of your class, every instance will have access to this variable, ... |
68,545,705 | 68,545,813 | Is std::bind ignoring superfluous arguments standard-conforming? | The functor returned by std::bind ignores superfluous arguments [SO1, SO2, SO3]. A simple example looks as follows.
#include <iostream>
#include <functional>
void foo(int a) {
std::cout << "a=" << a << std::endl;
}
int main() {
auto f = std::bind(foo, 42);
f(3141); // a=42
}
It is clear that implementing std::... | Yes, for std::bind, the superfluous arguments will be discarded.
If some of the arguments that are supplied in the call to g() are not matched by any placeholders stored in g, the unused arguments are evaluated and discarded.
|
68,545,866 | 68,546,131 | std::uniform_int_distribution causes build to fail in release | When attempting to build my project in release in visual studio, I get the following errors in part of a random number generator. The program compiles and builds fine in debug, but not release. Does anyone know of a way to fix this?
| Before C++17, you needed to have the angle brackets:
std::uniform_int_distribution<> distrib(1, 6);
Given the error is:
Argument list is missing
you probably need to pass the right build settings to your compiler, both in release and debug.
|
68,546,502 | 68,566,283 | Inserting elements in a bst using recursion | I'm trying to add elements enter by the user in a BST.For this I've used 2 functions, one is used to create the function and other is just used to insert element to the tree. One is a pre-order function that is used to check if insertion is done or not Initially I tried to add elements manually.Its not printing all ins... | The issue that I noticed in my code (Unfortunately unable to upload the snippet). was in the part mentioned below.
if(root->data==data){
return root;
}
Firstly let me explain the recursion function, at beginning the root would be null at insertion(here inserting 5 as root) so first condition will be satisf... |
68,546,925 | 68,548,343 | scrolling background image, can't hide seams, c++ raylib | I'm trying to get a scrolling background to work where the background image is smaller than the window of the program. For this reason, I created a for loop to move two groups of the same copied image.
The weird thing is that the two groups of images keep drifting apart instead of staying together, seamless.
This is u... | You've made your code overly complex. To get repeats just make a source rectangle (UV coordinates) that are larger than the source image and OpenGL will repeat it. Set your source rectangle to be the same size as the screen and just offset the source rectangle origin as you scroll.
Here is a simple example.
https://git... |
68,547,434 | 68,547,534 | about const keyword as a parameter in function | I still don't understand what is the difference between these two code i mean if we put const
keyword in front of data type parameter in function what happened to my our code
#include <iostream>
using namespace std;
void function1(const int x);
int main(){
};
And if we don't put const keyword what happened to our... | The const keyword prevents a variable from being modified.
It mostly used to prevent an object that is passed by reference from being modified. It can also prevent mistakes at compile time like writing = instead of == in boolean statements.
In your case, the variable is passed by value and not by reference. In both fun... |
68,547,643 | 68,549,220 | C++ Get Another Windows Hwnd In Same Process | I've made a dll that you can inject into applications. I want that dll to find another window in the same process.
Here you can see a example. The console host (Konsolfönstervärd) is the dll I injected and I want that to find the lockdown-example window hwnd.
It is very simple to get the handle with the window title. ... | So I came up to a answer with modifying the enumWindowCallback a little bit.
BOOL CALLBACK enumWindowCallback(HWND hwnd, LPARAM lParam)
{
int length = GetWindowTextLength(hwnd);
char* buffer = new char[length + 1];
GetWindowText(hwnd, buffer, length + 1);
std::string windowTitle(buffer);
DWORD lpdw... |
68,548,175 | 68,548,539 | Why the std::map storing fewer elements than expected? | Why the map in my code is storing only two elements instead of three?
vector<int> v1 = { 140,229,319 };
vector<int> v2 = { 82,216,326 };
map<int, int> mp;
for (int i = 0; i < v1.size(); i++)
{
if (v1[i] > v2[i])
{
mp.insert({ 1,v1[i] - v2[i] });
}
else if (v2[i] > v1[i])
{
mp.insert... | First, std::mapis a sorted associative container, which only keeps unique keys. Meaning, what you're expecting is not possible with the std::map.
You should think either with
std::multimap(sorted list of key-value pairs),
std::vector<std::pair<int, int>>(unsorted list of key-value pairs) etc here, so that the multiple... |
68,548,299 | 68,548,635 | Changes in GNU C++ stdlib std::variant implementation | I have the following example with std::variant usage:
#include <iostream>
#include <string>
#include <variant>
class Cat {
public:
const std::string& getSound() const { return sound; };
private:
std::string sound = "Meow.";
};
class Dog {
public:
const std::string& getSound() const { return sound; };
pr... | gcc-8 is broken in allowing this, and produces broken code when you try to use it.
Putting aside the official definition of std::visit() and std::variant<> for a second, this intuitively has to be the case from a pure language standpoint.
To demonstrate this, let's ask ourselves the question: "What is the return type o... |
68,548,616 | 68,548,650 | Will a derived class call a protected constructor in base class before its own constructor? | My derived class should go through the same init procedure as the base class, initializing some vars and setting some states. The following is a simplified example:
class Base
{
protected:
int x = 0;
Base() { x = 1; }
};
class Sub : public Base
{
public:
void printX()
{
... | Yes, default constructor is derived class is going to call default constructors of its bases. (It becomes more interesting with virtual inheritance, but there is none in the snippet, so we do not need to go into the horrors of those).
See Implicitly-defined default constructor on https://en.cppreference.com/w/cpp/langu... |
68,548,946 | 68,549,738 | Move unique_ptr outside of variant | I have a unique_ptr inside a variant. I'm trying to do this:
if(std::holds_alternative<std::unique_ptr<something>>(a_variant)) {
auto thing = std::get<std::unique_ptr<something>>(a_variant);
}
Obviously it doesn't work, but how can I move the pointer outside of the variant?
| You need to std::move the std::unique_ptr out of the std::variant.
struct something final {};
std::variant a_variant(std::make_unique<something>());
if(std::holds_alternative<std::unique_ptr<something>>(a_variant)) {
auto thing = std::move(std::get<std::unique_ptr<something>>(a_variant));
}
Or, auto thing = std::... |
68,549,602 | 68,550,210 | Implementing logging with messages not constructed when severity is low | I'm wondering if there is any way to assure that messages that are defined in logging line are not constructed. There are some cases that I would add logging with 'trace' severity but I'm concerned about messages beeing constructed anyway (no matter if severity is high or low). Let's consider follwing simplified loggin... | Preamble: I think this is a bad idea. The execution order of expressions is a core fundamental property of the language, and messing with that in a transparent way for the sake of saving a few lines of code is just asking for surprises, unexpected program behavior and superfluous cognitive load.
That being said, should... |
68,549,618 | 68,549,717 | Generating a set of all combinations | I am trying to solve a problem:
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed) (similarly ... | I guess you want to pair each student with a different mentor in each permutation. But thats not what you are doing here:
for(auto s: students) {
for(auto m: mentors) {
curr+=check(s, m);
}
}
This two loops calculate the sum of all students paired with all mentor... |
68,549,724 | 68,686,110 | Faster alternatives to outer | I'm trying to make the following call to outer() substantially faster. Parallelizing via foreach is still prohibitively slow, so I'd like to attempt calling this in C++ using Rcpp but would love to hear any faster alternative.
Given a matrix mat and a list of matrix colnames col.list I am summarizing mat as such.
mycal... | You could try:
sapply(col.list, function(v) rowMeans(mat[, v]))
I suspect the reason your solution is slow is Vectorize: it's a nice way to transform a scalar function into a vectorized function, but it has a huge cost: since it's based on mapply, it will call the function on each element, one by one. That is, one cal... |
68,550,140 | 68,550,425 | frequency of a digit in an integer in c++ | I have been given some integers and I have to count the frequency of a specific digit in the number.
example input:
5
447474
228
6664
40
81
The first number says number of integers in the list. I am finding frequency of 4 in this case. I tried to change the integer to an array, but it is not working.
#include<iostream... | No need to create an array, or to determine the number of digits. Just loop until the number reaches zero.
int digitCount(int n, int d) {
if(n < 0) n = -n;
int count = 0;
for(; n != 0; n /= 10)
if(n % 10 == d) count++;
return count;
}
Test:
cout << digitCount(447474, 4) << endl;
cout << digitCo... |
68,550,222 | 68,550,414 | Is it safe to read(only) the same non-atomic variable in different threads without locking? | I have a class method in which I want to read the same non-atomic class member simultaneously in different threads. The method is const, so it doesn't write to the member being read. Is it safe to not bother about any locks in this case?
Edit:
I should have given an example:
class SomeClass()
{
public:
void... | Given that:
Yes, the value can be changed by other methods, but not during the execution of the method with multiple threads.
It is not inherently safe to blindly read non-atomic values that have potentially been modified by some other thread even if you know for 100% certain that no modification will be happening co... |
68,550,287 | 68,550,496 | Issue reading file with ifstream using absolute path | Hello stack overflow community. I came here as a last resort because i probably made a stupid mistake i cannot see myself.
The question im asking is for some reason when i try to read a file with an absolute path(or relative, you can see i tried that in my code) it cannot read the file for some unknown reason(atleast t... | It seems zenity, which you use as file chooser, outputs an extra newline after the file name, which you include in the name. In Linux, files can actually contain embedded newline characters in their name, and you actually try to open "test.odin\n" instead of "test.odin".
|
68,550,324 | 68,555,573 | How to connect to bluetooth device on Windows? | I would like to allow the user to connect to paired audio devices directly from the app instead of navigating to the bluetooth settings manually.
I am successfully listing all bluetooth devices using WinRT Apis:
var result = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelector());
// allow user to sel... | I found it out by chance myself and it works now. Depending whether the service is already in the state (even if the device is disconnected), you will need to turn it off before. So turning it off and on again works:
BluetoothSetServiceState(pointer.Handle, ref deviceInfo, ref serviceRef, 0);
BluetoothSetServiceState(p... |
68,550,469 | 68,551,039 | ESP32 serial communucation between 2 of them | I'm trying to do a small project between which involves measuring temperature with an ESP32, send it through a serial connection to another ESP32, and make the latter write on the the Serial connection with my computer. I am using some LEDs for monitoring.
The code for the sender is:
#include <Wire.h>
#include <LiquidC... | By initializing the communication with the computer with another HardwareSerial instance instead of the default Serial instance the message was sent.
|
68,550,907 | 68,551,152 | How to initialize array of object | I want to initialize an array of stationary objects. I am taking input of number_of_stationary_items in the constructor.
The error I get is:
invalid use of non-static data member
Here is how I am doing it:
class Inventory
{
int number_of_stationary_items;
Stationary S1[number_of_stationary_items];
public:
... | The way to do this with the fewest changes to your code is to use std::vector.
#include <vector>
struct Stationary final {};
class Inventory
{
int number_of_stationary_items;
std::vector<Stationary> S1;
public:
Inventory()
{
cout << "Enter number of stationary items: ";
cin >> number_o... |
68,551,040 | 68,551,158 | Interfacing std::filesystem::path with libraries that expect UTF-8 char*? | I'm looking to use std::filesystem::path to easily manipulate paths, but the libraries I'm using expect a const char* in UTF-8 encoding on all platforms.
I see that I can get a u8string, but its c_str() returns a char8_t*.
Is there some way for me to go from filesystem::path to a UTF-8 encoded char* on all platforms?
| A buffer of char8_t can be reasonably safely cast to a char const* pointer and passed to the other API.
char8_t is a distinct type whose underlying storage is identical to an unsigned char. Casting unsigned char bits to char is legal.
char may be signed or unsigned, so fiddling with it is somewhat dangerous in portabl... |
68,551,143 | 68,551,410 | too few arguments in function call? | too few arguments in function call? what's wrong with this code?
I want to output to std::cout day
#include <iostream>
#include <string>
class Date
{
public:
Date(unsigned _day, unsigned _month, unsigned _year) : day(_day), month(_month), year(_year) {}
int GetDate(Date& dt)
{
return dt.day;
}
... | As this member function
int GetDate(Date& dt)
{
return dt.day;
}
is a non-static member function then it is natural when it outputs the data member day of the object for which it is called. But it is defined with a parameter that accepts another object of the type Date.
Thus in this call of the function
std::cout ... |
68,551,297 | 68,551,589 | Can I always rely on RVO by the compiler? | I have a function for reading files into a string variable. And I am not sure what is a better way to implement it:
void readFile(const std::filesystem::path& path, std::string& dest)
{
std::ifstream input(path, std::ios::in | std::ios::binary);
if (!input.is_ope... | As mentioned by others, there is no guarantee that the compiler will optimize this, because the returned value is a named variable (see https://en.cppreference.com/w/cpp/language/copy_elision).
However, in my opinion you can almost always rely on RVO if you enable optimizations, as RVO is one of the first and easiest o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.