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 |
|---|---|---|---|---|
67,345,337 | 67,346,110 | Why does my program keep skipping out an if statement? | My program is designed to change gears of a bike using DC motors with encoders. I have a few if statements so far basically saying if a button is pressed then run the motor until the position is met then turn off the motor. For example this first statement would be moving from gear 1 to gear 2. Then I have another stat... | Try this: if motor reach to the desired position then buttonPushCounter++
#define ENCA 2 // PINK
#define ENCB 3 // YELLOW
// this constant won't change:
//const int buttonPin2 = 3;
const int buttonPin = 4; // the pin that the pushbutton is attached to
//const int ledPin = 13; // the pin that the LED is attac... |
67,345,382 | 67,345,482 | how to update global variable in if else statement (C++) | I am a newbie in C++ and it is a very easy task but all tutorials that I looked use cout some string in if-else conditions.
I want to update a global variable in if-else statement.
Here is the code;
double theta_radian{};
if (l2 >= l1)
{
double theta_radian = atan2(e2.y(), e2.x());
... | Here is the updated code:
double theta_radian; // NOTE: Brackets were not needed here, also 'double' is a value-type
if (l2 >= l1)
{
theta_radian = atan2(e2.y(), e2.x());
std::cout << "theta_local" << theta_radian << std::endl;
}
else
{
theta_radian = atan2(e1.y(), e1.x());
}
std::cout << "theta_radian" << ... |
67,345,726 | 67,346,011 | C++ Conditional template constructor | I have a HandleID class that acts similar to a smart pointer. Here are the important bits:
template<class T>
class HandleID
{
// Only if T is not const
friend class HandleID<const T>;
public:
HandleID();
HandleID(int id);
HandleID(const HandleID<T>& other);
HandleID& operator=(const HandleID<T>& other)... | The SFINAE way...
To simplify, you can add a using type for the no-const T
using no_const_T = std::remove_const_t<T>;
that is equal to T when T isn't const, different when T is const.
Then you can SFINAE enable your constructor/operator only when T and no_const_T are different
template <typename U = T,
std::... |
67,345,822 | 67,346,272 | How to create a recursive nested hashmap in C++? | def recursiveDict():
return collections.defaultdict(recursiveDict)
# I can create a dictionary like the following
dic = recursiveDict()
dic['a'] = 1
dic['a']['a'] = 1
dic['a']['a']['a'] = 1
dic['a']['a']['a']['a'] = 1
and so on....
I have returned to work with C++ after working for 4 years with Python and other dy... | Since you clarified that you are familiar with the basic concepts of operator overloading, I will sketch out a basic blueprint that you can follow to implement this syntax.
Your container will implement an operator[] overload that returns a helper object. Let's say that your container is called CharMap, and after all i... |
67,346,164 | 67,374,187 | How access class functions with <future> library? | I'm trying to make a program with #include <future> library.
When I try to access a header function, I get an error.
no instance of overloaded function "async" matches the argument list -- argument types are: (std::launch, int ()) [line 16, 14]
a pointer to a bound function may only be used to call the function
[line ... | You can pass a member function pointer and the instance of the class it will be called on:
#include <future>
#include <iostream>
namespace Class {
class FNH {
public:
int selam(){
std::cout << "selam";
return 1;
}
int selam_2(int a, int b){
std::cout << "selam "<< a << " " << b;
return 1;
}
}... |
67,346,165 | 67,346,240 | why does it throw an error when i compile it? | In index.hpp I have created a class that has multiple data members like int age, std::string city; etc. i have defined a constructor outside the class. In program.cpp i have created an object called sam. when i try to compile it, it shows error. what's the reason?
program.cpp
#include<iostream>
#include "index.hpp"
in... |
i have defined a constructor outside the class
Yes, but you have not declared it inside the class.
Also, you should not put code inside header files unless you are creating a template.
To fix your problem, add the declaration to the class:
class profile{
public:
profile(std::string new_name, int new_age, std::st... |
67,346,580 | 67,346,609 | Using std::conditional with iterator | In "Mastering the C++17 STL" book I saw both iterator and const_iterator implementation in one class using conditional for less code duplication
Here's my implementation for simple array class (most code for array class is skipped):
template<class T, size_t N>
class Array
{
public:
template<bool Const>
class Ar... | The member type pointer and reference of ArrayIterator should be defined as member type type of std::conditional, not std::conditional itself.
Change them to:
using pointer = typename std::conditional<Const, const value_type*, value_type*>::type;
// ^^^^^^^^ ... |
67,346,728 | 67,369,832 | How to deal with "not covariant" errors in paired hierarchies (C++) | Suppose I want a class Team to have a virtual get_player member which is implemented by FootballTeam and RugbyTeam, and that these implementations return the covariant types FootballPlayer and RugbyPlayer.
Suppose I also want Player to have a virtual get_team member which is implemented by FootballPlayer and RugbyPlaye... | We, unfortunately, cannot forward declare classes WITH inheritance.
So you have to drop one covariant return type and break the circular dependency loop somewhere.
|
67,347,085 | 67,347,148 | How to make multiple shapes appear on the same screen? | I'm writing a program that allows the user to draw different shapes through the menu options, the shapes after being drawn need to be on the same screen, but the problem is that after choosing another option in the menu to draw another shape, the previous shape disappears. How can I fix this? This is my program:
void d... | You have to use a separate Boolean state variables for each shape (rectangle_shape, circle_shape), instead of one integral variable that indicates the shape (shape):
bool rectangle_shape = false;
bool circle_shape = false;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
if (rectangle_shape)
{
draw_... |
67,347,402 | 67,347,488 | Pass on already deduced type as parameter type for a callback | So I'm trying to do something like the following
int x = 123;
myFunction(x, [](auto y) {
std::cout << y;
});
And myFunction is defined as
template <typename T>
void myFunction(T val, void(*callback)(T)) {
callback(val);
}
When trying to compile the code clang gives me the error could not match 'void (*)(T)' ... |
is it possible somehow to exclude the callback parameter from being deduced and instead just use the deduced type of val?
Sure.
If you define something like this
template <typename T>
struct self
{ using type = T; };
you can define myFunction() as follows
template <typename T>
void myFunction(T val, void(*callback)... |
67,347,411 | 67,347,600 | How to allocate memory fo array of objects | I am trying to create an array of objects in C++. As C++ Supports native objects like int, float, and creating their array is not a problem.
But when I create a class and create an array of objects of that class, it's not working.
Here is my code:
#include <iostream>
#include <string.h>
using namespace std;
class Emp... | The advice here, as always, is to use some STL container, like an std::vector.
That said you're probably going to need a default Employee constructor (unless you always initialize all the elements of the container with the constructor you already have, which is unlikely what you'll do, if you are to manually allocate m... |
67,347,545 | 67,348,779 | Compile-time set subtraction of two tuples | I have an application where I am constructing tuple out of a parameter pack:
template<class... T>
struct foo {
typedef std::tuple<T...> A;
}
And I have another tuple-type B defined as:
typedef std::tuple<char, int> B;
Is there a way to obtain a new tuple C, such that C is a set subtraction of the types in the sets A... | Disclaimer. Please don't put code like this into an actual code base. If you do, this implementation is by no means "optimal" and should be cleaned up before use (maybe add an answer if you do).
I found this an interesting challenge, and found the following solution:
// Try this live at https://compiler-explorer.com/z/... |
67,347,630 | 67,347,834 | Placement new and delete in constexpr functions | Let's imagine we have some class
struct Foo {
constexpr Foo(int& x) : x_(x) { x_++; }
constexpr ~Foo() noexcept { x_++; }
int& x_;
};
In C++20 with g++-10 -std=c++20 we can have a function like this:
constexpr int do_foo_1() {
int x = 0;
Foo* p = new Foo(x);
delete p;
return x;
}
int ... |
What is the difference between my usage and usage of these operators in standard library?
Your usage is not called std::allocator<T>::allocate or std::construct_at.
These particular functions - along with a few others - are specifically granted exceptions to the normal rule:
For the purposes of determining whether a... |
67,347,696 | 67,348,472 | Different signatures in operator overrides | I'm looking at some basic vector library, the class has two signatures for the operator*, but I can't get my head around the differences between the two.
vec4 vec4::operator*(float c) const {
return vec4(data[0] * c, data[1] * c, data[2] * c, data[3] * c);
};
vec4 operator*(float c, const vec4 &v) {
return vec... | The first one is a member function. That means you have a declaration inside a class, like so:
class vec4 {
public:
vec4 operator*(float c) const;
};
and it's definition outside the class:
vec4 vec4::operator*(float c) const {
return vec4(data[0] * c, data[1] * c, data[2] * c, data[3] * c);
};
It takes only... |
67,347,818 | 67,349,031 | TicTac Game just stops randomly | I wrote this Tictac game in c++... It runs fine and all except after certain number of inputs it just stops working like it goes to a new line in the compiler but sometimes i am able to complete the game.. i tried it in vscode as well as in dev c++ results are the same. is it a problem in my code..
#include <iostream>
... | I don't have much experience in the header <ctime>, but here is what I did to fix it:
#include <iostream>
#include <ctime>
using namespace std;
class TicTac
{
char board[3][3] = { {' ',' ',' '},{' ',' ',' '},{' ',' ',' '} };
int track;
public:
TicTac() : track(0) {
srand((unsigned)time(0));
}
f... |
67,348,059 | 67,348,274 | Why does `std::ranges::clamp` limits the number of projections so strictly? | According to [alg.clamp#5], the time complexity of std::ranges::clamp requires at most 2 comparisons and 3 application of projections. The possible implementation in cppreference is given by:
struct clamp_fn {
template<class T, class Proj = std::identity,
std::indirect_strict_weak_order<std::projected<cons... | This is very much intentional. I asked specifically about this complexity requirement during the LWG review of the paper in Prague because it outlaws the "obvious" implementation. And yes, this requires the implementation to invoke the projection on the value and "suspend the result in mid-air" with auto&& or equivalen... |
67,348,149 | 67,348,237 | C++ "not a class or struct name" error when inheriting from another class | I'm a beginner to C++ following this tutorial. I'm working on the section dealing with Classes and running into the following error.
not a class or struct name C/C++(262)
I am attempting to inherit the properties of a Shape parent class into a Circle class, but my editor claims that the Shape class is not defined. The ... | You are including "Shape.h" after "Circle.h". Hence Circle class is defined before Shape class. The compiler when it reaches line "class Circle: public Shape", it cannot identify "Shape" as any user-defined class or struct, thus it is raising the error. To correct it include "Shape.h" before "Circle.h" or include "Shap... |
67,348,211 | 67,361,275 | Why does bazel not see includes defined in bazelrc? | I am migrating large legacy makefiles project to Bazel. Project used to copy all sources and headers into single "build dir" before build, and because of this all source and header files use single level includes, without any prefix (#include "1.hpp").
Bazel requires that modules (libraries) use relative path to header... | Bazel use sandboxing: for each action (compile a C++ file, link a library) the specific build directory is prepared. That directory contains only files (using symlinks and other Linux sorcery), which are explicitly defined as dependency/source/header for given target.
That trick with --copt=-Ia/b/c is a bad idea, becau... |
67,348,244 | 67,348,354 | I've been working on my introduction to C++ project which is to make a game of NIM | I've been working on my introduction to C++ project which is to make a game of NIM. I've written program and I thought it should run smoothly but I've countered the following errors.
I know too much code but I couldn't figure out what is the issue that is stopping me from running the program.
I'm new to the programming... | You are missing an ending while condition after your do loop. The syntax is :
do{
//do stuff here
}while(condition);
In your case the condition would be (stonesNum!=0)
OR
Do
if (stonesNum == 0)
{
if (turn == 0)
{
cout << "The computer wins!" << endl;
retu... |
67,348,337 | 67,348,459 | Why is maxHeap initialisation syntax different from minHeap through priority_queue? | I was trying to create a minHeap using the regular syntax but found out that
maxHeap is initialised as:
priority_queue<int> maxHeap;
whereas minHeap is initailised as:
priority_queue<int, vector<int>, greater<int>> minHeap;
Any idea to why is it so in C++? It could have been much easier to remember if minHeap and max... | The priority_queue defaults to a max heap, so
priority_queue<int> is shorthand for priority_queue<int, vector<int>, less<int>>, which does indeed match the min heap syntax
|
67,348,379 | 67,350,589 | How to support implicit conversion from a Variant type, e.g. from int to unsigned long? | I'm trying to have my Variant type, a wrapper around c++17's std::variant, implicitly convert between types where appropriate. For instance, a char to std::string, or int to unsigned long. Here's my code:
#include <variant>
using variant_t = std::variant<
std::monostate,
std::string, bool, std::int32_t... | For an operator T () solution based (but with the std::variant as a member, not inherited)
template <typename T>
operator T () const
{
return std::visit(
[](auto const & val)
{ if constexpr ( std::is_convertible_v<decltype(val), T> )
return T(val);
else
{... |
67,348,613 | 67,349,431 | How to solve Assertion Error when using solvePnP? | I'm newbie in Visual Odometry and is following the tutorial of solving VO using PnP. However when I run the program, I get the following error:
terminate called after throwing an instance of 'cv::Exception'
what(): OpenCV(4.3.0) /home/wctu/opencv-4.3.0/modules/calib3d/src/solvepnp.cpp:754: error: (-215:Assertion fai... | The OpenCV function cv::solvePnP makes checks internally if the input data you supplied actually makes sense and actually matches the documentation (assertion). In your case it fails to do so and therefore throws an error message:
terminate called after throwing an instance of 'cv::Exception'
what(): OpenCV(4.3.0) /ho... |
67,348,850 | 67,349,660 | how to assign the enum values to strings using map in C++ | I have a map with string and enum. I am getting an enum value as input and from that I need to get a string.
Below is the code snippet I have written for that:
std::map<std::string, Messages> m_MessagesMap;
auto MessageID = GetMessageID();
GetStringFromEnum(MessageID);
std::string CJsonMessageUtil::GetStringFromEnum(M... | If you do not need that map for something else, then the easiest would be this, as suggested by @Casey :
std::string
getString( EnumType et )
{
switch( et )
{
case et1: return "string1";
case et2: return "string2";
...
default: assert(0);
}
}
But if you do need that map elsewhere (and of course not d... |
67,348,939 | 67,356,713 | AVX-512 - How to gather data from memory using assembly instruction? | I'm trying to gather 64-bit integers from memory using the assembler instruction. Below you can see how I call assembly code from C. Please notice that assembly code uses NASM syntax.
nasm_gather.asm file
bits 64
section .text
global nasm_gather:function
extern base_addr
extern vindex
nasm_gather:
; ... | Gathers need a mask (so they can record progress if interrupted, or if one element faults). NASM normally doesn't let you assemble illegal instructions without a warning; it's a NASM bug that it doesn't help you spot this error.
Also, your entire approach of using globals instead of function args is bad for both maint... |
67,349,064 | 67,501,411 | How to associate file types with Code::blocks when the association dialog doesn't come? | When I install codeblocks, there was an option about set this program for all c/c++ files and after that all file with .cpp, .C, .cxx, .cc extensions was associated to open with codeblocks as its default program. But, then I reinstall codeblocks then that options didnt come and I need to associate all cplusplus/c files... | In Code::Blocks go to Settings / Environment... / General Settings and to the right of Check & set file associations (Windows Only) click on Set now
|
67,349,483 | 67,349,560 | Why this implementation of vector doesn't work for string? | I've tried this implentation to do same as vector stl. This implementation works for int,float,double and char. But it doesn't work for string. It shows runtime error for string.Can you please fix the problem?
Here is the github repository link: https://github.com/Nayeem-CSE-CoU/DataStructure/blob/main/vector.cpp
I've ... |
ptr=new T();
Your vector implementation creates a single dynamic object.
void push_back(T n)
{
*(ptr+pos)=n;
pos++;
}
Your vector implementation attempts to access the pointer to a single object as if it was a pointer to an array of objects, accesses outside the bounds of that single object, and behavio... |
67,349,833 | 67,350,123 | Not Able to Understand how the following code is working | https://leetcode.com/contest/biweekly-contest-51/problems/replace-all-digits-with-characters/
I tried to solve this question but i was not able to do so so i looked into the discussions and i was able to find the answer but i was still not able to understand how the third line of the code is giving me the ouput.I know ... | The task is essentially asking you to replace every digit in the string with shift(s[i-1], s[i]).
So for every odd index i, you convert s[i] from a character to an integer (by subtracting '0') and adding that to the previous character s[i-1]. Another way to write the third line is like this:
s[i] = s[i-1] + (s[i] - '0'... |
67,349,849 | 67,350,035 | Trying to make a triangle that can rotate and move by applying the same transformations to all three points | I am trying to make boids simulation and for that I need triangles that move and rotate.
I made a Triangle and a Boid struct.
struct Triangle
{
olc::vf2d p1 = { 0.0f, 0.0f };
olc::vf2d p2 = { -5.0f, 10.0f };
olc::vf2d p3 = { 5.0f, 10.0f };
};
struct Boid
{
Boid()
{
}
Boid(olc::vf2d _po... | That does not look like a proper rotation to me. A quick search for a 2D rotation matrix yields something more like this:
x' = cos(theta) * x - sin(theta) * y
y' = sin(theta) * x + cos(theta) * y
i.e.
float x1 = triangle.p1.x * cosf(boid.angle) - triangle.p1.y * sinf(boid.angle) + boid.position.x;
float y1 = triangle.... |
67,350,240 | 67,371,626 | Why does loading a block of memory from a DLL only crash at the second call to memmove? | This is the class in question (only functions that pertain to this question) and everything it depends on (all written myself). It provides an interface to a DLL.
struct MemRegion {
const uint64_t address;
const uint64_t size;
};
enum Version {
VERSION_US,
VERSION_JP
};
const struct MemRegio... | I found out that HMODULE is equivalent to void*. Since you can't really use pointer arithmetic on void*s, you have to cast it to a uint8_t* or equivalent to properly get an offset.
Here's what that looks like in practice:
void save_state(Slot& slot) {
uint8_t* const _dll = (uint8_t*)((void*)m_dll);
for ... |
67,350,896 | 67,352,212 | Why can't the .size() of an array passed to a function as a constant reference be used as a template parameter? | I can't seem to figure out why the following code doesn't work:
#include <array>
template <long unsigned int s> void a() {}
template <long unsigned int s> void b(const std::array<int, s>& arr) {
a<arr.size()>(); // error: no matching function for call to 'a'
}
int main() {
const std::array<int, 2> arr {{0, ... |
Maybe in C++2X, it will work with consteval functitons.
For non-reference argument it works https://godbolt.org/z/Wx9va54z5.
I think it is fine to pass std::array of built-ins by value in general anyway.
(This works in GCC and clang.)
#include <array>
template <long unsigned int s> void a() {}
template <long unsi... |
67,351,183 | 67,351,290 | Making "Objects" In C++ | C++ | JS | So, I'm fairly new to C++ and have been fiddling with it, but fail to see why everyone says that C++ is the object-Oriented version of C. It's true C doesn't have classes, namespaces, etc. unlike C++ and JavaScript, but coming from JavaScript I find it quite difficult to make the connection with C++ and objects.
In JS,... | In C++, to make a custom object, you use classes, structs, and unions (although unions are a more advance topic).
A class is a user-defined type, where the default access modifier is private.
A struct is a class, but where the default access modifier is public.
A union is a more advanced topic, you may research it if y... |
67,351,625 | 67,351,746 | Why is there a difference of 90 degrees between rotation and direction? | Firstly, this problem is not unique to the current project I am currently working on and has happened several times before. Here is the problem.
I have a Triangle struct. olc::vf2d is a vector class with x and y components.
struct Triangle
{
olc::vf2d p1 = { 0.0f, -10.0f };
olc::vf2d p2 = { -5.0f, 5.0f };
... | There are some missing items to be able to diagnose. You have to have some kind of coordinate system. Is it a right-handed coordinate system or a left-handed coordinate system. You determine this by taking your X/Y origin, and visualizing your hand over it with your thumb pointing towards you. When the X-axis rotat... |
67,352,317 | 67,352,416 | why can I still give const value a new value | The book said I cannot change the value of const once I gave it a number, but it seems I can still give it a number even if it was given.
#include<iostream>
using namespace std;
const int fansc(100);
cout<< fansc << endl; //output:100
int fansc(20);
cout<< fansc << endl;//output:20
| The C++ code you gave won't compile, and rightly so. A const variable(a) is, well, ... constant. The error is shown in the following program and transcript:
#include <iostream>
using namespace std;
int main() {
const int fansc(100);
cout << fansc << endl;
int fansc(20);
cout << fansc << endl;
}
pax> g+... |
67,352,506 | 67,453,386 | When using file to read data and writing file, I can't attain the correct anwser, but when I debug, it works nice | It's about a prediction of house price using regression analysis.
The main of question is, when I set a break point at the end of the code, I can see the answer, but when I run it, it returns error codes.
I had changed the way to read the file, but it not works well.
Please point the error of mine.
#include<cstdio>
#in... | It has been solved by detele the funcation of freopen.After I detele it, the answer of debug is same as run. Prehaps the freopen has some secrets usage which I don't know.
|
67,352,690 | 67,352,714 | How can I declare 100 different named variables of the same type? | I have a class named Movies and I have a hundred different movie names in an array. I want to make these Movies into a Movies type. How can I do that? I don't want to declare 100 individual variables.
I tried to make Movie name as 'Movies' type variable by using 'for-statement' but it doesn't work:
I declared a variabl... | You can create an array (or list) of Movies objects and add new Movies objects to it (With 'new' operator) in the for loop.
Something like this:
Movies* moviesArray[array_size];
for (int i = 0; i < array_size; i++)
moviesArray[i] = new Movies(array[i]);
Note that you may need to define Movies constructor before co... |
67,352,943 | 67,352,989 | Can't use more modern for loop with vector of derived class object. Why? | I have a base class and some derived classes. I generate a few objects of the derived classes, cast to the base class, and push them into a vector. I can iterate over the vector using an int index, but not using an iterator. Any idea why?
Given...
class Product
{
protected:
char product_id;
char size_id;
pub... | The answer came from @Daniel Langr:
You are trying to copy a vector element into p in each iteration,
which is not possible (unique_ptr doesn't support copy semantics).
Easy fix: auto & p or, better if sufficient, const auto & p.
|
67,352,965 | 67,353,582 | How to avoid restarting the rectangle when drawing a new one? | I'm trying to draw multiple rectangles in this program, but whenever I draw a new rectangle, the old rectangle disappears, how can I draw a new rectangle without losing the old rectangle? This is my program:
struct Position
{
Position() : x(0), y(0) {}
float x, y;
};
Position start, finish;
void mouse(int butt... | Note that simply removing glClear would lead to all rectangles you ever drawn persisting on the screen - you won't be able to e.g. delete just one of them. It may also lead to the initial contents of the window contain some garbage pixels (though this can be fixed by doing glClear just at the start of your program).
A ... |
67,353,522 | 67,354,079 | How to compare date and time, given in string format? | I wonder to know how I can compare date and time in a string format in C++?
In other words my question is that how can I implement the compare function for the following class using libraries?
class DateTime {
private:
string date =;
string time ;
public :
DateTime (string d, string t) :date (d), time(t... | Here is how i could finalize it after searching different references.
First i got some random wrong results while testing with around 8000 inputs, but i realized one field that i commented in code should be updated before calling mktime() function.
class Time {
private:
time_t _timeType;
struct tm buf;
... |
67,353,526 | 67,353,557 | What's this type of initialization called? | I saw code in a Vulkan tutorial that goes:
VkImageMemoryBarrier imageMemoryBarrier = {
.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
.dstAccessMask = VK_ACCESS_SHADER_READ_BIT,
.oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
/* .image and .subresource... | This is still aggregate initialization, with the syntax of designated initializers supported since C++20.
T object = { .designator = arg1 , .designator { arg2 } ... }; (3) (since C++20)
T object { .designator = arg1 , .designator { arg2 } ... }; (4) (since C++20)
And about members not mentioned in initializer:
Fo... |
67,353,764 | 67,356,961 | How to get a source location from the function as argument without using static member function `current`? | I want to my function get_source to return a std::source_location type by taking a another function as an argument.
For example, I have a function named helloMessage and sumOf with the following argument types and return type:
void helloMessage(const char* message);
int sumOf(int num1, int num2);
And supposed I have ... | source_location::current is always the ultimate source of any source_location object. source_location is serious about being the location in the source of the code that created that object.
So there is no way to turn a function into the location in the source that it came from. Not unless that function object has store... |
67,354,793 | 67,354,841 | Can function pointers be de referenced | An excerpt from Object-Oriented Programming with C++ by E Balagurusamy-
Using function pointers, we can allow a C++ program to select a function dynamically at run time. We can also pass a function as an argument to another function. Here, the function is passed as a pointer. The function pointer cannot be de-referenc... | Your compiler is right, and the book is wrong.
But p(4,5) and (*p)(4,5) do the same thing, so it's almost never necessary to dereference function pointers.
[expr.unary.op]/1
The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function... |
67,354,903 | 67,355,320 | How to automatically initialize component parameters? | While doing a game engine that uses .lua files in order to read parameter values, I got stuck when I had to read these values and assign them to the parameters of each component in C++. I tried to investigate the way Unity does it, but I didn't find it (and I'm starting to doubt that Unity has to do it at all).
I want ... | Let's expand my comment. In a nutshell, you need to get from
"I have some things entered by the user in some file"
to:
"the client code can read the value without std::get"
…which roughly translates to:
"input validation was done, and values are ready for direct use."
…which implies you do not store your variables ... |
67,355,022 | 67,355,905 | Should I use linked lists or arrays when sorting 100 million elements? | I want to implement algorithms like quicksort, mergesort, etc., while working with a big data files, like 100 million elements. I can't use std::vector, std::sort, or anything like that, since this is a school assignment to get to know these specific algorithms. I can only use things that I will only write on my own.
S... | If the number of elements is large, the better option would be an array (or any type that has contiguous memory storage, i.e. a std::vector, allocating with new [], etc.). A linked list usually does not store its nodes in contiguous memory. The contiguous memory aspect leads to better cache friendliness.
In addition ... |
67,355,312 | 67,490,332 | SDL2.dll not found -lSDL2 in QT (QJoystick) | I'm using the QJoystick library in windows and MinGW compiler. I'm working in QTCreator.
I add it to the project.pro file:
include (./3rdparty/QJoysticks-master/QJoysticks-master/QJoysticks.pri)
And I just include #include <QJoystick>.
And if I'm running the code, I have this errors:
:-1: error: skipping incompatible ... | The problem may be caused by 32-bit sdl2 library version. Just go to the website http://libsdl.org/download-2.0.php then download x64 version and replace the SDL2.dll file in "...\QJoysticks\lib\SDL\bin\windows\mingw"
|
67,355,343 | 67,356,953 | Making a menu in C++ (OOP) | I'm creating a console application and have the need for a menu.
This menu can link to a next menu or preform an action.
What is a good OOP way of doing this?
I've seen many do it like this, but isn't really maintainable
TJ::clearScreen(); // Function I wrote to clear the console
TJ::breakSection('='); // Creates a lin... | It looks like you are looking for function pointers.
You can store them in a vector like so:
std::vector<void (*) ()> options{&functionA , &displayMenuB, &functionC, &displayMenuD};
options[0](); // Executes function A
options[1](); // Shows menu B
The only issue is that displayMenuB needs to be a function here, not ... |
67,355,370 | 68,931,282 | LoadPackagedLibrary failes with ERROR_MOD_NOT_FOUND on XBox | i'm currently trying to load a self-written dynamic link module (Compiled with /ZW /EHsc) in an UWP app using the LoadPackagedLibrary(...) function. It is required to load all libraries dynamically due to the way the libs are build. I have included the DLL within the project and enabled it as content (Also verified: it... | To compile a UWP DLL you need to pass these arguments to the compiler:
/D__WRL_NO_DEFAULT_LIB__ /DWINAPI_FAMILY=WINAPI_FAMILY_APP /MD
And these linker flags:
/APPCONTAINER /NODEFAULTLIB:ole32.lib /NODEFAULTLIB:kernel32.lib /NODEFAULTLIB:user32.lib /NODEFAULTLIB:msvcrt.lib windowsapp.lib
Furthermore, you need to speci... |
67,355,568 | 67,355,700 | I'm Trying to do Arithmetic on the Value of Two Pointers in C++ but it Sometimes Works and Sometimes Fails. Struggling to Find Explanations Online | I feel silly due to the basicness of the question but using my basic understanding of pointers my program is performing unexpectedly and I can't understand why.
#include <stdio.h>
void update(int *a,int *b) {
*a = *b + *a;
*b = (*a - *b);
}
int main() {
int a, b;
int *pa = &a, *pb = &b;
scan... | This has nothing to do with them being pointers, but with the operations being done.
*a = *b + *a;
*b = (*a - *b);
is done in sequence, so the *a value is changed before calculating *b.
I assume you were expecting something like
int a_before = *a;
*a = *b + *a;
*b = (a_before - *b);
|
67,355,581 | 67,356,442 | Print name of the function that the variables belong to in C++ | I am having so much trouble trying to solve this one out. I have to read a .c file that has three functions (add, sub and main) and I want to print to the console the name of their variables with the name of the function in brackets. I tried implementing a string function_name in my struct to store the value of the fun... | I can see you're incrementing id_ref now, but it's still not initialized, so you have undefined behaviour. Easiest way is to do = 0; where its defined in the struct.
As for your function, assuming there's no nested functions here, then you can just use a variable to keep track of that.
#include <iostream>
#include <str... |
67,355,732 | 67,356,203 | Does this pushback to a shared pointers vector causes memory leaks? | I'm making a node editor for a project I'm in, and I have an std::vector of shared pointers of Node, a class which has derived classes of different node types.
As I say, this is a vector of shared pointers (I'm experimenting with smart pointers so in this I'm a bit newbie), and when I create a node, the next code is ex... | As you might know, shared pointers delete data they point at by themselves at the moment the last shared pointer stops to point at the data (last reference is destroyed - shared pointers keep information about how many shared pointers point to this data stored in memory).
The only way you might have a problem with memo... |
67,356,268 | 67,356,415 | Problem with sending dynamic array in write system call in c++ | I have created two processes using fork, I want to send an integer array on heap memory to child process using write and read system call. In the parent process, if i make the array on stack the problem is solved but i want to do it in heap.Below is my code:
int fd[2];
pipe(fd);
pid_t p=fork();
if(p>0){
close(fd[0]... | There are two mistakes in your code.
The first is this:
int *info=new int[7];
//..
write(fd[1],info,sizeof(info));
Since info is an int *, the sizeof(info) is the same as sizeof(int *), the size of a pointer to integer. Usually the value will be either 4 or 8.
To fix this, you want to state the total number of bytes ... |
67,356,331 | 67,357,954 | Scoped_lock with repeating arguments | I use std::scoped_lock to guard pairs of objects in multi-threading environment. But I found that scoped_lock can lead to deadlock (in Visual Studio and gcc) if both its arguments are the same. For example,
#include <mutex>
struct S
{
mutable std::mutex m;
int v = 0;
S & operator = ( const S & b )
{
... | The phenomena you would really afraid of is "self deadlock". It occurs, when 2 conditions are fulfilled simultaneously:
the same thread calls repeatedly mutex.lock() on the same mutex object,
and that mutex belongs to non-recursive type, which does not support such recursive locking.
In C++ you have 2 types of mutexe... |
67,356,569 | 67,356,621 | Destructor and erase for shared pointers | As far as I know destructor is called when an element is erased from container, please correct me if I'm wrong..But Destr X prints shouldn't appear before after erase
#include <iostream>
#include <memory>
#include <vector>
struct X
{
X()
{
std::cout<<"Contr X"<<std::endl;
}
~X()
{
... | Since you use a shared_ptr, you have two references to both objects. These are x and x2, and the shared_ptrs inside vector v.
When you erase(), the destructor of shared_ptr is called, and the reference count is decremented, but still 1. Therefore object X still exists.
After leaving the scope of main(), the count is de... |
67,356,848 | 67,357,993 | Checking for a templated static method via concepts | I want to write a concept that checks if the type has a static method called foo. That method will have a templated parameter (the function will be called multiple times later with different parameter types).
Because of that templated parameter, it's quite difficult to check it. For the start, I thought I only check if... |
How do you correctly check for the existence of a templated static method (working in Clang and GCC)? And ideally, can you even check more than this? Like checking if the return type is void, or if it is callable.
I do have some constraints on template arguments, for the sake of the simplified example in the questio... |
67,357,282 | 67,357,365 | How does comparator in a set works with functor in C++? | Here is a simple program to show my point:
#include <iostream>
#include <set>
class comparator
{
public:
bool operator()(int* a, int* b){return *a < *b;}
};
int main()
{
std::set<int*> v1{new int{1}, new int{1}, new int{2}, new int{2}};
std::set<int*, comparator> v2{new int{1}, new int{1}, new int{2}, new int{2}}... |
I didn't define the operator to return true on duplicate values, so why would it show this behavior?
Because a std::set is intended to work with "less than" comparator, and it is implemented that way. That is, if for two values x and y in the set both x<y and y<x are false, then x and y are assumed to be equal and th... |
67,357,283 | 67,357,653 | check if there is anything next to the item in board (2D array) | Hey I'm making simple console game in C++. We have pawns on board (I made it using 2D dynamic array). I want to check if there is space to move our pawn. My simplest and best idea would be if I could check every square next to the pawn. The problem, however, arises when the pawn is in the corner of the board.
(x-1,y), ... | You can just check whether index is in bounds:
if (x >= 0 && x < SIZE_X && y >= 0 && y < SIZE_Y)
return array[x][y];
else
return nullptr;
Alternatively use try/catch:
try
{
return array[x][y];
}
catch (out_of_range e)
{
return nullptr;
}
|
67,357,331 | 67,359,053 | Making ReSharper use m_ convention | I'm using ReSharper C++ with Visual Studio but it uses some weird naming conventions that I don't like. I want to use this convention, which uses m_ prefixes on class member variables and snake case. They state that .clang-format can be used, but I'm not using LLVM, but VS' compiler.
Did someone make a file applying th... | You can configure the naming conventions on the "ReSharper | Options | Code Editing | C++ | Naming Style" options page, or choose one of the predefined schemes. That said, using both "m_" as a class member prefix and "t_" as a parameter name prefix is unusual, and none of the major C++ style guides use this convention.... |
67,357,693 | 67,357,765 | How to create custom C++ template that receives any type such as STL vector? | I'm trying to create data structure for sorting data that will firstly receive any kind of object, i.e. int, string or MyCustomObject and then perform other tasks.
// heap.h
template <typename T>
class Heap{
public:
Heap();
~Heap();
}
//heap.cpp
template <typename T>
Heap<T>::Heap(){}
template <typename ... | To remove the undefined reference to Heap<int>::Heap() error you have to put the definition into the header file, too. Yes, that may seem strange, but that is the usual approach with templates:
heap.hpp:
template <typename T>
class Heap{
public:
Heap();
~Heap();
};
template <typename T>
Heap<T>::Heap(){}
temp... |
67,357,925 | 67,358,136 | gl-shader: Error compiling shader: Compile failed. ERROR: 0:9: 'assign' : cannot convert from '4-component vector | I am trying to write a shader when I can pass both image saturation value like this https://gl-react-cookbook.surge.sh/saturation?menu=true and image colorscaling like this https://gl-react-cookbook.surge.sh/colorscale?menu=true in react native for that I am using opengl in react native. As from the example, I can ru... | Just read the error messages you got:
ERROR: 0:9: 'assign' : cannot convert from '4-component vector of float' to '3-component vector of float'
So 0:9 here tells us to look into the first string (counting is 0-based here) passed to glShaderSource, line 9, which in your code is:
vec3 brt = c.rgba * brightness;
Th... |
67,357,982 | 67,358,343 | how to print something after a while loop in C++ | Not really interested in finishing project I am more interested in knowing why I can print the answer variable after the while loop. I know it works if I have it inside the while loop. I know I get an error code -1073741819 which meant that the loop terminate abortly or there is something wrong after the while loop en... | As @Igor Tandetnik specified above, "scanf(" %c", &sign); will expects an argument of type *char and scanf(" %c", &quit[0]); will attempts to modify a const object (the first character of a string literal)"
I modified the code as such:
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int nu... |
67,358,053 | 67,367,361 | How to define a class template with reference type template parameter of template template parameter type | I would like to define a class template (hereafter called C) which takes a reference to an object of an to-be instantiated class template (hereafter called S) as template parameter. The objective is that C can be fully instantiated with one template argument.
S is a class template on its own which has one integral type... | In C++17, you might do
template<int I> struct S { int get() { return 42 + I; } };
template <auto& n>
struct C;
template <int I, S<I>& n>
struct C<n>
{
int get() { return n.get(); }
};
S<42> s;
int main()
{
C<s> c;
return c.get();
}
Demo.
Before C++17, template <auto& n> struct C; has to be replaced. fo... |
67,358,076 | 67,358,157 | Why does this basic Try-Catch fail to catch | I am learning about try-catch constructs in C++ and I have the following example that appears to fail to execute the code inside either of the catches. I have spent the past few hours trying to find the bug/issue without luck.
I am wondering if there is an issue with g++ on my machine -- I am using mingw's g++ and Wind... | it would be more logical to do something like that:
int main(){
try {
std::cout << "Start of Try-Catch\n";
int a = 13;
int b = 0;
if(b==0)
throw std::string("Passed the div by zero issue\n");
int p = a/b;
std::cout << "printing p: " << p << std::... |
67,358,251 | 67,359,809 | Binding an empty texture to image unit produces segfault | I want to draw to the texture via a compute shader. For this I am trying to bind the texture to an image unit:
glBindImageTexture(0, texture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
But when I run the code it produces a segfault.
This is how I create the empty texture:
unsigned int texture;
glGenTextures(1, &t... | According to https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindImageTexture.xhtml glBindImageTextureis only available in GL versions greater or equal to 4.2. After updating the GL version of my project everyone works fine now.
|
67,358,553 | 67,358,808 | Adding a constructor for specific case of templated class | I'm implementing a templated class Vect<std::size_t N>, a vector of N double. The general constructor takes a std::array<double, N> const& array, but I would like for instance for N=2 to have a constructor taking 2 double, to allow lighter instantiation.
I thought of a solution that works well (see below), but it feels... | What about avoiding the full class specialization and SFINAE enabling the two-double contructor only when N is 2?
Something as
template <std::size_t M = N, std::enable_if_t<(M == 2), int> = 0>
Vect (double x = 0, double y = 0): v{x,y} {}
I'd also like to have an alias Vect2D for Vect<2>, either with a typedef or anyt... |
67,358,825 | 67,423,631 | Installing SFML in CLion on windows | I got SFML installed in CLion but i am running into some issues when i try to run some basic code to see if it works properly.
#include <SFML/Window.hpp>
int main()
{
sf::Window window(sf::VideoMode(800, 600), "My window");
// run the program as long as the window is open
while (window.isOpen())
{
... | For your linker flags, you need to add sfml-window and sfml-system.
|
67,358,974 | 67,359,160 | C++: error, multiple definition of variable | Getting error message saying: SudokuGame\sudoku_solver.h:6: error: multiple definition of `grid'
Can anyone point out why? I guess i'm including sudoku_solver.h in the wrong way
See parts of my code files below.
sudoku_solver.cpp:
#include <iostream>
#include "sudoku_solver.h"
using namespace std;
bool isPresentInCol... | sudoku_solver.h is included in both sudoku_solver.cpp and main.cpp. Hence two definitions of the global variable grid.
|
67,359,409 | 67,359,658 | An 'asm' declaration is not allowed here | So I have this code here, which does not let me compile my dll, It just returns the error above.
void Math::AngleVectors(const Vector &angles, Vector *forward, Vector *right, Vector *up)
{
auto SinCos = [](float flRadians, float* pflSine, float* pflCosine)
{
__asm
{
fld DWORD PTR[fl... | Unfortunately, you can't do what you're trying to do. Due to security concerns, inline assembly isn't supported inside a lambda in Visual Studio 2019:
https://learn.microsoft.com/en-us/cpp/overview/cpp-conformance-improvements?view=msvc-160#inline-assembly-code-isnt-supported-in-a-lambda-expression
Paraphrasing the ans... |
67,359,711 | 67,359,887 | how to check if all of a vector values are equal to a determined value | I have this code:
int generatore(std::vector<bool> vettore, int *x) {
int y;
if (std::adjacent_find(vettore.begin(), vettore.end(), std::not_equal_to<>()) == vettore.end() {
return *x + 1;
}
else {
do {
y = rand() % *x;
} while (vettore.at(y) == true);
r... | Your if condition already checks whether all the values in the vector are the same, so you could check if the first element is also the one you want:
if (vettore.front() == false // add this
&& std::adjacent_find(vettore.begin(), vettore.end(), std::not_equal_to<>()) == vettore.end()) {
// ...
}
Doing this ch... |
67,360,049 | 67,360,546 | custom sort a vector 2d c++17 send to back | I know that we can sort a std::vector using c++17
but I want to customize this
currently, I'm doing this, v is vector<vector<int>>
v=[[10,125],[2,13],[3,2],[1,2]]
I want to sort this 2d vector in terms of summation of both numbers also I want to send those pairs to the end of the vector which has a higher first index ... | I find the following style much easier to reason about. You've given two rules, in order of importance:
Pairs with a particular ordering should be first.
Otherwise, compare by the sum.
std::sort(v.begin(), v.end(), [](std::vector<int> &lhs, std::vector<int> &rhs) {
const int lhs_sum = lhs[0] + lhs[1];
const int... |
67,360,578 | 67,360,652 | My winreg function is not being recognized | The error:
error: no matching function for call to 'RegCreateKeyExW'
What I am including:
#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <string>
#include <winreg.h>
My code:
HKEY hKey;
LONG result = 0;
char *path = "SYSTEM\\CurrentControlSet\\Control\\IDConfigDB\\Hardwar... | You are calling the TCHAR version of RegCreateKeyEx(). It is clear from the error message that RegCreateKeyEx() is resolving to the Unicode version, RegCreateKeyExW() (because UNICODE is defined in your build config). That version takes in a wide wchar_t string as input, but you are passing in a narrow char string inst... |
67,360,751 | 67,361,231 | Cover QLabel with QPixmap in C++ | My goal
This is an example of how I want the QPixmap to be contained inside the QLabel. The image keeps its aspect ratio and fills the given dimension. It will be clipped to fit.
Here is the CSS equivalent:
object-fit: cover;
Current code
This almost does what I want, but it stretches the image to cover the QLabel, s... | Can be implemented as QWidget subclass using QTransform.
class Label : public QWidget
{
Q_OBJECT
public:
explicit Label(QWidget *parent = nullptr);
void setPixmap(const QPixmap& image);
protected:
void paintEvent(QPaintEvent *event);
QPixmap mPixmap;
};
Label::Label(QWidget *parent) : QWidget(paren... |
67,360,907 | 67,360,932 | C++ convertion char int ARM | I have this very simple C++ code :
#include <iostream>
int main() {
std::cout << (int)(char)(int)char(-2);
return 0;
}
I am executing it on different setups :
Ubuntu 20.04 x64 (g++) -> Output : -2
Windows 10 x64 MSVC 2017 -> Output : -2
MacOS x64 Clang -> Output -2
Ubuntu Armv8 (g++) / EC2 Insta... | A compiler is allowed to choose if char is signed or unsigned. The standard says that they have to pick, but don't mandate which way they choose.
GCC supports -fsigned-char and -funsigned-char to force this behavior.
|
67,361,182 | 67,361,214 | How I can define a QMap with struct as key | I try to define a QMap which it's key is a C++ structure.
struct ProcInfo_S
{
quint8 tech = 0;
quint8 direction = 0;
quint8 category = 0;
};
QMap<ProcInfo_S, uint64_t> G;
G[{2,3,4}] = 2;
But when I compile this code, I get the following compile error:
error: no match for ‘operator<’ (operand types are ‘co... | The order of the elements in the map is determined by calling operator< of the keys. From documentation:
[...] The key type of a QMap must provide operator<() specifying a total order. Since Qt 5.8.1 it is also safe to use a pointer type as key, even if the underlying operator<() does not provide a total order.
One w... |
67,361,578 | 67,362,089 | C++20 <chrono> incomplete type used in nested name specifier | Now that GCC 11, which supports the new calendar and time zone features is released, I am trying to use these in my code.
With the following minimal example:
#include <chrono>
#include <iostream>
int main()
{
using namespace std;
cout << chrono::utc_clock::now() << endl;
return EXIT_SUCCESS;
}
compiled ... | Only partial C++20 chrono support is in gcc at this time. Here is the current state of the libstdc++ source code on this matter. This shows a simple forward declaration of utc_clock, and no definition, which is consistent with the error message you are seeing.
I am seeing more support for file_clock, including a low-... |
67,361,815 | 67,361,976 | Priority Queue With a Custom Comparator No Matching Constructor | I am trying to create a priority queue with a custom comparator but the following code gives me a compile error:
auto comparator = [](std::pair<std::vector<int>, File&> const &a, std::pair<std::vector<int>, File&> const &b) {
return a.first.front() > b.first.front();
};
std::priority_queue<std::pair<s... | There's a mismatch in your question, between uint64_t and int. Assuming that this is squared away:
You need at least C++20 in order to compile the shown code. Prior to C++20, lambdas are not default-constructible, and you attempting to default-construct your std::priority_queue.
You need to explicitly pass the comparat... |
67,361,860 | 67,361,880 | Lowest month won't show up | Write a program that lets the user enter the total rainfall for each of 12 months (starting with January) into an array of doubles.
I'm a beginner and I'm having trouble getting the lowest month to display, but the highest month displays.
Here is the code :
#include <iostream>
#include <iomanip>
using namespace std;
in... | You forgot to give highest_month and lowest_month an initial value, so they remains empty when the first month has highest or lowest rainfall.
Give them initial values to fix:
high_num = rainfall[0];
low_num = rainfall[0];
highest_month = months[0]; // add this
lowest_month = months[0]; // add this
Another way is addi... |
67,362,295 | 67,362,513 | Using isdigit() to determine if vector<string> index is letter or number | Trying to determine whether an index entry of a vector of strings is a letter or number. I am trying to use isdigit(), but it won't work because a suitable conversion can't be made using isdigit(stof(eq[i]))
Essentially, if I find that it is a letter, I want to change that value to 0.
#include string
#include vector
u... | How about just having a check as
if(eq[i].size() == 1 && std::isalpha(eq[i][0])) {
eq[i] = "0";
}
Would that work for your case?
EDIT: In case you have something like eq[3] = "abc"; i.e. entire strings rather just single letters, then something like this could be done:
if(
std::any_of(eq[i].cbegin(), eq[i].cen... |
67,362,383 | 67,363,213 | Can I skip some variables in boost serialization? | I have Players class and it has some variables
class Players
{
private:
friend class boost::serialization::access;
template <class Ar>
void serialize(Ar &ar, unsigned)
{
ar &username &password;
}
public:
std::string username = "", password = "", email = "";
};
I just want to serialize ... | Your code seems correct.
Remember that you cannot deserialize an archive that you created with an old version of the serialization routines.
If that is the case, as a very primitive workaround you can do this below, or learn how to deal with archive versions.
template <class Ar>
void serialize(Ar &ar, unsigned)... |
67,362,704 | 67,362,749 | Can I use a while or for loop to print the list? | #include <iostream>
#include <string.h>
namespace forward_circular_linked_list {
typedef struct Node {
std::string data;
Node *nextNode;
}Node;
class ForwardCircularLinkedList {
private:
Node *head;
public:
ForwardCircularLinkedList() : head(nullptr) {}
v... | Yes, you can use do-while or a for loop.
But do-while is more natural because it checks the condition after the body of code.
You have a circular data structure and (presumably) you want to print each element once.
Doing only one round of circling.
do{...move circulator}while(compare with head) has the right logic.
CGA... |
67,362,922 | 67,363,016 | How to move a range of element in a list to the front of an element also in the same list? | I want to move a range of element in a list to the front of an element also in the same list. I'm trying to use
list.splice(const_iterator pos, list &other, const_iterator first, const_iterator last)
to implement this.
This is my code:
list<int> ls{1, 2, 3, 4, 5, 6, 7, 8, 9};
// try to move [6, 9] to the front of 5
a... |
in actually pos != first
No. Given first = ++pos, pos is incremented and assigned to first. They are equivalent, and pos is in the range [first,last).
I think you want first = std::next(pos);.
LIVE
|
67,363,203 | 67,363,229 | Why does my vector need a constant value? | I'm trying to make an adjacency list graph implementation using vectors. In my vector declaration, I keep getting an error of "expression must have a constant value." I don't understand why I get this error, as I thought that vectors were already dynamic arrays and this wouldn't be a problem.
int nodes = 5;
vector<int... | The size of an array variable must be compile time constant, regardless of the type of the element of the array.
It is somewhat unclear whether your array declaration was intentional. If you want a dynamic array of vectors, then what you could use instead is a vector of vectors. If your intention was to create a single... |
67,363,895 | 67,363,975 | Big O Complexity of this double loop | I have been trying to figure out the Big O Complexity of this code:
void findSection(string s)
{
string start = "abc";
string end = "xyz";
int startIndex = s.find(start);
string tempS;
while(startIndex<s.size())
{
for(int i=startIndex; i<=s.size()-3; i+=3)
{
tempS = ... | TDLR: O(N²)
Outer loop is N iterations (one iteration for each char in the string).
Inner loop:
A normal inner loop that starts on the index of the outer loop is N/2. But since it's incremented by 3, It's (N/2)*(1/3). Or simply N/6
N*(N/6) is N²/6. Hence order of the highest polynomial: N²
|
67,364,134 | 67,365,985 | How to improve the speed of merkle root calculation in C++? | I am trying to optimise the merkle root calculation as much as possible. So far, I implemented it in Python which resulted in this question and the suggestion to rewrite it in C++.
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <streambuf>
#include <sstream>
#include <openssl/evp.h... | There are plenty of things you can do to optimize the code.
Here is the list of the important points:
compiler optimizations need to be enabled (using -O3 in GCC);
std::array can be used instead of the slower dynamically-sized std::vector (since the size of a hash is 32), one can even define a new Hash type for clarit... |
67,364,157 | 67,364,302 | Statement has no effect (if/else) | I'm a student who's learning C++ and I can't figure out why this problem is happening and how to fix it. If/else statement is not appearing when I run the program. If you could help me out that would be great, thanks! Also, please excuse what I've written down there, I'm just a student studying at high school. Thanks!
... | Corrected lines:
if (password=="Steven"){
cout<<"Selamat datang bos!"<<endl;
}
else
{
cout<<"Password salah, coba lagi!"<<endl;
}
|
67,365,234 | 67,365,343 | Why only static member can access private destructor? | #include <iostream>
using namespace std;
class MonsterDB
{
private:
~MonsterDB() {}; //private destructor
public:
static void DestroyInstance(MonsterDB* pInstance)
{
//static member can access private destructor
delete pInstance;
}
//...other methods
};
int main()
{
// instantia... | As you might recall, static (in this context) means that the function behaves like a global function, meaning it is not bound to a single instance of the class.
MonsterDB::DestroyInstance(pMyDatabase);
Obviously, if DestroyInstance is not static, this line will always fail (and it has nothing to do with private destru... |
67,365,267 | 67,366,252 | How to check more efficiently if every key in a std::map has been called | I know the title is weird but i don'y know how to say this, here is a really poor example of what i usually use:
void exercise1(std::vector<bool> &MyVec) {
std::cout << "Exercise 1";
MyVec.at(0) = true;
}
void exercise2(std::vector<bool> &MyVec) {
std::cout << "Exercise 2";
MyVec.at(1) = true;
}
int... | You can use a std::set to store the index of the functions you already called. Because a std::set only stores unique elements, you know that all functions have been called when the size of the set equals the size of the map:
std::set<int> already_called_funcs;
do {
int index = my_random_index();
exercises[... |
67,365,282 | 67,365,808 | Where is std::cout defined? | I would like to know how it works...
In the <iostream> header, there is namespace std:
#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>
namespace std {
extern istream cin;
extern ostream cout;
extern ostream cerr;
extern ostream clog;
extern wistream wcin;
extern wostream wcout;
... | How libstdc++ used by gcc does it:
Storage for cout is defined as a global variable of type fake_ostream which is presumably constructible without problems.
https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/src/c%2B%2B98/globals_io.cc
Then during library initialization rewritten with a placement new using ... |
67,365,720 | 67,366,301 | Accept socket connection in background while displaying Qt GUI in C++ | My problem
This function is supposed to accept() a connection from a client and return the new file descriptor newfd. The problem is that waiting for a connection freezes the Qt GUI.
int tcp_connect(int sockfd)
{
struct sockaddr_storage client_addr;
socklen_t sin_size = sizeof client_addr;
int newfd = accep... | Qt has QTcpSocket with asyncronous signal-slot api, you can use that. Or you can use QThread.
|
67,366,439 | 67,366,696 | Traversing through all possible elements in the data structure | I'm stuck with algorithmic problem for several days and any help is appreciated here.
Let's say that I have some modules in my app which can call other modules (as submodules). Something like blocks in Matlab Simulink. Also modules could call each one forming a loop.
For the sake of simplicity I've made a schema how th... | This would be the straightforward brute-force approach:
Make a list of modules you are going to disable.
Make a list of modules you have already looked at.
Add X to the list of modules you're going to disable.
Find a module you're going to disable that you haven't already looked at. Call it M.
Add M to the list of mod... |
67,366,762 | 67,366,830 | Derive a templated class' member variable type from a template member type | The title might seem a little confusing, so here is a more thorough explanation:
I have a templated class that has a vector as a member variable. The template argument is a struct (or class) that will have one certain variable. The type of this vector shall be derived from the template argument (from this one certain v... | You can get the type via decltype, if the names of data member are always the same:
template <class S>
class someClass {
vector< decltype(S::variable) > history; // if S=thingA, make it a double, if S=tingB make it a complex<double>
};
|
67,366,953 | 67,370,282 | hiding OpenGL symbols - using declarations | I have noticed that libraries which load OpenGL functions hide symbols using macros, for example Glad:
#define glGenQueries glad_glGenQueries
It allows to avoid collisions in more complex applications which may link to OpenGL through different libraries. I have a C++ library which also loads OpenGL symbols. Instead o... | The same names in different namespaces do not conflict, even if you use using. using GL::glGenQueries only tells the compiler that when you write glGenQueries, you mean GL::glGenQueries. It doesn't actually put the function outside of the namespace.
|
67,367,256 | 67,367,439 | list of pointer to base class-understand code | I am training to my exam in c++ and I don't understand why the code display only print function of the base class (also after I debug the code) and never go to the print of derived class.
Can you explain me why in a simple way, and does there is some issue I can do in order to also display the print function of derived... | You need to declare print() virtual in order for polymorphism to work.
Here is your example with suggested formatting improvements,
#include <iostream>
#include <list>
class A{
int a;
public:
A(int x):a(x){}
virtual void print() { std::cout << "a=" << a << ' '; }
};
class B:public A{
int b;
public:
... |
67,367,887 | 67,368,802 | Converting a R code into C++ for Rcpp implementation | I have this simple "for loop" written in R which I have to convert in to C++. Following is the reproducible example of R code:
# Parameters required
a <- 1.8
b <- 1
time.dt <- 0.1
yp <- 40
insp.int <- 7
ph <- 2000
dt <- seq(0,ph,time.dt) # Time sequence
MD.set <- c(seq(insp.int, ph, insp.int), ph) # Decision points ... | The error you are getting is simply because there's no automatic conversion from NumericVector to std::unordered_set<int>. You can fix this by doing:
std::unordered_set<int> sampleSet( MDSet.begin(), MDSet.end() )
This calls the unordered_set's constructor with beginning and end iterators of MDSet, which will populate... |
67,368,330 | 67,368,354 | I have an issue converting a float variable into a string in C++ | I am not an expert when it comes to using C++ so I need a little help here. Consider the following code:
float thresh = 3.0;
string threshold = to_string(thresh);
cout<<strlen(threshold)<<endl;
The terminal shows this error:
error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to
‘co... | strlen() is for calculating length of C-style string.
To obtain the length of std::string, you should use the size() or length() member function.
cout<<threshold.length()<<endl;
In case you want to stick to use strlen(), you can use c_str() member function to obtain C-style string from std::string.
cout<<strlen(thresh... |
67,368,581 | 67,369,024 | Why is this class and the objects of the class LOCAL in this IF statement? | I am a beginner at this so please bear with me. It might be something really simple that I may have missed as well. Here's the code.
class USA { // USA CLASS
public:
int Economy = 1000000000;
};
void ChooseAttributes() { // THIS FUNCTION IS CALLED SOMEWHERE IN THE CODE
if (PlayerCountryName == "USA") { // CHE... | You appear to have a type model in mind that's more like Python. C++ is a different language. Importantly, it's compiled.
For types, that means they are entirely created at compile time, before the first if statement is even run. At compile time, the relevant part is the { } block. It doesn't matter whether that's if(.... |
67,368,717 | 67,368,763 | Pointer to object and destructor | I am trying to understand why my code doesn't use destructor of class Name. In fact I write two classes. First one called Name and a second called Person that have a pointer to object Name. What I don't understand is why the program doesn't called to the destructor of Name, because I think when I write "new" I create a... | You are creating a memory leak here, because you create a new instance of Name here
Person(string name) { myname = new Name(name); }
but you never delete it. This is the reason why the destrcutor of Name is never called.
To avoid this you can use an std::unique_ptr or an std::shared_ptr, which will automatically handl... |
67,368,931 | 67,450,534 | C++23 - What are the benefits of the stacktrace_entry class? | When this class in the header file is added to the language, what problems will we be able to handle more easily and which syntaxes are planned to replace ? Below I am sharing a code I got from the cppreference web site.
Class std::stacktrace_entry
namespace std {
class stacktrace_entry {
public:
... | When you attach to a C++ program with a debugger and halt execution, one thing that is relatively easy to do (with some compile-time instrumentation) is work out the call stack of the code at a given point.
In general, the implementation of C++ is that the call stack is a linked list (possibly stored in a non-trivial w... |
67,369,145 | 67,369,624 | Structuring memory allocation and pointers to game objects in C++ | I'm writing a small game in C++. I'm relatively new to the language and I'm struggling with how best to store all the game objects in memory and how to refer to them during runtime.
It's a puzzle game where you push 'shapes' which consists of 'blocks' like tetris-pieces:
struct Block{
int x,y,z;
bool visible, s... | Memory allocation strategies in game engines, especially custom game engines, are typically designed to address the specific needs and challenges that are unique to the game that you are building.
There are a myriad of different strategies that can be employed, and each of them are suitable for different scenarios, wit... |
67,369,150 | 67,370,392 | How to make Constexpr function when "failure was caused by a read of a variable outside its lifetime" | I have struct that is specialised by an enum Id. I have a idOf function that takes a Type<Id> and returns the template-parameters.
I cannot really modify all the Types to include an extra member and recon this must be super simple to solve as constexpr.
I have hit an issue when the initialisation of the Type object is ... | The closest solution I have got is using a template object to determine the Id instead of using a constexpr expression:
template <typename cId>
struct IdOf;
template <Id cId >
struct IdOf< Type<cId> > : std::integral_constant<Id, cId> {};
template<typename T>
constexpr Id idOf = IdOf< std::decay_t<T> >::value;
This... |
67,369,345 | 67,369,582 | C++ concept member check type ambiquity with reference | I am learning C++ concepts, and I have an obnoxious problem:
I do not know how to differentiate between member variable being variable of type int and member variable being a int&.
Reason for this is that check I am using is using instance.member syntax and in C++ that returns a reference.
Full example:
#include <iostr... | The problem here is that expression concept checks use decltype((e)) in the check rather than decltype(e) (the extra parentheses matter).
Because t.val is an lvalue of type int (expressions never have reference type), decltype((t.val)) is int& regardless, as you've discovered.
Instead, you need to explicitly use the si... |
67,369,563 | 67,369,647 | How to prevent brace-initializer being interpreted as integer in function overload? | I have an Expression class that stores algebraic terms. The public interface I want it to have is something like:
expr.add({1}) // add term "x1". (error: code adds constant 1)
expr.add({0,1}) // add term "x0 * x1".
expr.add({0},2) // add term "2 * x0"
expr.add(2) // add constant 2
But I'm hav... | You can add an overload for initializer_list which will bind to the argument if it's in a brace initializer
void add(std::initializer_list<var_t> vars, int coeff=1)
{
add(std::vector<var_t>(vars), coeff);
}
In the implementation, you can just call the vector overload explicitly and/or give the user a warning.
Here... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.