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,009,035 | 68,009,592 | I still can't get my head around why we need the template for perfect fwd | I have this code: (live eg: https://godbolt.org/z/js1qK9hd1)
struct big_class
{
std::string s1;
std::string s2;
std::string s3;
std::string s4;
std::string s5;
std::string s6;
std::string s7;
};
void func(const big_class &bc)
{
std::cout << bc.s1 << bc.s2 << bc.s3 << bc.s4 << bc.s5 << b... | Unlike big_class&&, which is a rvalue reference and can only take in an rvalue reference, the template version T&& is a universal reference / forwarding reference.
When you pass in something into the template function, T&& might be deduced to either an rvalue reference (big_class&&), or an lvalue reference (big_class&)... |
68,009,538 | 68,024,131 | different INTERFACE compiler options for different languages | CMake, as of v3.20, has the target_compile_options() command, which we can invoke, for example, like so:
target_compile_options(foo INTERFACE "--some-option")
which is well and good... as long as we're only using foo in compilations in a single language, or even with a single compiler. But what if I want to depend on ... | There may be a generator expression that works for you: $<COMPILE_LANGUAGE:languages> (https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html#id2)
I haven't tried this out in your scenario though.
target_compile_options(foo INTERFACE
"$<$<COMPILE_LANGUAGE:C>:--option-for-C>"
"$<$<COMPILE_... |
68,009,824 | 68,010,161 | priority_queue c++ with custom comparator and O(n) time | I was searching but I didnt find an easy way to create a priority_queue using a cumstom comparator but that also takes linear time to create the elements in the priority_queue.
it is possible to create a priority_queue in linear time using:
vector<int> arr = {1,2,3,4};
priority_queue<int> pq(arr.begin(),arr.end());
an... | Assuming points is a container containing std::vector<int>s, this is how you could define your priority queue:
std::priority_queue<std::vector<int>,
std::vector<std::vector<int>>,
decltype(cmp)> pq(points.begin(), points.end(), cmp);
Demo
|
68,009,851 | 68,016,612 | wxWidgets problem - libwx_gtk3u_gl-3.1.a: no such file or directory | I am trying to compile a program that uses wxWidgets. When I run "make", it is returned to me :
Building target using GCC compiler: sources/geometry-manager.cpp
g++ -g -c sources/geometry-manager.cpp -std=c++17 -w -c -rdynamic -W `wx-config --cxxflags --libs --gl-libs` `geos-config --cflags` -lgeos -lglut -lGLU -lGL -l... | You must have built wxWidgets yourself, but when configuring it, configure didn't find the required OpenGL headers/libraries, so OpenGL support was disabled, as you can confirm by looking at config.log file it created. You will also find the details of why did this fail in the same file, but you probably just need to a... |
68,010,592 | 68,011,444 | Print deduced template arguments at compile time | How to print automatically deduced template arguments at compile time?
std::pair x(1, 2.0);
In the above example the type of x is std::pair<int, double>. Is there a way to print the deduced type of x at compile time, e.g. as std::pair<int, double> or in some other readable form?
Edit. I am using a library (DPC++) that... | Here's one (admittedly roundabout and verbose) approach:
#include <utility>
template <class T>
struct type_reader {
type_reader() {
int x{0};
if (x = 1) {} // trigger deliberate warning
}
};
int main() {
std::pair x(1, 2.0);
type_reader<decltype(x)> t;
}
Depending on your compiler and... |
68,010,600 | 68,011,339 | How to write modular code in c++ with gtkmm? | How to write modular code in gtkmm3
I want to create objects in a window that I have using the different classes I created (inherited from Gtk::Grid) and put them in the mainGrid window
I do this but it shows me nothing
class MainWindow:public Gtk::Window{
public:
MainWindow();
private:
Gtk::Gri... | The problem here seems to be that you are not using inheritance and polymorphism, even though you made it clear in your classes that they are indeed inheriting.
Here is a working example:
#include <gtkmm.h>
class FirstGrid : public Gtk::Grid
{
public:
FirstGrid()
{
// Since FirstGrid is a Gtk::Grid, ... |
68,010,682 | 68,010,744 | Why does an exception thrown in a constructor fully enclosed in try-catch seem to be rethrown? | Considering this silly looking try-catch chain:
try {
try {
try {
try {
throw "Huh";
} catch(...) {
std::cout << "what1\n";
}
} catch(...) {
std::cout << "what2\n";
}
} catch(...) {
std::cout << "what... | cppreference has this to say about a function-try-block (which is what we have here):
Every catch-clause in the function-try-block for a constructor must terminate by throwing an exception. If the control reaches the end of such handler, the current exception is automatically rethrown as if by throw.
So there we have... |
68,010,970 | 68,012,204 | Distributing C# Class Library for UWP | I have core functionality written in c++.
To use this from UWP, I made dynamic library and chained like this: [c++ native dll] - [c++/cx windows runtime component] - [UWP c# class library].
c# dll provides API for UWP and c++/cx is used just for interoperability between c++ and c#.
My test UWP app works fine and no... |
Is there a way to distribute my dlls in all-in-one structure? (like aar)
You may refer .NetStandard library, and mix them in one .NET Standard library. And if you want this library could run in the multiple platform, you need to refer Xamarin Forms class library structure, for more detail please refer this blog.
|
68,011,356 | 68,011,519 | How can i add a path to this URL via user input? | Trying to prompt the user to type their username on this instagram link so that it will open on their profile, how can I add the username to this line of code?
string UName;
cout << "For this option please enter the Username" << endl;
cin >> UName;
ShellExecute(0, 0, L"https://www.instagram.com/... | std::string has an operator+ for concatenating a char char* with a std::string, returning a new std::string. You can call c_str() on that std::string when passing it to ShellExecuteA() (not ShellExecuteW()), eg:
string UName;
cout << "For this option please enter the Username" << endl;
cin >> UName;
string url = "http... |
68,011,397 | 68,011,570 | How to cause SAL compiler warnings in my own code using Visual C++ without running static code analysis | If I create a new console project in VS 2019 and add my own annotated implementation of printf and call both real printf and my version:
// SALTest.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <cstdarg>
int my_printf(_In_z_ ... | SAL annotations have no effect whatsoever during the compiling stage, as they are implemented as empty preprocessor macros. They only have an effect on static analysis tools.
In the case of printf() (and other similar standard functions, like scanf()), modern compilers have built-in knowledge of the requirements of the... |
68,011,566 | 68,011,598 | Alias a template function with default parameters | The following C++ code does not compile:
template <typename T>
void f(int, bool = true);
void g()
{
auto h = f<int>;
h(1); // error: too few arguments to function
}
Instead, I have to call h with the 2nd parameter:
h(1, true);
Why doesn't h(1) work?
Is there a simple way to alias a template function to bind ... | h is declared as function pointer, unfortunately it can't specify default arguments.
Default arguments are only allowed in the parameter lists of function declarations and lambda-expressions, (since C++11) and are not allowed in the declarations of pointers to functions, references to functions, or in typedef declarat... |
68,011,937 | 68,012,081 | How to add async wait in C++? | I have two threads running one is a producer which produces the data and put it in a queue and the other is a consumer which consumes that data. I would like the producer to produce the data with a delay of a few seconds but do not want the consumer to be waiting it should process the data asynchronously as soon as it... | std::this_thread::sleep_for gets called while the mutex is still held. This prevents the other execution thread from doing anything, it's as simple as that. The mutex is still locked. When a thread has locked a mutex and then is waiting on a condition variable, the execution thread will not resume, even if the conditio... |
68,012,430 | 68,012,610 | V8 - Exposing a non-void C++ function to the Javascript code | I have already successfully gotten V8 to run arbitrary Javascript files. The trouble comes when I try to expose a C++ function so that it can be run by the Javascript code.
I define the following simple toy function,
v8::Handle<v8::Value> f(const v8::FunctionCallbackInfo<v8::Value>& args)
{
v8::Isolate* isolate = ... | https://v8docs.nodesource.com/node-16.0/dd/d0d/classv8_1_1_function_callback_info.html
Return void. Your args has a ReturnValue property. You can set your return value into it.
args.GetReturnValue().Set( 2 );
I find google code tends to change APIs a lot, so looking at current docs and/or source is your best bet.
|
68,012,876 | 68,013,353 | Overriding map iterator to return dynamic_casted value | EDIT: I have a working solution now, https://wandbox.org/permlink/joS14MzfmmayNRd3, just want to know if it can be improved.
I have a map map<int, unique_ptr<Base>>, whose values can also be of type unique_ptr<Derived>. I have wrapper classes A and B which store Base and Derived in the map respectively (all Base or all... | There are several problems here:
You're taking p by value, that is, you're making a copy. But std::unique_ptr is not copyable.
BaseMap::value_type is already an std::pair<const Key, Value>.
std::make_pair() decays arguments, you need to wrap an argument into std::reference_wrapper with std::ref() to pass a reference.
... |
68,012,977 | 68,013,296 | Valgrind Invalid write of size 8 when modifying variable in vector | I am trying to modify the value of a variable within a vector of 'Vertex' (a struct I made) but when I run valgrind I keep getting this error, Here is my code and the valgrind error:
struct Vertex {
bool discovered = false;
double distance = INFINITY;
size_t prev;
double xcor;
double ycor;
};
int ... | This happens in case numV is zero or negative. In that case the vertices vector will be empty and trying to set vertices[0].distance accesses memory that was not allocated (there is no first element in the empty vector).
|
68,013,461 | 68,013,820 | Which constructor is getting called for below string code? | I was reading c++ primer and came across an example of list initialization for vector where the author mentioned that if list initialization isn't possible, the compiler then looks for other ways to initialize the object. Below is such an example for vector of string.
vector<string> v8{10, "hi"};
This creates a vector... | What's coming into play here are the rules for direct-list-initialization which has one of the syntax as
T object { arg1, arg2, ... };
Here, in the case of std::string s{10, 'c'}, T in the above syntax is std::string and the rule that applies is
Otherwise, the constructors of T are considered, in two phases: All
cons... |
68,013,767 | 68,013,938 | Difference between equivalent and equal for c++20 three way comparison operator? | In c++20 the new three way comparison operator <=> (spaceship operator) is introduced and it can result into four values given below :
std::strong_ordering::less
std::strong_ordering::equivalent
std::strong_ordering::equal
std::strong_ordering::greater
However when I run below code snippet it appears that both equal ... | They are the same thing, both numerically and conceptually. If a comparison generates strong ordering between the items being compared, equivalence and equality are the same.
The reason there are two words for it is because this is not the same for other kinds of ordering. Weak and partial don't have equality at all; t... |
68,015,323 | 68,016,699 | Find largest mode in huge data set without timing out | Description
In statistics, there is a measure of the distribution called the mode. The mode is the data that appears the most in a data set. A data set may have more than one mode, that is, when there is more than one data with the same number of occurrences.
Mr. Dengklek gives you N integers. Find the greatest mode of... | You're overcomplicating things. Competitive programming is a weird beast were solutions assume limited resources, whaky amount of input data. Often those tasks are balanced that way that they require use of constant time alternate algorithms, summ on set dynamic programming. Size of code is often taken in consideration... |
68,015,921 | 68,016,627 | Eclipse C++ Run Error "Launch Failed. Binary Not Found." | I am trying to run the "Hello World" C++ program in Eclipse. It says "Launch Failed. Binary Not Found." I tried adding a C++ application, but it doesn't work. I also tried changing the binary parser to PE Windows. I am using Mingw-w64 8.1.0 (Posix, dwarf). I have no idea what I'm doing. Does anyone know what to do.
Upd... | I went to the Debug folder where Test.exe was and ran it. It required libgcc_s_dw2-1.dll, libstdc++-6.dll, and libwinpthread-1.dll to run. So, I copied them to the folder from MinGW. I put Debug/Test.exe into C++ Application and it worked!
|
68,016,039 | 68,016,265 | How to extract sub-vectors of different datatypes from vector<char>? | I have a std::vector<char> data which represents data from a network byte-stream as well as different offsets as integer values. I know that the vector holds the data for a 4x4 trajectory matrix (32bit float), a RGB image (Unity TextureFormat.RGB24) and a gray scale image (Unity TextureFormat.RFloat).
What I need to do... | You need to copy the bytes into objects of the right type
std::vector<char> data = /* get from network */;
Eigen::Matrix4d trajectory;
std::vector<uint8_t> rgb_image_data(rgb_image_size);
std::vector<uint8_t> gray_image_data(gray_image_size);
std::memcpy(&trajectory, data.data() + trajectory_offset, sizeof(Eigen::Matr... |
68,016,301 | 68,021,799 | UE4 cast to specific class from UUserWidget C++ | Let's assume i have 3 cpp class.
1- Afirst_class : public AActor
2- Asecond_class : public AActor
3- Uwidget_class : public UUserWidget
I'm trying to cast from Uwidget_class to Asecond_class. After that from Asecond_class to Afirst_class.
When i click the UButton(defined in Uwidget_class), OnClicked dynamic executi... | Like George said in his comment, that cannot work. Cast is for moving around an inheritance tree, but only along the parts of that tree that are directly related to the actual class of the object being referenced.
So you could cast both your widget and actors to UObjects, but I suspect that's about as common as they'l... |
68,016,811 | 68,017,139 | how to get C++/Python source code of a Python Obj? | Python int obj has dynamic memory allocation. When the number is small, memory is small; when large, otherwise. But the numpy array unit has fixed memory once declared.
I am very curious about how python implemented these mechanisms in its source code, either in C++ or Python code.
Where can I get a valid version of py... | CPython source is available via github.com/python, for discussion of implementation (rather than code only) see laurentluce.com post.
|
68,017,155 | 68,021,427 | Is there a way to switch boost::json::serializer to beautified output? | Using boost::json::serializer as shown in the example in docs - quick look saves the json-tree in compact format.
Is there a way to instruct the serializer to output a human readable file (i.e. with newlines and whitespaces)? I searched around, but didn't find any hints.
NB: Even better would be writing the higher leve... | This is not a feature of the library. The library has goals stated in the intro. It doesn't include user-friendly presentation formatting. In fact, even their number formatting can be said to be down-right user hostile.
The promise of the library centers at data interchange between computer systems:
This library focus... |
68,017,211 | 68,017,428 | Resizing a std::vector using move insertion and copy insertion | In the C++ standard vector.capacity section, it defines two overloads for resize(). (see also https://en.cppreference.com/w/cpp/container/vector/resize)
This overload requires that the type T is MoveInsertable and DefaultInsertable:
constexpr void resize(size_type sz);
The other overload requires that the type T is Co... | I agree that the second parameter could be an rvalue reference - this saves one copy, when it is subsequently copied from the first newly appended item. I assume what you have in mind is something like this:
std::vector<LargeObject> v;
// ...
LargeObject obj = setupLotsOfResources();
// Now do 1 move and 9 copies in... |
68,017,319 | 68,017,487 | Vector of structs with const members | I'm coming back to C++ after many years and I'm on the C++17 standard. As per this question, it seems custom structs with const members are not always compatible with vectors without public copy-assignment constructors.
In my case though, unlike the linked question, the following compiles fine:
#include <vector>
struc... | The problem with const members is that they disable compiler-generated operator=. So, if you use the vector in a manner that operator= is not needed, or if you provide your own operator= somehow, it all works fine. Generally, you never strictly need const member fields, and they cause a lot of problems with STL contain... |
68,017,584 | 68,017,737 | Cast from type parametrized by const template argument to non-const template argument | I have a class with variadic template parameters:
template<typename... Args>
class something {
public:
something(Args&&... args); // omitted for brevity
}
I have a function that accepts a list of arguments and returns an object of this class:
template<typename... Args>
auto make_something(Args&&... args) {
retur... | There are two options, depending on if you really want to have something<int, const std::string &> be a type that make_something(1, t) returns.
If that is the case, you can have a converting constructor
template<typename... Args>
class something {
public:
something(Args&&... args); // omitted for brevity
template<t... |
68,017,734 | 68,017,775 | C++ Ternary Operator with Equality Statement | While debugging someone else's code, I ran into an expression of the following form:
auto result = value == bool_value? result_if_bool_value: result_if_not_bool_value
I am familiar with ternary operators, but I am confused by the double equality operator in the above statement.
Specifically, what is the equivalent of ... | The conditional operator has lower precedence than ==. Hence the line is parsed as:
auto result = (value == bool_value ) ? result_if_bool_value: result_if_not_bool_value
It is the usual
( condition ) ? expr_true : expr_false
In general the conditional operator is not equivalent to an if, but you get the same result w... |
68,017,801 | 68,018,345 | Compiling different source files with different flags | My makefile currently is:
# Environment
...
CC=gcc
CCC=g++
CXX=g++
# Macros
...
# Object Files
OBJECTFILES= \
${OBJECTDIR}/_ext/511e4115/File1.o \
${OBJECTDIR}/_ext/511e4115/File2.o
# CC Compiler Flags
CCFLAGS=-m64 -fno-common -fPIC -fno-strict-aliasing -fexceptions -fopenmp -Wall -Wextra
CXXFLAGS=-m64 -... | COMPILE.cc is a built-in variable:
COMPILE.cc = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
and you can override variables on a per-rule level, so with the following Makefile:
CXXFLAGS := all the rules
CXXFLAGS_DIFF := $(subst all the, fewer, $(CXXFLAGS))
bad.o: CXXFLAGS=$(CXXFLAGS_DIFF)
I get:
% make -n good.o... |
68,018,088 | 68,018,127 | In my code for preorder traversal of binary tree, what is the reason for segmentation fault? | I have to return the elements of a binary tree in an int vector. I have written the following code, but it gives segmentation fault. What could be the reason for that? Also, does my code use correct logic?
struct Node
{ int data;
struct *Node left;
struct *Node right;
}
Node(int x)
{
data = x;
le... | You are calling preorder twice for each ans.insert. They will return different vectors and their begin() and end() won't match. Therefore using them for specifying range is invalid.
Instead of this:
ans.insert(ans.end(), preorder(root->left).begin(),preorder(root->left).end());
ans.insert(ans.end(), preorder(root->righ... |
68,018,136 | 68,018,557 | Replace a variable of a type with const members | Suppose I have a class with some constant member:
class MyClass {
public:
MyClass(int a) : a(a) {
}
MyClass() : MyClass(0) {
}
~MyClass() {
}
const int a;
};
Now I want to store an instance of MyClass somewhere, e.g. as a global variable or as an attribute of another object.
MyClass var;
Later, I... | const members are problematic in general for the very reason you discovered.
The much simpler alternative is to make the member private and take care to provide no means to modify it from outside the class:
class MyClass {
public:
MyClass(int a) : a(a) {
}
MyClass() : MyClass(0) {
}
~MyClass() {
}
pri... |
68,019,107 | 68,021,545 | Registry RegQueryValueExW | Is it possible to read a value in the Registry not to an array of chars but directly to an AnsiString in this case?
LONG result;
wchar_t buf[255] = {0};
DWORD dwBufSize = sizeof(buf);
String d = "Nazwa";
DWORD dwType = REG_SZ;
result = ::RegQueryValueExW( hkSoftware, (LPCWSTR)(d.c_str()), NULL, &dwType, (LPBYTE)&buf, ... | First off, your code example is not using AnsiString. In C++Builder 2009 and later, String is an alias for UnicodeString instead.
And yes, you can use UnicodeString with RegQueryValueExW(), without using a typecast. UnicodeString::c_str() returns a WideChar*, and WideChar is an alias for wchar_t on Windows, so WideChar... |
68,019,301 | 68,019,383 | how to convert a barycentric coordinate calculation in c++ to python? | I'm looking for help with converting this piece of code which is in c++ and was wondering how it would look like in python.
void Barycentric(Point p, Point a, Point b, Point c, float &u, float &v, float &w)
{
Vector v0 = b - a, v1 = c - a, v2 = p - a;
float d00 = Dot(v0, v0);
float d01 = Dot(v0, v1);
fl... | with numpy you would get a very similar looking function.
import numpy as np
def Barycentric(p, a, b, c, u, v, w):
v0 = b - a
v1 = c - a
v2 = p - a
d00 = np.dot(v0, v0)
d01 = np.dot(v0, v1)
d11 = np.dot(v1, v1)
d20 = np.dot(v2, v0)
d21 = np.dot(v2, v1)
denom = d00 * d11 - d01 * d01
... |
68,019,382 | 68,019,551 | How to Advance void * pointer? | In C++ I had:
MallocMetadata *tmp = static_cast<MallocMetadata *> (p);
But now I want tmp to be 5 bytes before in memory so I tried:
MallocMetadata *tmp = static_cast<MallocMetadata *> (p-5);
But that didn't compile, I read some articles which suggested this (and didn't work too):
MallocMetadata *tmp = static_cast<Ma... |
C++ How to Advance void * pointer?
It is not possible to advance a void*.
Advancing a pointer by one modifies the pointer to point to the next sibling of the previously pointed object within an array of objects. The distance between two elements of an array differs between objects of different types. The distance is ... |
68,019,395 | 68,019,490 | Why is throwing of move operation is ignored for one overload of std::vector::resize()? | In the C++ standard vector.capacity section, it defines two overloads for resize(). (see also https://en.cppreference.com/w/cpp/container/vector/resize)
This overload requires that the type T is MoveInsertable and DefaultInsertable:
constexpr void resize(size_type sz);
The other overload requires that the type T is Co... |
Throwing of the move constructor is not mentioned in the second overload. why?
Because the second overload requires the type to be CopyInsertable. Given that requirement, the case "of a non-Cpp17CopyInsertable T" doesn't exist for the second overload, so there is no need to mention that case.
|
68,019,488 | 68,114,251 | How to bind reference of non-movable object in variadic template arguments? | In the following minimal example:
#include <iostream>
#include <functional>
class Non_movable{
public:
Non_movable(void){ }
Non_movable(const Non_movable& other) = delete;/* Copy constructor */
Non_movable(Non_movable&& other) = delete; /* Move constructor */
Non_movable& operator=(const Non_movable& other) = ... | In the parameter pack expansion you can write any pattern including at least one parameter pack, see https://en.cppreference.com/w/cpp/language/parameter_pack.
This means that in your make_bound function you can just write
return std::bind(fun, std::ref(args)..., std::placeholders::_1);
Please find your adapted minima... |
68,019,574 | 68,023,980 | How to include wxWidgets headers in CMake project | I am trying to run wxWidget example using cmake but unable to include the headers of wxWidgets in my C++ project(CMakeLists.txt). If i run the program using the command
g++ main.cpp `wx-config --cppflags --libs` -o wxTest
the program works and display the window. But how can i do that using CMakeLists.txt file. For ex... | CMake has first-party support for wxWidgets, here's an example:
cmake_minimum_required(VERSION 3.20)
project(wxTest)
find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net)
include(${wxWidgets_USE_FILE})
add_executable(wxTestmain.cpp)
target_link_libraries(wxTest PRIVATE ${wxWidgets_LIBRARIES})
It's a ... |
68,019,993 | 68,021,778 | Generic multi-functor composition/pipelining in C++ | Is it possible to achieve generic multi-functor composition/pipelining in C++ 20?
struct F{//1st multi-functor
template<typename T> void operator()(const T& t){/*...*/}
};
struct G{//2nd multi-functor
template<typename T> void operator()(const T& t){/*...*/}
};
F f;
G g;
auto pipe = f | g;//what magic should happe... | So here is a quick little library.
#define RETURNS(...) \
noexcept(noexcept(__VA_ARGS__)) \
-> decltype(__VA_ARGS__) \
{ return __VA_ARGS__; }
namespace ops {
template<class D>
struct op_tag;
template<class Second, class First>
struct pipe_t;
template<class D>
struct op_tag {
D const& self() co... |
68,020,388 | 68,021,125 | How can I avoid circular dependencies in a header only library? | I am a developing a C++ header only library.
There are several parts of the code which follow this pattern:
holder.h
#pragma once
#include "sub.h"
struct Holder
{
void f();
Sub s;
};
sub.h
#pragma once
struct Holder;
struct Sub
{
void g(Holder& h);
};
#include "sub.ipp"
sub.ipp
#include "holder.h"
i... |
struct Sub
{
void g(Holder& h);
};
void Sub::g(Holder& h)
{
h.f();
}
Non-inline functions won't work well in header-only libraries, because the headers are typically included into more than one translation unit. You should use inline functions instead.
How can I avoid circular dependencies in a header only... |
68,021,192 | 68,021,415 | Physics in my game gives a wrong result with vsync turned off C++ | I calculate Newtonian physics based on gravitation in my 2D game. It works exactly how it's supposed to, when vsync is turned on (60fps), but once I turn it off and gain about 3.5k fps, the character starts to fall incredibly fast. The answer seems obvious, I just need to multiply character's velocity by deltaTime, but... | The acceleration means how large the velocity increases per unit time, so you should multiply deltaTime to the acceleration, not only to the velocity.
In other words,
acceleration += -Physics::g; // 9.81f
should be:
acceleration += deltaTime * -Physics::g; // 9.81f
|
68,021,677 | 68,022,002 | Conversion failed! FFMpeg with custom exe in a pipe | I need to use a batch file with FFmpeg pipe query. I have a set of images (img0.bmp, img1.bmp, img2.bmp) and I need FFmpeg to iterate through them and pass raw data to my custom .exe.
So, the query looks like this
ffmpeg -y -hide_banner -i img%01d.bmp -vf format=gray -f rawvideo pipe: | MY_CUSTOM_EXE
and code of the c... | You must let your program consume the output from ffmpeg otherwise you get the errors you describe.
I tested my hunch and came back with:
av_interleaved_write_frame(): Broken pipe
Error writing trailer of pipe:: Broken pipe
So a simple
#include<iostream>
int main(){
char c;
while(std::cin >> c){} // consume ... |
68,021,853 | 69,176,939 | Mocking overloaded methods with the same number of input arguments using GMock | I have a class that defines an overloaded method that I need to mock. The issue is, the two overloads both take only one argument and GMock seems to think the call is ambiguous.
Here is a small example demonstrating the problem (oversimplified for the sake of demonstration):
#include <gmock/gmock.h>
#include <gtest/gte... | I had the same issue and solved it using gMock Cookbook's Select Overload section. You have to define the matcher's type, e.g. by writing Matcher<std::string>(). Remember to include this directive above (using ::testing::Matcher;).
|
68,021,983 | 68,028,077 | Bison C++ get name of token - yytname_ is private | I'm attempting to get the name of a token in C++ Bison:
E.g. %token <int> TPLUS "+" TMINUS "-" TMUL "*" TDIV "/"
However in the C++ variant of Bison, %token-table does not do anything.
I have noticed that there is a token mapping in the generated bison code: const char* const parser::yytname_[]; however it is private.... | First, ensure that you have a recent version of Bison (I believe the minimum is v3.6, but the v3.7 versions have several useful bug fixes).
That will generate a static member function named symbol_name with one of the following prototypes. Note that `token_symbol_kind is an internal token number, not the value produce... |
68,022,127 | 68,043,632 | The code below prints the character for the pi number in VS2019, instead of the character `ã`. What am I missing? | The code below prints the character for the pi number in VS2019, instead of the character ã.
#include<iostream>
const char* p = "\u00E3"; // Character ã LATIN SMALL LETTER A WITH TILDE
int main() {
std::cout << p << '\n'; // This should compile by any compiler supporting some ASCII compatible enc... | Yes, U+00E3 is the code point for ã. That is just a number. That number has to be encoded to be stored anywhere (memory, a file, etc.). You have an encoding issue. You wrote the byte 0xe3 to the terminal but its code page is cp437, where 0xe3 is decoded as π.
On Windows, using wide strings and setting the terminal ... |
68,022,390 | 68,022,445 | QByteArray of zero size; where do begin() and end() point to? | QByteArray uses copy-on-write strategy, so copying them is cheap. I assumed that also means that it's okay to pass them by value.
However, this assumption seems to break when I use QByteArray with zero length:
struct Frame
{
QByteArray load{0, 0}; // zero size, fill with zeroes
QByteArray getLoad() { return load; ... | You are calling frame.getLoad() twice in your call of std::copy. they will return different QByteArray, so their begin() and end() has no relation.
You can have getLoad() return the reference to load to overcome this problem.
QByteArray& getLoad() { return load; }
If you want getLoad() return the copy of load, you sho... |
68,023,398 | 68,026,736 | Why my setters can't be activated although I've made pointers for parameters? | Hi everyone I'm a newbie to programming and self-taught C++ by a website.
I'm writing a program to calculate the distance between the beginning and the end point. Here's my code
File Point.cpp:
#include<iostream>
#pragma once
using namespace std;
class Point {
private:
int x;
int y;
public:
Point() {
... | @Tenphase has already mentioned that you should not put int in the line:
begin.setX(int x1)
^^^
However, there seems to have a lot more problem with your code here. Your Point class seems to work fine, however you seems to have a lot of problems with your Line class.
For instance, in your setBegin function... |
68,023,898 | 68,023,940 | C++ different output using global variables vs passing variable thorugh function | I was solving this question.
When the min and max variables are set as global variable, I'm getting the correct output, but when I pass them in the functions it messes up the output.
I can't figure out the reason. Can someone tell me, how are these two code snippets different.
global:
int min = 1,max = 0;
//d... | The global variable is global. The changes to the value will retain among all calls of travLeft and travRight.
On the other hand, the argument is local to the function. The new value of min and max are passed to the next level of recursion, but the update of min in the first recursion
travLeft(root->left,min,i-1,left);... |
68,024,563 | 68,024,633 | Passing a string literal to a template char array parameter | The CTRE library is able to parse and validate regular expressions at compile time using syntax like ctre::match<"REGEX">(text_to_search). I know this syntax is only supported in C++20, which is fine, but I am unable use string literals this way no matter what I try. Here's a very simple example:
// The compiler refuse... | Being able to do this hinges on a little-known feature of C++20: a non-type template parameter can have a class template type, without template arguments specified. CTAD will determine those arguments.
So you create a class templated by size_t N, that has char[N] as a member, is constructible from one, and N is deducib... |
68,025,219 | 68,025,713 | C++ Tree traversal: Why Looping is slower than Recursion in this case? | I need to traverse a tree in my C++ code for a large number of times, the depth of the tree can vary from one iteration to another. I might also conditionally early break from the tree traversal. While profiling my code (using Visual studio compiler), I noticed that the tree traversal part was the biggest bottleneck in... | The tree you are traversing is so small compared to the number of iterations you are running that managing the dynamic memory of the stack object dwarves any gains you think (we'll revisit that later) you are getting from doing it in a loop.
Let's try and remove that memory allocation overhead and see what happens to t... |
68,025,322 | 68,934,838 | Drag and drop QStandardItem holding file paths to another application in C++? | I have a treeview which is modeling a file tree. Each item in the TreeView is a QstandardItem that holds a file path. I would like to be able to get the file it referres to and drag the item into another application. The files are all video files so I would like to add the ability to drag and drop into VLC, Adobe Premi... | minialistic code :
main.cpp
drag d:/1.txt drop to notepad
#include <QtWidgets/QApplication>
#include <QMimeData>
#include <QTreeView>
#include <QDrag>
#include <QStandardItemModel>
#include<QUrl>
class Myodel :public QStandardItemModel
{
Q_OBJECT
public:
QStringList mimeTypes() const override
{
ret... |
68,025,806 | 68,275,279 | How do I combine two arrays of 8 bits each (binary number strings into one single string with 16 bits? (arduino, shift registers) | In Arduino, I'm trying to combine the 8-bit binary numbers/strings from two PISO (parallel in - series out) shift registers into one 16-bit binary string. The binary numbers stored on a variable (switchVar1) with the shiftIn() command on Arduino switchVar1 = shiftIn(dataPin, clockPin);
switchVar1 was first defined by b... | It got figured out with thanks to everyone commenting. So I just did it like:
switchVar1 = shiftIn(dataPin, clockPin); switchVar2 = shiftIn(dataPin2, clockPin2); uint16_t switchVariable = switchVar1 | (switchVar2<<8);
as in I first created two, byte files and "shifted" the numbers on one (switchVar2) 8 steps to the lef... |
68,027,143 | 68,048,312 | Best way to calculate a running hash for an unordered_map? | I've got a simple wrapper-class for std::unordered_map that updates a running hash-code for the unordered_map's contents, as key-value pairs are added or removed; that way I never have to iterate over the entire contents to get the current hash code for the set. It does this by adding to the _hash member-variable when... | Your concept's perfectly fine, just the implementation could be improved:
you could take the hash functions to use as template arguments that default to the relevant std::hash instantiations; note that for numbers it's common (GCC, Clang, Visual C++) for std::hash<> to be an identity hash, which is moderately collisio... |
68,027,145 | 68,027,282 | How to define a type for a ranges::view without defining it initially? | I need to specify different ranges::view's depending upon a variable. Such as:
#include <ranges>
#include <vector>
auto main() -> int
{
std::vector<double> xs = { 1.0, 2.0, 3.0, 4.0, 5.0 };
auto x = int(0);
auto vi;
if(x == 0)
vi = xs | std::ranges::views::all;
else
vi = xs | std:... | Normally, you would want to avoid this altogether by not declaring vi until it can be inferred properly, which is not as constraining as you might think:
#include <ranges>
#include <vector>
#include <iostream>
template<typename RangeT>
void foo(const RangeT& vi) {
for(auto & v: vi) {
std::cout << v << "\n"... |
68,027,262 | 68,044,045 | Arduino NeoPixel code behaves oddly when code is moved to class | So I've been running into a weird issue while trying to compartmentalize some test code I wrote for an Arduino/NeoPixel application. There are two scenarios: Scenario A, my code before the move, and Scenario B, my code after the move. The test code works as expected in Scenario A (a red light walks across my 8x8 led ma... | The issue is apparently in the Screen constructor:
Screen(uint8_t width, uint8_t height, uint8_t pin) :
width(width), height(height), pin(pin)
{
pixels = Adafruit_NeoPixel(width * height, pin, NEO_GRB + NEO_KHZ800);
}
Now it creates "empty" pixels using default constructor and in the code block it creates anot... |
68,027,323 | 68,027,455 | Filling array of arrays | I am trying to calculate the correlation and store the values in an array of arrays. It seems like the problem is filling vectors into a vector. I have tried some solutions but no luck. I appreciate your help.
void BuildCorrelationForMatrix()
{
std::vector<std::unique_ptr<correlation>> m_correlationMatrix;
std::vector<... | std::vector<std::vector<float>> m_correlationValues;
This creates a new vector. This vector is completely empty. There's nothing in it.
m_correlationValues[col_idx].push_back(row_values);
The [] operator accesses existing values in the vector. It does not add values to a vector. It doesn't matter what col_idx is, he... |
68,027,913 | 68,029,101 | Why Does ReadProcessMemory Give Me Error Code 299? | I am trying to read a float from a game's memory. The game is called Muck, it is 64 bit. My program's platform is also 64 bit. When I call ReadProcessMemory(), it gives me a value that I know is not the correct value, and it returns 0 (which means there was an error). Calling GetLastError() gives me error code 299.
Cod... | Here is how I solved it:
LPVOID loc = (LPVOID)0x1DB7C83158C;
bool r = ReadProcessMemory(handle, loc, &val, 4, NULL);
I was passing a pointer.
|
68,027,919 | 68,043,338 | Error installing C/C++ plugin in Netbeans 12.4 with JDK 16 in Windows 10 | I'd like to install C/C++ plugin in Netbeans 12.4 with JDK 16 in Windows 10.
I have an error during the install C/C++ plugin.
Windows: 10
Netbeans: 12.4
JDK: 16.0.1
I attached photos:
| You are getting this problem because NetBeans is using JDK 16 to download a plugin, where that download process relies on the unpack200 tool which was deprecated in JDK 11, and removed in JDK 14.
Since NetBeans 12.4 supports three JDK releases (8, 11 and 16), the solution is to:
Temporarily switch the default platform... |
68,028,230 | 68,028,278 | C++ why templating a class resolves undefined class error | I encounter a compiler error when I try to declare a nested class with a member of the outer class type:
class A {
public:
class Anested {
A a; // Error: 'A::Anested::a' uses undefined class 'A'
};
};
Changing the outer class to a class template removes the compiler error:
template <size_t n>
class B {... | In the case of A::Anested, A is an incomplete type when a is declared, the compiler hasn't seen the whole declaration of A yet, so it can't declare a as an instance of A. Incomplete types only work when dealing with references and pointers.
In the case of B::Bnested, templates are handled in multiple stages. The compi... |
68,028,339 | 68,848,430 | C++ - function multiple definition of `Lexer::Tokenize | so I was trying to compile a file and I got this error(mingw-64):
C:\Users\me\AppData\Local\Temp\ccfdOWKk.o:EKLexer.cpp:(.text+0x0): multiple definition of `Lexer::Tokenize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
C:\Users\me\AppData\Local\Temp\cc9yNSun.o:EnderKnightShell.cpp:(.... | Thanks to templatetypedef's comment, I found that the issue was including a .cpp file. The solution is to use a header and cpp source file combo
|
68,028,516 | 68,035,237 | Is there a better way to set C++ format options in VS Code instead of packing them into one long string? | I am using Clang C++ on macOS in VS Code and I have overridden some C++ formatting options in 'settings.json' file. I am able to set some things from the Settings UI, but for more detailed settings I have added the following entry in 'settings.json':
"C_Cpp.clang_format_fallbackStyle": "{ EmptyLineBeforeAccessModifie... | Based on a comment from Frank I tried using .clang-format file and after some messing around I got it to work. I first tried putting .clang-format inside the .vscode directory in my project, but that didn't work. After reading move about clang format I moved the file to my home directory (note the file format for .clan... |
68,028,559 | 68,028,967 | When is a multiset sorted? Insertion, iteration, both? | I have a multi-set containing pointers to custom types. I have provided a custom sorter to the multi-set that compares on a particular attribute of the custom type.
If I change the value of the attribute on any given item (in a way that would influence the sorting order). Do I have to remove the item from the set and r... | http://eel.is/c++draft/associative.reqmts#general-3
For any two keys k1 and k2 in the same container, calling comp(k1, k2) shall always return the same value.
It is simply illegal to change the change the object in a way that affects how it compares to other objects within the associative container.
If you want to do... |
68,028,759 | 68,028,779 | Why a[21] is not equal to a[021]? | #include<bits/stdc++.h>
using namespace std;
int a[500];
int main()
{
a[21]=10;
if(a[21]==a[021])puts("Yes");
else puts("No");
return 0;
}
g++ -std=c++11
The output is No, can anyone tell me why?
| In C++ a leading 0 on an integer literal means that value is in octal (similar to the way that 0x21 means that value is in hexadecimal).
Each of these values will be different. Here's a quick online demo:
http://cpp.sh/3cws4n
Note: the default output format for cout is decimal so the values you see are in decimal.
|
68,028,860 | 68,028,980 | Created CMake static library has no symbols | My project looks like this:
include/util/safety.h
include/opcodes/8bit_load_opcodes.h
include/CPU.h
src/util/safety.cpp
src/CPU.cpp
src/main.cpp
src/opcodes/8bit_load_opcodes.cpp
CMakeLists.txt
With the CMake script below
cmake_minimum_required(VERSION 3.17)
project(gameboy)
enable_testing()
FIND_PACKAGE(Boost 1.65.1... | The safety.h only has one template function, and the definition part is located in safety.cpp, which is wrong. Template functions should be defined in headers, so you get an empty library here. We need to put the definition part in the header file, and remove the library libcpu_util.a
template<typename T>
T validate_a... |
68,029,551 | 68,044,303 | Difference color when drawing image in Cairo | i have an issue when using Cairo to draw image in linux system. the output image color not similar to original image if using cairo_image_surface_create method. like code below:
int width, height, channels;
unsigned char* data = stbi_load(imagePath.c_str(), &width, &height, &channels, STBI_rgb_alpha);
this->imageSource... | I am pretty sure that the red and blue channels are swapped on that right image. Sadly, I have no idea what STBI_rgb_alpha is and Google does not find anything that looks like helpful docs, so:
Cairo stores each pixel as a uint32_t with alpha in the high byte and blue in the low byte, i.e. uint32_t pixel_value = alpha... |
68,029,973 | 68,030,515 | Hints behave differently with boost than with standard library? | I'm trying to use a hint to insert into a boost::flat_map, but the obvious syntax does not compile, even though it does compile when I use a hint to emplace with std::map. Am I missing something obvious?
#include <boost/container/flat_map.hpp>
#include <map>
int main() {
std::map<int, int> map;
map.emplace_hin... | This is a known bug that was fixed in the 1.70 release.
|
68,030,097 | 68,030,244 | C++ Initializer list when dependencies do not have copy ctor or assignment operator | Approach 1
I have some type Foo which internally contains a std::mutex.
class Foo {
std::mutex m_;
};
I wrote another class Bar. Bar has Foo as a member and a constructor, like this (note - this code doesn't compile):
class Bar {
Bar(Foo foo) : foo(foo) {}
...
private:
Foo foo;
};
My IDE complains:
Call to imp... |
Is it that because Foo has a deleted copy constructor and deleted copy assignment, my only option is to have it constructed on the heap and then work via indirection (via pointers)?
Close, but not quite.
Because a mutex isn't copyable, Foo isn't copyable either by default. You're trying to copy, and that's not possib... |
68,030,254 | 68,031,664 | Making numbers in readable format in QSpinBox | I'm using QSpinBox for displaying and changing numbers. But numbers are large enough, it's hard to read them for user. Now I'm going to format numbers, for example if the number is 12345678 it should be displayed 12 345 678 or 12.345.678 like that. But I've no idea how to do that.
P.s: my english is not well, sorry for... | Use this code to set QSpinBox separate thousand number:
// Init
ui->spinBox->setGroupSeparatorShown(true);
ui->spinBox->setValue(123456);
// Set value on change
this->connect(ui->spinBox, &QSpinBox::valueChanged, [=] {
ui->spinBox->setGroupSeparatorShown(true);
ui->spinBox->setValue(ui->spinBox->v... |
68,030,473 | 68,114,166 | Debugging applications with large linked libraries takes a lot of time | I'm using some of the LLVM-Project libraries which results in a file the size of 180MBs when it gets linked. This causes a problem of delay every time I'm trying to debug the application which is waiting at least around 40 to 52 seconds to link those large libraries. I have an NVME M.2 SSD which is really fast at likin... | As @Alex Reinking said, LLVM Dynamic linking isn't supported on Windows but there is a way around it.
Following this link
I was successful to enable dynamic linking on Windows
|
68,030,985 | 68,031,046 | Struct definition for linked lists in c++ | While solving questions related to linked lists in C++, the struct definition for implementation of list was given as follows.
Struct node{
int data;
node *next;
node(int x) : data(x), next(NULL) {}
};
what is the significance of 3rd line :
" node(int x) : data(x), next(NULL) {} ".
Accessing it as a function is ... | node(int x) : data(x), next(NULL) {}
This is the constructor of node. It creates a node and initializes the member data with value x.
Read more What is this weird colon-member (" : ") syntax in the constructor?
If you are from python background, then it is same as
class Node:
def __init__(self, x):
... |
68,031,370 | 68,063,257 | C++ Protobuf, error when trying to build a FileDescriptor that imports another one | Currently I have the following two proto definitions, both .proto files are in same folder:
topmessage.proto:
syntax = "proto3";
message TopMessage {
// some fields
}
crestmessage.proto:
syntax = "proto3";
import "topmessage.proto";
message CrestMessage {
// some fields
TopMessage tm = 4;
}
Then, as part ... | it's a name problem, instead of using message name when building FileDescriptor, use the name of the .proto file ("topmessage.proto" for example)
|
68,031,646 | 68,032,685 | Why doesn't my example satisfy this "requires" expression? | I am attempting to use concepts with a variadic template. My template class is below. The concept should say: "Each type T should have a member function Func that accepts an input of type FuncArgType."
#pragma once
#include <tuple>
#include <concepts>
#include <iostream>
template<typename FuncArgType, typename... Ts>... | You don't need the lambda or std::apply. You can simply use the parameter pack directly:
template<typename FuncArgType, typename... Ts>
requires requires(FuncArgType func_arg, Ts... args)
{
(args.Func(func_arg), ...);
}
note that this allows implicit conversions.
Here is a full example.
However, your concept is c... |
68,031,888 | 68,032,092 | C++ for range loop for template class | I have a template class below that depends on 2 classes U and T
and have implemented the iterator function for both classes (see the end of this post).
I can iterate over the respective vectors of the class using iterators,
but I was wondering if it was possible to do the same using the for range loop syntax instead of... | You might provide function to return "range" (directly std::vector or a wrapper):
template <typename Z> // Or SFINAE or if constexpr or any other implementation
auto& getVector() { return std::get<std::vector<Z>&>(std::tie(m_vect_u, m_vect_t)); }
template <typename Z>
const auto& getVector() const { return std::get<co... |
68,032,407 | 68,032,645 | Qt No such slot using jump tables | I'm trying to create multiple QCheckBox without repeating code using a for. The problem is that for the connect I need a jump table array.
The jump table declaration it's okey but then Qt don't find the slot.
Here is a simplified example:
QVBoxLayout* v = new QVBoxLayout;
m_jumpTable[0] = &Example::showZero;
m_jumpTabl... | As per the comment, you will need to use the new signal/slot syntax for this so...
connect(check, SIGNAL(clicked(bool)), this, SLOT(m_jumpTable[i](bool)));
should be...
connect(check, &QCheckBox::clicked, this, m_jumpTable[i]);
(Assuming m_jumpTable[i] is of the correct type.)
|
68,032,700 | 68,063,652 | How can exclude the file extension when i rename the item in QTreeView | Now the action to rename will choose all the text i wanted to change ,but i want to keep the file extension used to be.
I don't want the user change the extension when they don't want to that.
How can i solve the problem.
thanks.
| Solved,
first,inherited by qstyledelegate and replace the editor by qlineedit
second,see
QStyledItemDelegate partially select text of default QLineEdit editor
|
68,033,075 | 68,033,564 | std::conditional compiles in Godbolt using msvc but not in VS2019 | I have this code:
#include<type_traits>
enum class DataFormat : int8_t
{
cDouble = 0,
cFloat = 1,
cChar = 2,
cBool = 3
};
class MatrixBase
{
protected:
MatrixBase(DataFormat const aDataFormat) : _dataFormat(aDataFormat) {}
public:
DataFormat getFormat() const { return _dataFormat; }
pri... | Changing rrr's declaration to
Matrix<float> m;
results in a compilation failure on all compilers:
Extraction of the resulting type from the inner std::conditional is missing. This should be:
using ActualDataFormat =
typename std::conditional<std::is_same<tType, bool>::value,
DataFormatBool,
... |
68,033,146 | 68,034,152 | Can someone explain this output? (C++) | Hello can someone please explain the output of the following C++ code espacially the numbers after the output of the first one 43211223334444
Here is the code:
void rek(int i) {
if (i > 0){
cout << i;
rek(i-1);
for (int k=0; k < i; k++)
cout << i; }
}
int main(){
rek(4);
return 0;
}
Here is the o... | We can write the dynamic stack development down manually. Below I have pseudo code with an indentation of four per stack level. The commands are on the left, the resulting output, in that order, on the right. I have replaced i with the respective number to make even more transparent what's going on.
rek(4) ... |
68,033,625 | 68,079,901 | Lambdas in unevaluated context (requires expressions) | I know there are several questions about this topic but hear me out, please.
I'm aware that we can use capture-less lambdas in unevaluated contexts (like decltype), but what about lambdas that do capture?
I couldn't find anything in the current C++ standard that would suggest that this is at all a problem since C++20, ... |
I'm aware that we can use capture-less lambdas in unevaluated contexts
This is not restricted to stateless lambdas. P0315R4 (Wording for lambdas in unevaluated contexts) removed the restrictions for lambdas (not just stateless ones) to not appear in unevaluated lambdas, whilst modifying the wording for some sections ... |
68,034,285 | 68,036,906 | When does NRVO kick in? What are the requirements to be satisfied? | I have the following code.
#include <iostream>
struct Box {
Box() { std::cout << "constructed at " << this << '\n'; }
Box(Box const&) { puts("copy"); }
Box(Box &&) = delete;
~Box() { std::cout << "destructed at " << this << '\n'; }
};
auto f() {
Box v;
return v; // is it el... | Apparently there was a change in the C++20 standard that affects copy/move elision (Quoting the draft):
Affected subclause: [class.copy.elision] Change: A function
returning an implicitly movable entity may invoke a constructor taking
an rvalue reference to a type different from that of the returned expression.
Funct... |
68,034,464 | 68,034,863 | Why XOR before SETcc? | This fragment of code
int foo(int a, int b)
{
return (a == b);
}
generates the following assembly (https://godbolt.org/z/fWsM1zo6q)
foo(int, int):
xorl %eax, %eax
cmpl %esi, %edi
sete %al
ret
According to https://www.felixcloutier.com/x86/setcc
[SETcc] Sets the destinati... | Because setcc sucks: only available in 8-bit operand-size. But you used 32-bit int for the return value, so you need that 8-bit result zero-extended to 32-bit.
Even if you did only want to return a bool or char, you might still do this to avoid a false dependency when writing AL. xor-zeroing doesn't cost "a cycle", i... |
68,034,613 | 68,034,673 | Search in Rotated Sorted Array Leetcode | I'm stuck in the question. My code keeps returning 3 as output for the inputnums = [4,5,6,7,0,1,2], target = 0. I'm doing some modified version of binary search and printing the indices of middle index and checking whether value at that index is equal to the target value.Values of middle indices in binary search are st... | You'll have to think on some modification in the binary search approach because binary search approach is applicable only for sorted array.
Hint : Think about finding some subarrays (which are sorted) and then apply binary search only on those specific parts.
Currently, you are not comparing a[low] & a[mid]. Only if yo... |
68,034,621 | 68,035,395 | C++ push-pipeline with multi-functors | Is it possible to chain 3 or more multi-functors with in a pipeline functionality and an elegant syntax like pipeline?
struct Filter0{//multi-functor; will be the last one in pipeline
template<Args...args> void operator()(Args&&...args){/*not important what is done here*/}
};
template<std::invocable F> struct Filter... | the key problem is that you demands F, the type of the functor which filter should receive, for parameter, but you actually provide a lambda expression.
auto pipe2 = filter2 | (filter1 | filter0);
pipe2 is Filter2<Filter1<Filter0>>, has parameter type Filter1<Filter0>, but you provide [left,right](auto&& arg){ left(ri... |
68,034,642 | 68,052,322 | Insertion of new nodes in a Tree | I want to code a class named tree for creating the Data Type Tree . I want a function inside class tree which will automatically create nodes and insert values in nodes level-wise( row-wise ).
For this I have also created Queue Data Type to store addresses of the left and right of a node which is being filled .
But whe... | #include<iostream>
using namespace std;
// Prortotypes
struct treeNode;
// Queue required for Tree
struct node{
treeNode *address;
node *next;
};
class queue{
node *front, *rear;
public:
queue(){
front=NULL;
rear=NULL;
}
void enQueue(treeNode *);
treeNode * deQueue();
} ... |
68,035,199 | 68,035,423 | std::vector<std::pair<int, float>> and void error | I'd like to sort m_correlationValues in descending order and get ids of the sorted list. I've got this error. I'll appreciate your help.
no match for 'operator=' (operand types are 'std::vector<std::pair<int, float> >' and 'void')
return idx_correlation.second; });
void MatrixCanvas::SortMatrix()
{
int naxes = ... | You have two problems:
sort does not return a copy of the sorted range. It modifies the range provided. If you want the original to be left alone, make a copy of it first and then sort it.
std::sort's third argument is a comparator between two values, which has the meaning of "less than". That is, "does a come bef... |
68,035,321 | 68,035,449 | Return value being passed as an argument | I come from a java background but am now working on large C++ code bases. I often see this pattern:
void function(int value, int& result);
And above method is called like so:
int result = 0;
function(42, result);
std::cout << "Result is " << result << std::endl;
In java, the following would be more common:
int resul... | First, this used to be an established technique to have more than one output of a function. E.g. in this signature,
int computeNumberButMightFail(int& error_code);
you would have both the payload int as the return value, and a reference to some error variable that is set from within the function to signal an error. It... |
68,035,480 | 68,035,778 | C++ pure virtual function has no overrider | I'm trying to recreate space invaders in it's most basic form. For my game i currently have a couple of classes, one for the game functionality, one for the game engine, and one for the player.
My current problem is that i have no overrider and no default constructor, Which i find very confusing, because in the "GameFu... | // User MUST OVERRIDE THESE!!
virtual bool OnUserCreate() = 0;
virtual bool OnUserUpdate(float fElapsedTime) = 0;
These functions must be overriden in every class that extends olcConsoleGameEngine. At the moment you have only overriden them in GameFunction.
Also you are using the new keyword to create a player instanc... |
68,035,992 | 68,036,192 | Too many initializer value eror | I am just a beginner in coding. I know the basics of c++ and c#. I was making a dll injector. I also followed a tutorial for a part. One part of the thing I have from the tutorial has an error and it is "Too many initializer values". I don't know what that means and why it is there. The error is at the nullptr in the n... | You appear to be trying to use the VirtualAllocEx WinAPI routine but you have not named that function in your attempted call, which is just incorrect syntax.
In place of the line:
void* allocated_memory(h_process, nullptr, MAX_PATH, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
you need to declare your void* pointer and ... |
68,036,536 | 68,036,601 | why the constructor and destructor of the same class object are implicitly called multiple times | English is not my native language,so please forgive me for my grammar problems.
When I run my program, I find that class constructors are called when defining objects and explicitly calling constructors。After calling the constructor and after leaving the scope, the destructor is called twice。
#include<iostream>
class t... | Your program runs as follows:
The constructor is called for the global object test myclassone;.
main() is called.
begain and mid are printed.
The constructor is called for the temporal object test(1,1,1).
The temporal object is assigned to the global object.
The destructor is called for the temporal object test(1,1,1)... |
68,036,555 | 68,036,679 | Can another tread unlock a mutex although it has not acquired the lock previously? | Can thread t2 unlock a mutex m, although the mutex was previously locked by thread t1? Can the mutex m be unlocked twice?
To illustrate these questions, I wrote the following little script:
#include <atomic>
#include <mutex>
#include <thread>
#include <iostream>
class spinlock_mutex {
std::atomic_flag flag;
pu... | The link you shared already has the answer
The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined.
"Undefined behavior" in C++ doesn't mean "the program can define it". It literally means "this behavior will never be defined by any conforming compiler". See this question for... |
68,036,729 | 68,036,923 | Code Not working in VS Code but works in OnlineGDB | I am practicing about primeSieve with C++ language in VS Code 1.57.1.
But the attached code doesn't show output in VS Code while it shows output in online c++ compiler like
https://www.onlinegdb.com/online_c++_compiler
Can anyone help me to resolve this issue.
#include<iostream>
using namespace std;
void primeSieve(){/... | Size of p[] is 1000. Your loop goes up to 1000. Try removing the = in the loops and just keep i < 1000.
|
68,037,055 | 68,038,075 | Tests fail when throw exception anywhere in TEST macro googletest | I have some problems with google testing framework
So, when I run the following code:
void f(){
throw runtime_error("");
}
TEST(test, test1){
EXPECT_THROW(f(), std::runtime_error);
}
So, I got such error:
make[2]: *** [test/CMakeFiles/gTest.dir/build.make:101: test/gTest] Segmentation fault (core dumped)
make... | The problem was with type of exception, thanks. Presented code works
|
68,037,062 | 68,037,121 | Any way to declare multiple friend classes in one statement? | I wish to declare multiple C++ friend classes in one statement as below, just to tidy the code. The reason is, in my actual application, there will be three or four friend classes, so it'll be messier than this sample.
Is it possible in any way?
class A{
friend class B, C; // this doesn't work
// friend class B... | No you need to write it out longhand.
I can't think of a grammatical reason why your notation couldn't be introduced. (C++17 allows you to shorten the namespace notation, for example, so you're idea is not without precedent).
Why don't you propose your idea to the C++ standards committee?
Of course there will be counte... |
68,037,236 | 68,037,833 | How do I convert a std::vector<thrust::device_vector<int>> to int**? | I am working on an application in which previous processing has produced a (shortish but variable-length) std::vector of (big) thrust::device_vectors, each with the same length (but that length is also variable). I need to convert it to a raw pointer on the device to pass it to a cuda kernel.
I did the process below, w... | Your error is here:
halfRawNumberSquareOnHost[i] = (thrust::raw_pointer_cast(numberSquareOnHost[i].data()));
it should be:
halfRawNumberSquareOnHost[i] = (thrust::raw_pointer_cast(numberSquareDevice[i].data()));
The first is grabbing a host pointer (not what you want at that point.) The second is grabbing a device p... |
68,037,252 | 68,037,581 | Is it safe to delete static casted pointer? | Consider abstract class AbstractMap and it's child classMyMap. Is it safe to perform the following delete operation? Or, should I delete the ptr only after re-casting to MyMap? And why? I guess it is unsafe, because in this case destructor of MyMap is not called.
AbstractMap* ptr;
ptr = static_cast<AbstractMap*>(new My... |
Consider abstract class AbstractMap and it's child classMyMap.
Is it safe to perform the following delete operation?
ptr = static_cast<AbstractMap*>(new MyMap());
delete ptr;
Deleting through a pointer to base sub object can be safe only if the destructor of the base (AbstractMap in this case) is virtual. If that pr... |
68,037,543 | 68,067,217 | pybind11 custom type segmentation fault | I try to write python bindings with pybind11. Since I also need non simple python types I have to create custom type casters. My problem is that whenever I call
get_point from python the LPoint2d will be returned but the following command will lead to a segmentation fault.
As far as I understand the python reference co... | It seems that just increasing the reference counter solves this issue.
static handle cast(const LPoint2d &src, return_value_policy policy, handle parent) {
py::object p3d = py::module::import("panda3d.core");
py::object plp = p3d.attr("LPoint2d")(src.get_x(), src.get_y());
plp.inc_ref();
... |
68,037,802 | 68,037,947 | why does an external function that takes a class object as a parameter calls a move constructor when it returns the same object | hey guys am still learning c++ but am just kind of confused about move constructors and copy constructors.
first i have a simple function that set a value to an object
#include <iostream>
#include "item.hpp"
#include "player.hpp"
player giveHealth(player user, int value) {
user.set_health(value);
return user;
... |
as you see i didnt add && on the return type
&& would make the return type a reference. If you were to return a reference, then there wouldn't be a move. But you'd be returning a reference to a local variable which would have been destroyed at the end of the function and as such the returned reference would always be... |
68,037,934 | 68,096,871 | SHARING_VIOLATION with multi-threaded file IO on Windows | I have some code that resembles this minimal reproduction example (the real version generates some code and compiles it):
#include <fstream>
#include <string>
#include <thread>
#include <vector>
void write(unsigned int thread)
{
std::ofstream stream("test_" + std::to_string(thread) + ".txt");
stream << "test" ... | We can rewrite the file writing using Win32 API:
void writeRaw(unsigned int thread)
{
const auto str = "test_" + std::to_string(thread) + ".txt";
auto hFile = CreateFileA(str.c_str(), GENERIC_WRITE,
FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, 0, nullptr);
DWORD ret{};
WriteFile(hFile, str.data(),... |
68,038,156 | 68,038,315 | would memory be leaked if on allocation failed in this code? | so for my homework I am not allowed to use std::smart_ptr however I am allowed to implement it myself and make any changes I want
so this is what I did
#ifndef SMART_PTR_H_
#define SMART_PTR_H_
template<class T>
class smart_ptr {
T* data;
public: typedef T element_type;
explicit smart_ptr(T* ptr = NULL)
: d... |
so IF a new threw std::bad_alloc would there be a memory allocation
If new throws, then that new will not have allocated memory. However, it is possible for the constructor to have made their own allocations, and a poorly implemented constructor can leak those allocations if the constructor throws.
You have a much wo... |
68,038,165 | 68,038,254 | why vector resize its size when i take input same element in the vecotor | //here if i take input n=5 then inserting in vec1 1,2,3,4, 5 then it consider in output only 1,2,3,4 according to its size but when i tried to insert in vec1 1,2,2,2,3,4 then its output is 1,2,2,2,3,4 how? as its size is 4.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
vector<int>... | cin>>i will overwrite your loop variable (so the loop terminates after you input a number that is >= n - 1).
You need to use a different variable to get your input.
int x;
cin >> x;
vec1.push_back(x);
|
68,038,253 | 68,038,402 | C++: Circular dependency with static members | I have the following code:
class B;
class A {
public:
static int somethingStatic;
int func() {
return B::somethingStatic;
}
};
class B {
public:
static int somethingStatic;
int func() {
return A::somethingStatic;
}
};
Build of that fails, because B is undefined.
So how can I... | You can't define A::func() referencing B's members before at least declaring B. A forward declaration of B is just saying that a class called B will exist, nothing about B's members. You can however declare A::func().
One way to do this is the typical .h file / .cpp file combination. If for whatever reason you want all... |
68,038,467 | 68,038,779 | Qt connect multiple signal with slot using function | I would like to set the font color and the background color if I click on a button.
I just added these two functions to the mainwindow.h file
public:
void createGrid();
private slots:
void clickCell(int row, int col);
mainwindow.cpp
QVector<QVector<QPushButton*>> buttons(10);
void MainWindow::createGrid() {
... | As per the comment: use the new signal/slot syntax to invoke a lambda as the slot. So your connect call should be something like (untested)...
connect(button, &QPushButton::released, this,
[=, this]
{
clickCell(i, j);
});
|
68,038,720 | 68,039,007 | Enum issue when converting from C++ to C | I am in the process of changing my C++ code into C code because I find myself gravitating toward more purely functional programs and am not really using any of the C++ features. The speedy compiling is also a plus.
I am having trouble with this particular bit in my header:
void gameLoop();
void doStuff();
enum GameSta... | As pointed out in the comments, you can't use the scope-resolution operator (::) in C (there is no such operator). Further, if you want to use GameState as a variable type (as in your declaration, GameState gameState;) then you will need to explicitly define it as a type, using the typedef keyword.
Here's a version of ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.