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,630,935 | 67,632,244 | Does C++ namespaces behave differently in Windows and linux? | So I had this dll where I was using two typedefs wrapped in a namespace like so,
Constants.h
namespace constants
{
typedef int Integer;
typedef float Decimal;
}
Now the place where I was using it in the dll, I used the namespace without using the fully qualified name like using namespace constants.
Now there w... |
As far as I know when we use using namespace constants the typedefs scope will only be inside that translational unit, i.e here utility.h.
utility.h is not a "translational unit" by itself. If you include utility.h into another file, then that other file (with all its included files) is a translation unit.
For exampl... |
67,631,098 | 67,631,410 | What is the difference between ifstream, ofstream and fstream? | In file handling, I came across ifstream, ofstream and fstream. Can anyone tell me the main difference between these?
| This is how the class hierarchy looks like:
From https://www.cplusplus.com/img/iostream.gif
The three classes that deal with file handling are:
basic_ifstream
basic_ofstream
basic_fstream
ifstream, ofstream and fstream are "char" template specializations which means they are nothing but basic_ifstream<char>, basic_o... |
67,631,491 | 67,639,421 | Access Qt UI of another Class from the MainWindow Class | I want to understand if the following sequence is possible? If yes, how can we achieve the same?
MainWindow Qt GUI has a QPushButton
While we click on the QPushButton, it must open another Qt GUI Window (a different class, say 'DialogClass')
In the newly opened Qt GUI Window we have a QLineEdit and QPushButton
While w... | Qt foresees its signals and slots approach for such purposes.
The QPushButton of your class offers a signal clicked which you connect to a custom (self-written) slot of your dialog. The dialog's slot then should read the contents of the QLineEdit and publish these on the dialogs own (custom) signal, which is connected ... |
67,631,671 | 67,635,747 | Building 'multi interface' using wxWidget | I have read several demos given by the wxWidget package, but none of them is 'multi interface'. Say I want to write a simple game using wxWidget, I may need a menu interface, a game interface, a setting interface and so on. My question is how can I build them into a single App? Do I need several wxFrame and Close and S... | You can indeed have multiple frames, but by default closing the last frame terminates the application. You can use SetExitOnFrameDelete(false) to prevent this from happening or just make sure that you create the new/next frame (without necessarily showing it) before closing the previous one.
It is also possible to simp... |
67,631,852 | 67,631,959 | A lot of errors in classes with constructors and function | Here is the code for my file
#include <iostream>
#include <string>
#include <cstdio>
#include <fstream>
class Sphere{
private:
int x;
int y;
int r;
public:
Sphere();
void set_x(int first);
void set_y(int second);
void set_r(int radius);
int get_x();
int get_y();... | Here are the errors in your original code:
In the main function, you did not call that method getQuant() with an object. You will need to call the getQuant() method with an object to fix that error.
First error in the method Array::getQuant()
To compare x with xp, you will need to call getSphere(i).get_x() <= xp b... |
67,633,328 | 67,639,441 | Benefits of using std::stop_source and std::stop_token instead of std::atomic<bool> for deferred cancellation? | When I run several std::threads in parallell and need to cancel other threads in a deferred manner if one thread fails I use a std::atomic<bool> flag:
#include <thread>
#include <chrono>
#include <iostream>
void threadFunction(unsigned int id, std::atomic<bool>& terminated) {
srand(id);
while (!terminated) {
... | It didn't work because std::jthread has a special feature where, if the first parameter of a thread-function is a std::stop_token, it fills that token in by an internal stop_source object.
What you ought to do is only pass a stop_source (by value, not by reference), and extract the token from it within your thread func... |
67,633,895 | 67,674,499 | C++: Segfault when compiling vector template class | I'm learning C++ and going through and exercise of creating a custom vector template class, which looks like
template<class T> class Vector
{
private:
std::vector<T> mData; // data stored in vector
int mSize; // size of vector
public:
// Constructor
Vector(int size)
{
assert(size > 0);
... | Error was not during compiling but running
|
67,633,900 | 67,634,083 | How does C++ handle template functions with respect to type conversions | My general idea of how some compilers work, is that during the type checking phase (semantic analysis) the AST is annotated with type conversion information, so with a example such as: 1 + 1.2, the node representing 1 will be annotated with a float (or double) to indicate that it has to be converted so that it can matc... |
Is the function duplicated for the possible different types it's called with?
Yes. Thats roughly the idea of writing templates. test is not a function, test<int,double> is.
The following is not really what happens but it works as a mental model to quite some extend.
You call
test(1,1.0);
Compiler deduces T and B to ... |
67,634,251 | 67,635,732 | Getting BSOD After When Trying To Print The Next Process Name In LIST_ENTRY List | I am trying to print the next process name after my process in the LIST_ENTRY list.
But I am always getting BSOD.
#include <Ntifs.h>
#include <ntddk.h>
#include <WinDef.h>
void SampleUnload(_In_ PDRIVER_OBJECT DriverObject) {
UNREFERENCED_PARAMETER(DriverObject);
DbgPrint("Sample driver Unload called\n");
}
... | You have multiple nonsensical casts in the code:
*((LIST_ENTRY*)(LPBYTE)EP + 0x448);
and
((UCHAR*)(LPBYTE)list_entry.Flink - 0x448 + 0x5a8);
This means for example convert EP (not the address of it) to a byte pointer, then (since casts have right-to-left associativity) immediately forget about converting to a byte po... |
67,634,345 | 67,635,553 | Unreliable DateTime parsing by COleDateTime | I am trying to parse the date using ParseDateTime method provided by COleDateTime class. But parsing of two different dates in the same program is returning inconsisent values for the month.
Code Snippet:
COleDateTime dtCreated;
dtCreated.ParseDateTime(safe_cast<CString>(strCreatedDate));
Inconsistent RESULTS:
if strC... | Since String^ is your input you could use DateTime::ParseExact, and then convert DateTime to COleDateTime using DateTime.ToOADate:
COleDateTime dtCreated(DateTime::ParseExact(
strCreatedDate, isDMY ? "d.M.yyyy" : "M.d.yyyy", nullptr).ToOADate());
|
67,634,500 | 67,714,487 | What is the meaning of "i32 (...)**" in LLVM IR? | I was reading Clang++ produced LLVM IR code of following code:
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea(char* me) = 0;
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};... | Let's watch simpler code
struct A {
virtual void f1();
int width;
};
struct B: public A {
void f1() {};
};
B a;
After compilation it is possible to get this:
%struct.B = type { %struct.A.base, [4 x i8] }
%struct.A.base = type <{ i32 (...)**, i32 }>
@a = dso_local local_unnamed_addr global %struct.B { %struct.... |
67,634,609 | 67,660,293 | Multiple producer-consumer problem sticks on last consume | I'm trying solve a multiple producer-consumer problem using pthreads and semaphore but it always sticks at the last consume and halt.
It will have NO_ITEMS of items and suppose buffer have size BUFFER_SIZE
This is my current code below.
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <stack>
#d... | Flawed logic
Your code has a logic problem. Suppose NO_ITEMS is 100, and 99 have so far been consumed. Let two consumer threads arrive at the top of the while loop at that point, and suppose that both read count as 99 (but see below), and therefore enter the body of the loop. Both consumers will block on sem_wait(),... |
67,634,915 | 67,635,004 | Template argument deduction with template class inside template class | I have a template class inside another template class. How can I write a template function that will accept any combination of inner/outer template class?
template <class X>
struct A
{
template <class Y>
struct B
{
int q;
};
};
template <class X, class Y>
int f( typename A<X>::template B<Y>& ab )
{
retur... | This template accepts any combination of inner and outer:
tempalte <typename T>
int f(T& ab)
{
return ab.q;
}
You cannot deduce X and Y from typename A<X>::template B<Y>. See here for details: What is a nondeduced context?. The fundamental issue is that there is no 1:1 relation between the actual type that the... |
67,634,934 | 67,644,277 | Concatenate range of ranges to range | Let rw = ranges::views.
I'm trying to create exclusively using range-v3 an analog of the construction:
std::vector<int> v;
// range = {0, 1, 2}
auto range = rw::ints (0, 3);
for (int i : range)
for (int j : range)
v.push_back (func (i, j))
// v = {func (0, 0), func (0, 1), func (0, 2),
// func (1, 0... | Thanks to Jarod42.
// range = {0, 1, 2}
auto range = rw::ints (0, 3);
// range_of_ranges = {{func (0, 0), func (0, 1), func (0, 2)},
// {func (1, 0), func (1, 1), func (1, 2)},
// {func (2, 0), func (2, 1), func (2, 2)}}
auto range_of_ranges = rw::transform (range, [] (int i) {
... |
67,635,028 | 67,635,105 | How to ensure auto parameters of a lambda are of the same type? | If I have a lambda function
auto foo = [](auto && a, auto && b){ /* some random c++ code */ };
How can I declare that a and b should be the same type even if that type can be any type?
| You can add a static_assert in the lambda body:
#include <type_traits>
auto foo = [](auto && a, auto && b){
static_assert(std::is_same<typename std::remove_reference<decltype(a)>::type,
typename std::remove_reference<decltype(b)>::type>::value,
"Must be of the same type!");
};
You might w... |
67,635,049 | 67,635,144 | OpenGL draws outside window bounds | while drawing a GL_LINE_STRIP I noticed the drawing is outside of window bounds, I can't see half of the drawing.
I want to center it within the window and automatically resize it to fit it.
can someone redirect me to how can I achieve that?
this is what I'm seeing:
I want it to be in that size & position:
This is my... | To solve the isseu, you need to know the bound of your curve. You have to change the the orthographic projection:
glOrtho(-6, 6, -6, 6, -1, 1);
In Orthographic Projection, the view space coordinates are linearly mapped to the clip space coordinates. The viewing volume is defined by 6 distances (left, right, bottom, top... |
67,635,484 | 67,635,485 | How does std::reverse_iterator hold one before begin? | This is a code example using std::reverse_iterator:
template<typename T, size_t SIZE>
class Stack {
T arr[SIZE];
size_t pos = 0;
public:
T pop() {
return arr[--pos];
}
Stack& push(const T& t) {
arr[pos++] = t;
return *this;
}
auto begin() {
return std::reverse... | Initialization of std::reverse_iterator from an iterator does not decrease the iterator upon initialization, as it would then be UB when sending begin to it (one cannot assume that std::prev(begin) is a valid call).
The trick is simple, std::reverse_iterator holds the original iterator passed to it, without modifying i... |
67,635,498 | 67,635,515 | Cannot convert argument from wchar_t[260] to LPSTR | I'm trying to get the path of my executable on my windows machine.
std::string get_exe_path_dir()
{
wchar_t path[MAX_PATH];
GetModuleFileName( NULL, path, MAX_PATH );
PathRemoveFileSpec(path);
std::wstring ws(path);
std::string str(ws.begin(), ws.end());
... | You are using explicit wchar_t instead of TCHAR, so you should use explicit Unicode version GetModuleFileNameW and PathRemoveFileSpecW instead of GetModuleFileName and PathRemoveFileSpec.
|
67,635,624 | 67,635,751 | Building project with clang-cl in VS2019 | I'm trying to build a project with clang-cl in Visual Studio 2019 checking C++17 option in the project's properties. And I get the warning:
constexpr if is a C++17 extension [-Wc++17-extensions]
I suppose that it should appear only for code that is not compiled as C++17. So why do I get this? Is the code compiled as ... | One possibility is that you have a different Standard selected for your project and an individual source file in that project. Try checking the "Language" option in the property sheet for the 'offending' source file(s) – make sure it is also set to use the C++17 Standard.
|
67,635,654 | 67,636,449 | Trying to solve Knights Tour on nested vector<vector<pair<int,int>> but is is not working | I have written a code for knights tour problem which work for 2D array but not for vector<vector<pair<int,int>>
WORKING CODE
#include <bits/stdc++.h>
#define N 8
using namespace std;
bool isPossible(int sol[N][N], int x, int y)
{
if ( sol[x][y]==-1 && x >= 0 && x < N && y >= 0 && y < N)
{
return true... | Both programs have undefined behavior because you access the 2D array/vector out of bounds.
You first check if sol[x][y] == -1 and then you check if x and y are within bounds:
bool isPossible(int sol[N][N], int x, int y)
{
if (sol[x][y]==-1 && x >= 0 && x < N && y >= 0 && y < N)
You need to check the bounds first.... |
67,636,231 | 67,636,550 | What is the modern, correct way to do type punning in C++? | It seems like there are two types of C++. The practical C++ and the language lawyer C++. In certain situations, it can be useful to be able to interpret a bit pattern of one type as if it were a different type. Floating-point tricks are a notable example. Let's take the famous fast inverse square root (taken from Wikip... | This is what I get from gcc 11.1 with -O3:
int_to_float4(int):
movd xmm0, edi
ret
int_to_float1(int):
movd xmm0, edi
ret
int_to_float2(int):
movd xmm0, edi
ret
int_to_float3(int):
movd xmm0, edi
ret
int_to_float5(int):
movd xmm0, edi... |
67,636,383 | 67,636,458 | Set pointer in class | i'm new to c++, and i start a project with SFML. I need a class that can handle sprite, so i do:
#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
class Particle
{
private:
sf::Sprite **sprite;
public:
Particle(sf::Sprite* sprite)
{
this->sprite=&sprite;
};
~Particle()... | The error is because
**sprite.setPosition(newPos);
is the same as
**(sprite.setPosition(newPos));
That is, you try to dereference what sprite.setPosition(newPos) returns.
To solve that error (leaving the other problem I already mentioned in a comment) you need to dereference the pointer variable itself:
(*sprite)->se... |
67,636,496 | 67,637,745 | Compiler Error: no match for 'operator[]' C++ | The compiler says the following error message for my simple depth first search algorithm written in C++:
error: no match for 'operator[]' (operand types are 'std::vector' and 'std::vectorstd::vector<int >::iterator {aka __gnu_cxx::__normal_iteratorstd::vector<int*, std::vectorstd::vector<int > >}')
if (!visited[i])
H... | The problem is in visited[i], where i is an iterator. If you want to iterate two vectors with a common index, then use directly a int or size_t, because iterators belong to a single container (in this case, to adj_matrix, not to visited) and behave like pointers, not like indexes.
So replace your last piece of code wit... |
67,636,890 | 67,637,227 | Injecting parameters with dependency injection | I am trying to setup dependency injection (https://boost-ext.github.io/di/) in my project and get the following compilations errors errors "no matching overloaded function found" and "invalid explicit template argument(s)".
My test setup is as follows
#include "di.hpp"
namespace di = boost::di;
class IA{
public:
v... | You call is wrong, it should be similar to:
auto test = injector.create<std::unique_ptr<IC>>();
Demo
|
67,636,972 | 67,637,012 | How to add rhs value to class in C++ (operator overloading) | I have a matrix class and I want to overload the * operator in c++ to multiply a scalar to the matrix.. I am able to achieve..
matrix1 * matrix2
matrix1 * 5
but I also want 5 * matrix1 to work.
How to achieve this.. Idk what to search for this, nothing is coming related :|
| Like this, calling your existing matrix * scalar function with the arguments reversed:
inline matrix operator*(int scalar, const matrix& mat) {
return mat * scalar;
}
The above is a free function, to be declared in whatever namespace matrix is in, not inside the class.
|
67,637,043 | 67,637,109 | Casting time_points: dependent name error | dependent-name 'BaseClock:: time_point' is parsed as a non-type, but instantiation yields a type
is the error I get for the following code:
struct H { SomeClock::time_point time; };
template<typename BaseClock>
void RelativeClock<BaseClock>::someMethod(H h) {
//...
typename BaseClock::time_point newtime;
n... | This should fix your compilation error:
newtime = time_point_cast<typename BaseClock::time_point>(h.time);
You were missing the typename there. It's needed to indicate that time_point needs to be a type and not a value.
|
67,637,112 | 67,637,477 | emmintrin.h:31:3: error: #error "SSE2 instruction set not enabled" # error "SSE2 instruction set not enabled", "scaling solution" | I have been building multiple projects that require sse2 instruction set. Adding -march=native as mentioned in sse2 instruction set not enabled has done the job till now.
However, in the 3 projects I have needed this, the gcc commands in the makefile were easy to locate and editing slightly the makefile worked. Now I t... | You can add the compiler option -march=native in CMakeLists.txt
SET(PROJECT_FLAGS "-march=native")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${PROJECT_FLAGS }")
Or
add_compile_options(-march=native) # CMake 2.8.12 or newer
|
67,637,307 | 67,637,413 | Conversion from const char[] to class with constructor from string | I try to pass a string to a function instead an object of class A, but I get an error.
Why is it not working and how can I make it work?
#include <string>
class A {
public:
A(const std::string &str) {
}
};
void test(const A &a) {
}
int main()
{
A a("abc"); //it's ok
test(a); //it's ok
test("abc... | In the implicit conversion sequence of one type to another, there is a rule that states: At most, only one user defined conversion can be applied. In
test("abc");
You need two user defined conversions. First you need to conversion from const char[N] to std::string, which is considered a user defined conversion1. Th... |
67,637,326 | 67,639,279 | Can I use std::stop_source to deferred cancel all worker threads from a worker thread? | I have two threads running in parallell started from the main thread.
Either thread may fail. If it do so I want to ask the other thread to cancel as well.
In C++ 20 there is std::stop_token and std::stop_source.
I have found several examples where the main thread ask all threads to cancel (deferred cancelation).
Howev... | In order for a location of code to be able to request a stop, that location must have a std::stop_source. In order for a location of code to be able to respond to the stop, it must have a std::stop_token taken from a particular stop_source.
Therefore, in order for a location of code to be able to both request and respo... |
67,637,357 | 67,637,792 | How to disable deduction of a template if an array is passed? | I'm trying to write a sum function so that numbers and arrays fall into its different specializations.
template<typename T>
std::enable_if_t<!std::is_same_v<std::decay_t<T>,const T*>,T>
sum(T arg1, T arg2) {
return arg1 + arg2;
}
template<typename T, std::size_t L1, std::size_t L2>
void sum(const T(&first)[L1], c... | You can use std::is_pointer to check for and exclude pointer types:
template<typename T>
std::enable_if_t<!std::is_pointer_v<std::decay_t<T>>, T>
sum(T arg1, T arg2) {
return arg1 + arg2;
}
live demo
But note - the type of arg1 + arg2 can be larger than T due to implicit promotion rules. It's safer to use auto re... |
67,637,420 | 67,637,449 | Class constructor "eating" up values | So I'm trying to run this sim program for a class that makes us build a Bet class using sets.
Here's the class definition:
class Bet2{
private:
set<int> mainNumbers;
set<int> luckyNumbers;
public:
Bet2();
void show() const;
set<int> getMainNumbers();
set<int> getLuckyNumbers();
};
So I decided... | std::set can store only up to 1 copy of a given value.
The lack of numbers should be because the random numbers happened to become the same as the numbers that were previously seen.
If you want to store multiples of the same value, you should use std::multiset instead.
If you want to generate a unique set of defined nu... |
67,637,538 | 67,637,606 | c++ constant function in class | Hello can someone please explain what does the const means in front of function declaration like so :
const void function(parameters);
I know, it means you can't modify what it returns, but how are we able to modify, what it returns? Thanks for any kind of reply.
| It means exactly nothing. The function does not return anything so the const modifier modifies nothing.
|
67,637,722 | 67,701,189 | Mapbox compile offline tool on Linux | I am trying to compile the Mapbox GL offline tool (mbgl-offline) on Linux to generate a database with offline data for a specific region.
Steps followed as posted in github repository to compile the offline tool on Linux but it failed:
git clone --recurse-submodules https://github.com/mapbox/mapbox-gl-native.git
cd ma... | The README.md clearly states how to build Mapbox: Developing
You tried to compile it with make, but if you look around the repository there are a lot of CMakeLists.txt, which indicates that you should use CMake to compile it.
These are the steps I followed to build it:
git clone git@github.com:mapbox/mapbox-gl-native.g... |
67,638,303 | 67,638,351 | C++ implementation of 2-3-4 Trees | I was looking for C++ implementation of 2-3-4 Trees online and was surprised that
There is no code available for it. I couldn't find anything. I have studies this Trees
But writing code is difficult for me as of now so I wanted to look at some already
implemented code. Is there an easy way to implement it using a 2-... | You're unlikely to find a production-quality implementation. A red-black tree is an isomorphic structure to a 2-3-4 tree, and is more efficient and easier to work with. So you'll find plenty of RB trees, and they're basically the same thing. (You could rework a RB tree into a 2-3-4 tree but that would just make it wors... |
67,638,371 | 67,638,436 | Left rotating array by d elements in C++ using vectors | The C++ function code I wrote:-
values of n=5(no. of elements in array) and d=4(no. of elements by which array is to left rotated)
vector<int> rotateLeft(int d, vector<int> arr)
{
int n=arr.size();
vector<int> temp;
for(int i=0;i<d;i++)
{ temp[i]=arr[i]; }
for(int j=d;j<n;j++)
{ arr[j-d]=arr[... | You get Segmentation fault for two reasons:
You have to resize temp to match arr before accessing the elements with the square brackets either with std::vector<int> temp(n); or calling temp.resize(n) afterwards.
You have made an indexing error which results in an access that is out of bounds: arr[n-d-k]=temp[k] should... |
67,638,439 | 67,648,504 | How do I draw an OBJ file in OpenGL using tinyobjloader? | I am trying to draw this free airwing model from Starfox 64 in OpenGL. I converted the .fbx file to .obj in Blender and am using tinyobjloader to load it (all requirements for my university subject).
I pretty much slapped the example code (with the modern API) into my program, replaced the file name, and grabbed the at... | E: When I wrote this answer originally I had only worked with vertices and normals. I've figured out how to get materials and textures working, but don't have time to write that out at the moment. I will add that in when I have some time, but it's largely the same logic if you wanna poke around the tinyobj header yours... |
67,638,689 | 67,639,952 | Is there a way to switch the dimensions order in a multi-dimensional vector? | I have a 3D vector and I want to be able to chose which dimension to plot as a function of another dimension.
So far, I am doing this manually: I create a second 3D vector and re-organize the data accordingly. This solution is not very practical since I need to switch the indexes (inside the nested loop) every time I w... | C++ does not provide multidimensional containers for the same reason that containers like std::vector do not provide a standard operator+ etc.: there is no standard that fits everyone's needs (in the case of a + operator, this could be concatenation, element-wise addition, increasing the dimensionality, who knows). If ... |
67,639,065 | 67,639,472 | MQTT client not subscribing to a given topic (or callback not working as intended) | I'm going nuts trying to guess why my Arduino Nano33 is not being able to receive mqtt messages. Or may be it receives them but the callback function is not working as I intend (since the callback is the only way I have to see if a message was received).
I can publish messages without problem. Any clues on what can be ... | You need a client.loop(); line in your loop() main function. Without that line, you MQTT code never gets executed.
|
67,639,564 | 67,639,668 | C++ unable to handle large boolean arrays | I am writing a function that requires me to turn a file into an array of 0s and 1s. I figured this was most easily accomplished using a bool array. However, the below code fails and crashes for files larger than ~1MB. My machine has 8GB RAM, so I see no reason for the crash.
string file_name;
cin >> file_name;
string t... |
I am writing a function that requires me to turn a file into an array of 0s and 1s. I figured this was most easily accomplished using a bool array.
I don't know why you figured that, the easiest way is to store a file as bytes, exactly as the file contains. vector<bool> does this, for example, it doesn't store each b... |
67,640,392 | 67,642,821 | Why does D'Esopo-Pape algoritham have worst case of exponential time comlexity? | D'Escopo-Pape algorithm is very similar in implementation to the Dijkstra's algorithm and works with negative weight edges but it doesn't work with negative cycles. It is apparently faster then Dijkstra's algorithm and Bellman-Ford algorithm in most cases. But there is apparently special cases where this algorithm tak... | Exponential time
This won't be a full proof, you can read "A Note on Finding Shortest Path Trees" (Aaron Kershenbaum, 1981, https://doi.org/10.1002/net.3230110410) if you want that. An other source you may find interesting is "Properties of Labeling Methods for Determining Shortest Path Trees".
The intuitive reason why... |
67,640,462 | 67,640,868 | std::min vs ternary gcc auto vectorization with #pragma GCC optimize ("O3") | I know that "why is my compiler doing this" aren't the best type of questions, but this one is really bizarre to me and I'm thoroughly confused.
I had thought that std::min() was the same as the handwritten ternary (with maybe some compile time template stuff), and it seems to compile down into the same operation when ... | Summary: don't use #pragma GCC optimize. Use -O3 on the command line instead, and you'll get the behavior you expect.
GCC's documentation on #pragma GCC optimize says:
Each function that is defined after this point is treated as if it had been declared with one optimize(string) attribute for each string argument.
And... |
67,640,514 | 67,648,643 | #include <Python.h> CMake project Visual Studio 2019 windows 10 | I am having some trouble building a simple C++ project in Windows.
What I want to do:
Run some simple code in C++
Print a graph using the matplotlibcpp library.
I installed the matplotlibcpp library by using vcpkg.
I have a problem with the matplotlibcpp.h header including Python.h.
I obtain this error:
Error code 10... | Python.h is a header of a library that responsible for embeding Python code into CPP. You probably don't have the library itself installed thus the error. You probably can do so using vcpkg. If you do have it and still suffer experience the issue then the text bellow should give you an idea of how things work. Unfortun... |
67,641,124 | 68,626,734 | GCC 11: How to tell CMake I don't want the default C++ GNU extensions? | So, back in GCC 10.2 (which used C++14 as the default), I could use this to tell CMake I wanted -std=gnu++17:
target_compile_features(mytarget PRIVATE cxx_std_17)
set_target_properties(mytarget PROPERTIES
CXX_STANDARD_REQUIRED ON
)
...which I actually didn't want, so I used CXX_EXTENSIONS OFF to force -std=c++17:
... | The answer to this question is that it is a bug in CMake 3.21 (but technically not 3.20, which is older than the compiler in question) that will be fixed in 3.22, most likely by the following merge request: https://gitlab.kitware.com/cmake/cmake/-/merge_requests/6177
|
67,641,774 | 67,642,985 | Tesseract OCR (C++) Cannot Evaluate Output String | I am attempting to extract output string from an OpenCV Matrix window and evaluate it, but it seems to return something similar to "someString\n" rather "someString". This renders it difficult to compare knowing there are (x) amounts of white spaces.
I tried:
creating a char array that omits the white spaces (I am awar... | As for why it's returning a string and a line break, I cannot answer that. But I can provide you an alternative system to what you are trying to accomplish. Remove your first for loop in the analyseAction function and in your if statement for "long" pass in... if(charArr[0] == 'l') {//do stuff} This does have a limit i... |
67,641,796 | 67,641,859 | Template that returns a type | My goal is to decide a type passed to a template class at compile time.
Here's some pseudocode:
// Definition
template<size_t BitCount>
get_type<BitCount> {
if (BitCount <= 8) return uint8_t;
if (BitCount <= 16) return uint16_t;
if (BitCount <= 32) return uint32_t;
if (BitCount <= 64) return uint64_t;
... | #include <type_traits>
#include <cstdint>
template <auto bitCount>
using UInteger =
std::conditional_t<bitCount <= 8, std::uint8_t,
std::conditional_t<bitCount <= 16, std::uint16_t,
std::conditional_t<bitCount <= 32, std::uint32_t,
std::conditional_t<bitCount <= 64, std::uint64_t,
void>... |
67,641,949 | 67,641,979 | ERROR: Invalid conversion from ‘const char*’ to ‘char*’ debugging homework problem | I'm new to C++ and am having a hard time debugging this. Any idea why I am getting this error? The upper function is supposed to take in a pointer to a C-string as an argument, iterate through each character in the string and convert it to uppercase. Also, how can I get my function to return the string in uppercase?
#i... |
Make the argument const char* because the function doesn't modify the string.
Apply toupper() to what should be printed. (toupper() returns int, so the result should be casted to char to have it be printed as characters)
Add a semicolon after return "Done".
#include <iostream>
#include <string>
#include <string.h>
u... |
67,641,957 | 67,642,045 | undefined behavior for int i = f1() * f2() | I am confused as to why would this result in an undefined behavior. Let me copy and paste the explanation from the textbook first and then show my own code and program which runs perfectly.
Precedence specifies how the operands are grouped. It says nothing
about the order in which the operands are evaluated. In most c... | You're getting it wrong. The author means IF the order matters, it's unspecified. In your case, the order of evaluation doesn't matter. In fact, the function might as well be constexpr. But if you had something like this:
int i = 0;
int f1() { return (i++) * 3; }
int f2() { return (i++) * 4; }
int main() {
int a ... |
67,642,516 | 67,642,813 | Range check error in C++Builder (RAD Studio) | I've been getting "Range check error"s while working with string arrays. To my understanding, this means I am using indexes that don't exist in my array.
My class and functions in my header file:
AnsiString toBin(int n) {
AnsiString zero = "0";
int len;
AnsiString result;
while (n != 0) {
result... | Unlike standard C++ strings and arrays, which are 0-indexed, AnsiString is 1-indexed. Its valid character indexes are 1 <= N <= Length, not 0 <= N < Length as your for loops are written for.
Also, in XOR(), return; should not compile, since XOR() is declared to return an AnsiString. You need to either return an actual... |
67,642,553 | 67,642,605 | How to convert an std::string_view to std::string? | An std::string_view is kind of a replacement for char* in C. It's a string that is not copied from place to place, just as char* is just a place in memory that is referenced from time to time.
However, sometimes we need to transform it in a string for functions that accept a string.
How do I do that?
| std::string has constructors that will accept a std::string_view as input, eg:
std::string_view sv{...};
std::string s1{sv};
std::string s2{sv, index, length};
Alternatively, you can use the std::string constructor that accepts a char* and length as input, eg:
std::string_view sv{...};
std::string s1{sv.data(), sv.siz... |
67,642,699 | 67,642,773 | segmentation fault in recursive binary searching | I want to binary search more than once using the same function but it's showing segmentation fault. For one input its giving correct answer but when I am giving multiple input for binary search(i.e, q>1 acc. to my code) then its showing segmentation fault.
#include <iostream>
#include <bits/stdc++.h>
using namespace st... |
The condtion r>=1 should be r-l+1>=1 to check if there are some element in the range.
The initialization int mid=(r-1)/2+l; should be int mid=(r-l)/2+l; to correctly calculate the middle element.
Variable-Length Array int x[n]; is not in the standard C++. You should use heap allication int *x = new int[n]; instead. Af... |
67,643,146 | 67,647,669 | How to convert a Unix epoch time to a Pascal TDateTime(double) in C++ | Following on from this Original post I need to do the conversion in the reverse direction (Unix Time to TDateTime).
@Howard Hinnant did a very elegant example using his date.h library but due to a compilation issue, I decided not to use it. His effort is appreciated though.
Could someone provide me with an example base... | This direction is easier than the other one. Here is a way:
#include <stdio.h>
double UnixToDateTime(__int64 epoch)
{
int days = epoch / (24*3600);
int secs = epoch % (24*3600);
return 25569 + days + ((double)secs)/(24*3600);
}
int main()
{
printf("%.12f", UnixToDateTime(1060041720));
}
Output:
37838... |
67,644,333 | 67,644,374 | when I trying to implement the counting sort I got this error " the problem caused the program to stop working correctly Windows | when I trying to implement the counting sort I got this error " the problem caused the program to stop working correctly Windows will close the program and notify you if a solution is available "
void CountingSort(int *A,int size) {
int SizeC = Max(A, size);
int* B = new int[size];
int* C = new int... |
i < SizeC and i <SizeC should be i <= SizeC. Otherwise, the elements with value SizeC won't be treated properly.
C[i] += C[i - 1]; with i = 0 will result in out-of-range read of C[-1]. The initialization of corresponding for loop should be int i = 1, not int i = 0.
The decrementing C[A[j]] --; should happen before B[C... |
67,644,471 | 67,644,519 | Thread 1: EXC_BAD_ACCESS (code=1) error c++ project | I'm new to programming. So I don't know how to properly use the debugging tools. Xcode tells me that " Thread 1: EXC_BAD_ACCESS (code=1, address=0xffefbf3804)". I would really appreciate it if you could help me figure this out and fix the bug. The program must read the file .bmp, then I want to count the pixel brightne... | array_bmp[i][j] will be out-of-range because its column has only width elements while j will go around width*3. It should be array_bmp[i][j/3].
|
67,644,475 | 67,644,610 | Specialize template separately for data member and member functions | I would like to specialize a template to do one thing on pointers to data members and another thing on pointers to member functions. This used to work up until gcc 11, with member functions acting as more specific. It still works with clang 11, but seems to have broken with gcc.
Here is a minimal non-working example:... | I'm not sure, but I suspect this is a GCC bug. As a workaround, you can modify your code a bit by writing the signature of F in the argument-list of the specializations instead of the parameter-list, and deducing a type instead of a non-type
template<typename F> struct which;
template<typename K, typename V>
struct wh... |
67,644,736 | 67,652,637 | LLDB is not launching a Clang++ compiled program | I am tying to launch a debugging of clang code via lldb. I'm using a WSL Ubuntu 20.04 LTS. I installed a clang and lldb via sudo apt-get install clang and sudo apt-get install lldb accordingly.
The test code (mytest.cpp) is the following:
#include <iostream>
int main()
{
std::cout << "TEST" << std::endl;
return 0;... | I found out that the problem was is WSL 1. I updated my WSL to WSL 2 and this all works.
|
67,644,893 | 67,646,175 | QTabView hide tab content but not tabbar | I have 2 QTabWidgets in a window that contain QWidgets and a additional button intended to collapse the tab content which controls visibility. Either both are visible or one is hidden.
When I set the widget visibility using the code below, the widgets disappear, but the tab widget doesn't resize.
for(int i = 0; i < tab... | Here are a couple of options, one of which is similar to hiding tabs in a QTabWidget.
1. Replace the tabs with dummy widgets.
You still want the tabs to show, so swap them out with an empty widget so the calculated height of the contents of the QTabWidget is 0.
2. Hide the contents of the tab's widget rather than the w... |
67,645,846 | 67,645,860 | Aren't pointers supposed to point to nullptr when an array ends? | Why does this code not work?, I used the function from "A Tour of C++" and it tells me that pointers point to nullptr when an array ends briefly explained. I tried to implement it and it doesn't show anything. Thanks in advance.
#include <iostream>
int count_x(char* p, char x)
{
int count = 0;
while (p)
{... | No, pointer at the end of an array are not null. You probably want:
while (*p)
which is the same as
while (*p != '\0')
and
while (*p != 0)
which are testing for the null character.
|
67,645,957 | 67,646,029 | What's the difference between these two given examples | I'm a beginner in C++ and programming itself actually. I just want to ask, What's the difference between these 2 examples. What is the difference between "len = strlen(str1)-1" and "i = strlen(str1)-1"
Top part of the code will be like this:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
... | Both examples are same except first uses an extra variable len.
This code is actually reversing the string. If str1 contains "123" then str2 will contain "321".
Function strlen(str1) returns the length of str1 but in C++ index of Arrays start from 0 that is why the last element index will be one less than length, hence... |
67,646,331 | 67,646,359 | Rational numbers in an array c++ | I want to enter fractions to an array and don't know which data type should i make this array with to get back the numbers when needed as fractions in c++
Float numbers [5]={7/6,1/6,5/66,1/42,1/30,4389/698} ; cout << numbers[3] ;
The output will be 0 and it should be 0.238 so what should I do to make it 0.238 ?
| Could you please share your environemnt? OS/Compile type/version?
In my environment,
float numbers [6]={5.5,4.7,2.8,1.6,9.3,8.2} ; std::cout << numbers[3] << std::endl;
the output is 1.6. and it should be 1.6.
BTW, there are 6 items in this array, so the size should be 6 but not 5.
|
67,646,362 | 67,647,852 | Reuse variable after move | Is it okay to do the following? The following code is using the vector v again in the loop (next iteration) after moving it.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void test(vector<int>&& v) {
cout << v.size() << endl;
v.push_back(5);
}
void test2(vector<int>& v) {
f... | Your code is correct, but the intention that you are communicating is wrong.
If someone sees the declaration of function test he will think that when calling the function he is giving away the ownership of the variable that he is passing, because the variable will be moved.
In general, after a call to std::move(v) you ... |
67,646,730 | 67,646,881 | Path string from std::vector` | I have a vector of char which looks something like
C:/Users/person/Desktop/Albedo.pngC:/Users/person/Desktop/Metallic.pngC:/Users/person/Desktop/Noice.pngC:/Users/person/Desktop/AO.png
How do I split the vector to individual paths?
That is, I want to have
std::string path1; // = C:/Users/person/Desktop/Albedo.png;
std... | For example a straightforward approach provided that each path in the vector has the extension .png can look for example the following way as it is shown in the demonstrative program below.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cstring>
int main()
{... |
67,646,758 | 67,648,104 | C++ memcpy/strcpy of char pointer to class member char pointer | i have a custom class, let's call it "Student" and a main method. I'm instanciating the class, and just want to output the content of the class.
My programm crashes with a: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Actual Code
Student.h
#ifndef PROG2_STUDENT_H
#define PROG2_STUDENT_H
#inc... | std::strcpy does not allocate memory. So your program is copying input to a "garbage" address that is occurred in the memory area where your Student object is placed. And as result no surprise that you are getting segment violation as result. There are two solutions:
a "C-style" way - allocate memory manually (i.e. li... |
67,647,013 | 67,647,086 | Why does this substitution failure create an error? | In a template specialization I have a template argument with an enable_if with parameter that results in the enable_if not having a 'type' member, and so that template specialization should fail, but not create an error:
#include <type_traits>
template <typename value_t_arg, typename T = void>
struct underlyingtype
{... | Your code is ill-formed (no diagnostic required) because the condition is always false regardless of the template argument, meaning the specialization would be ill-formed for every possible template argument.
[temp.res.general]/6.1
The program is ill-formed, no diagnostic required, if:
— no valid specialization can be... |
67,647,108 | 67,647,342 | How to replace a char in string with another char fast(I think test didn't want common way) | I was asked this question in tech test.
They asked how to change ' ' to '_' in string.
I think they didn't want common answer. like this (I can assure this)
void replaceChar(char originalStr[], size_t strLength, char originalChar, char newChar
{
for(size_t i = 0 ; i < strLength ; i++)
{
if(originalStr[... | Do not try to optimize a code when you do not know what is the bottleneck of the code. Try to write a clear readable code.
This function declaration and definition
void replaceChar(char originalStr[], size_t strLength, char originalChar, char newChar
{
for(size_t i = 0 ; i < strLength ; i++)
{
if(origi... |
67,647,154 | 67,647,300 | Why can't I bind an lvalue-reference to an rvalue while a concept can? | #include <utility>
template<typename T>
concept IsWritable = requires(T& obj)
{
obj = 0;
};
template<typename T>
void f(T&)
{}
int main()
{
static_assert(IsWritable<int&&>); // ok
int n = 0;
f(std::move(n)); // error
}
GCC error message:
error: cannot bind non-const lvalue reference of type 'in... | Given
template<typename T>
void f(T&)
{}
the line
f(std::move(n)); // error
must error, because you're trying to pass an rvalue argument, std::move(n), to a lvalue reference parameter, T&.
As regards the concept, notice that there's no argument-parameter pair on the value level. And it's on the value level that t... |
67,647,162 | 67,647,195 | Why can't I get compilation error of custom concept supplied with initializer list? | Suppose I have 3 concepts:
ostreamable
istreamable
iostreamable
Where the definitions:
template <typename T>
concept ostreamable = requires (std::ostream& os, T arg) {
{os << arg} -> std::convertible_to<std::ostream&>;
};
template <typename T>
concept istreamable = requires (std::istream& is, T& arg) {
{is >>... | This appears to be a GCC bug.
Clang & MSVC reject your code.
|
67,647,298 | 67,647,512 | Absolute difference of sum of two diagonals of a 2d array in c++ | I want to obtain the absolute difference of the sum of left and right diagonal of the given 2d array.
I have written the following function-
int diagonalDifference(vector<vector<int>> arr) {
int n=arr.size();
int summ1=0,summ2=0,result=0;
for(int i=0;i<n;i++)
{ for(int j=0;j<n;j++)
{
if(i... | Here is a solution in O(n) complexity. reference
for (int i = 0; i < n; i++)
{
summ1 += arr[i][i];
summ2 += arr[i][n-i-1];
}
|
67,647,675 | 67,647,874 | Why does this substitution failure create an error, again? | I asked a question just before about why std::enable_if<false> cannot be used in SFINAE contexts, as in:
template <typename T, typename DEFAULTVOID = void>
struct TemplatedStruct {};
template <typename T>
struct TemplatedStruct<T, std::enable_if_t<false>> {}; // enable_if expression
// isn't dependent on template type... |
// Failed to specialize alias template
For one, there's no alias template in your code.¹ You're just delcaring bIsIntegralType to be exactly the same thing as std::is_integral_v<value_t_arg>, which is fixed (to false or true) as soon as the instantiation of underlyingtype takes place.
Therefore, the two specializatio... |
67,647,775 | 67,650,184 | Read CSV from std::vector<unsigned char> using Apache Arrow | I am trying to read a csv input format using Apache arrow. The example here mentions that the input should be an InputStream, however in my case I just have an std::vector of unsigned chars. Is it possible to parse this using apache arrow? I have checked the I/O interface to see if there is an "in-memory" data structur... | The I/O interface docs list BufferReader which works as an in-memory input stream. While not listed in the docs, it can be constructed from a pointer and a size which should let you use your vector<char>.
|
67,647,796 | 67,647,961 | Problems trying to delete a BST in C++ | I want to delete all the nodes in a binary search tree.
Here's the code that inserts nodesAmount nodes in the tree:
void testFindInsert(int nodesAmount) {
int value;
BSTNode* n = NULL;
BSTNode* root = NULL;
for (int i = 0; i < nodesAmount; i++) {
value = rand() % INT_MAX + 1;
n = n... | The problem appears to be here:
n = new BSTNode(value, "");
if (!findNode(root, value))
root = (BSTNode*)insertNode(root, n, BST);
If a node with value value already exists then memory is being wasted by allocating it to n since that node n is not inserted.
So allocate memory for node once sure that the node with ... |
67,647,876 | 67,647,937 | How can I use a recursive function from inside a struct if I want to use a field from that struct as a parameter | I have an AVL tree (I will not post all of the code because it wouldn't make sense), and I want to use a recursive function to delete it. The code looks something like this:
template <typename T>
struct AVL
{
Nod<T>* root;
....
void clear();
....
};
template<typename T>
inline void AVL<T>::clear()
{
... | Create another private function that takes parameters:
template<typename T>
void AVL<T>::clear_helper(Node<T>* node)
{
clear_helper(node->left);
clear_helper(node->right);
....
}
template<typename T>
inline void AVL<T>::clear()
{
....
if (root == nullptr)
{
return;
}
clea... |
67,648,026 | 67,656,671 | C++ in-place class instantiation | Take a lot at this (working) code
class MyClass {
public:
double data[6];
double func() const {
return data[1] + 2*data[3];
}
};
double takeMyClassReference(const MyClass &obj) {
return obj.func();
}
void construct(const double y[]) {
const MyClass *obj = reinterpret_cast<const MyClass *>(y);
... | If you're willing to move from MyClass owning the data, to MyClass not owning the data.
class MyClass {
public:
double *data;
double func() const {
return data[1] + 2*data[3];
}
};
void construct(double y[]) {
MyClass obj;
obj.data = y;
double val = takeMyClassReference(obj);
// do something... |
67,648,146 | 67,648,435 | How unsafe is it to use std::prev with string_iterator.begin()? | i have this piece of code. This function doesn't copy adjacent duplicates chars.It keeps only one of them. To do shorter, i've decided to use std::prev with iterator.begin(). I know that it's a (very) bad practice, i come from C, but in C++ is somewhat different. The undefined behavior is almost non existent. Tell me g... | std::prev effectively does it - 1 in your case. However, it is undefined behavior to decrement a begin iterator.
Bidirectional iterator:
The begin iterator is not decrementable and the behavior is undefined if --container.begin() is evaluated
This means, that your very first loop iteration is already UB.
Note that th... |
67,648,151 | 67,648,176 | How do I select an entire row in a CListCtrlEx | What should be done in order to automatically select one of the rows in a CListCtrlEx after it has been filled with data.
The purpose is to select a default row when the CListCtrlEx is displayed. For example, if the data shown is a list of cities, to show one of the cities (could be, the previously selected one), selec... | Assuming m_MyList is part of a dialog, we add the following lines to OnInitDialog() and we want to select the first row:
m_MyList.SendMessage(LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
m_MyList.SetItemState(0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
m_MyList.SetFocus... |
67,648,239 | 67,648,416 | Iterators in Method call / Functional Equivalence / Best Practise | Quick question about how something is evaluated by the compiler. In the below code I'm wondering if what I've written is a good idea, or whether I should be more explicit.
constexpr auto Checksum = [](const std::vector<uint8_t>& values) -> std::array<uint8_t, 6> {
std::vector<uint8_t> data{ 0x03, 0x03, 0x00, 0x17, 0x... | constexpr auto Checksum = [](const std::vector<uint8_t>& values) -> std::array<uint8_t, 6>
{
//...
std::array<uint8_t, 6> ret;
//...
return ret;
}
//...
data.insert(data.end(), Checksum(data).begin(), Checksum(data).end());
The data.insert invokes undefined behavior, due to Checksum(data).begin() and ... |
67,648,316 | 67,648,422 | Windows CPP InjectSyntheticPointerInput | I'm trying to make a pen simulator using the win32 (Winuser.h) InjectSyntheticPointerInput API to allow me to simulate Pen Pressure and other sensors.
But when I try to Inject the input, it gives me an error code (87: The parameter is incorrect)... My code so far:
#include <iostream>;
#include <Windows.h>;
#include <e... | Following https://github.com/gsbischoff/usb-pen-injection/blob/master/PenClient.c
lines 126 and 127
// These bastards apparently must be zero
PointerInfo.penInfo.pointerInfo.dwTime = 0;
PointerInfo.penInfo.pointerInfo.PerformanceCount = 0;
|
67,648,591 | 67,694,193 | Ctypes: Extended Struct/Pointer (Inheritance) | I would like to send extended Struct/Pointer(In the example below PY_LayerExtended) from Python to C++ but I've got an error.
My C++ code supposed to be like this:
typedef struct PY_LayerBase {
} PY_LayerBase;
typedef struct PY_LayerExtended : PY_LayerBase {
} PY_LayerExtended;
typedef struct PY_Layer {
PY_Laye... | ctypes doesn't understand C++ inheritance, even though you can declare the ctypes Structures similarly using Python inheritance.
You can solve the issue one of two ways. Below I've adjusted the C++ code to give some feedback that the structures are accessed properly:
test.cpp:
#ifdef _WIN32
# define API __declspec(d... |
67,648,693 | 67,648,739 | Safely initializing a std::array of bools | Given this array declaration and initialization:
std::array<bool, 20> invalid_params{};
Can I assume that all the elements in the array will always be initialized to false, or is it better to do it explicitly?
| It's guaranteed to be filled with false values.
std::array is an aggregate, hence it has no user-defined constructors, hence value-initializing it performs zero-initialization.
But if you remove {} (turning it into default-initialization), the elements will be uninitialized.
|
67,648,992 | 67,649,135 | Function signature, pass by value vs reference difference | I'm pretty confused with c++ since I was working with python all the time. So here is the example:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
void print(const boost::system::error_code& e,
boost::asio::steady_timer* t, int count) {
if (count < 5) {
... | boost::bind returns a function object. It stores a count as data member:
class Functor {
int copyCount;
};
when calling boost::bind this int is copied. Functor provides function call operator which invokes bound print function:
class Functor {
int copyCount;
public:
void operator()() {
print(..... |
67,649,120 | 67,649,322 | C/CPP - Converting floating point arithmetic to integer arithmetic | I have the following c++ functions (implementing Bresenham's line algorithm), seen in the book
Computer Graphics From Pixels to Programmable Graphics Hardware By
Alexey Boreskov, Evgeniy Shikin
One of the function uses floats, and due to their inefficiency the book has presented another function which uses integer ar... | The floating-point code does four things with d:
Initialize d to 2dy/dx−1, where dy and dx are yb−ya and xb−xa, respectively.
Evaluate whether d is greater than 0.
Add 2dy/dx+2 to d.
Add 2dy/dx to d.
In floating-point, the division by dx may produce a non-integer. To avoid this, we transform the operations by multipl... |
67,649,395 | 67,649,452 | Where in the C++11 standard is std::fmodf stated? | According to the cppref page, std::fmodf was added to cmath in C++11. How is this possible though, because wouldn't this mean that cmath would break compatability with math.h previous to C++11? I'm unable to find any references that say std::fmodf was added in C++11 and was wondering where this is stated.
Thank you
|
Where in the C++11 standard is std::fmodf stated?
It wasn't mentioned directly (although it probably should have been mentioned either in the list of functions, or explicitly omitted). The change that causes std::fmodf to exist is here (quote from draft N3337):
The following referenced documents are indispensable f... |
67,649,609 | 67,649,707 | Using preprocessing directive #define for long long | #include <iostream>
using namespace std;
#define ll long long
int main() {
int a = 5;
ll maxi = 1;
maxi = max(maxi, maxi * ll(a));
cout<<maxi<<endl;
return 0;
}
Why does this code throw an error? I don't understand what's wrong with #define ll long long .
| Remember that #define performs a textual substitution. You end up with this:
maxi = max(maxi, maxi * long long(a));
Which is invalid, since the type name for a functional cast can't, roughly speaking, contain spaces at the top level. So, unsigned int(a), long double(a), etc, are all invalid for this the same reason.
T... |
67,649,734 | 67,649,923 | Clarification on classes and scopes in this scenario | I'm currently working with the JUCE Framework to create an audio VST plugin to get to grips and learn, but just want to clarify some basic stuff relating to classes.
in my header file, i have a class EQPLUGProcessor and inside that class i call static juce::AudioProcessorValueTreeState::ParameterLayout createParameterL... | An enclosing namespace or a class does not have to be specified only inside the same namespace or a class:
class store {
class give_me {
// ...
};
static give_me something_cool();
};
Here, the declaration of something_cool() only needs to reference give_me, rather than store::give_me. This is becau... |
67,649,742 | 67,662,092 | Using scoped `polymorphic_allocator` with `boost::circular_buffer` fails | Background
I want to use boost::circular_buffer with a scoped C++17 std::pmr::polymorphic_allocator. I.e. I want the same allocator for an outer container to be used for inner containers.
Side note:
boost::circular_buffer is allocator-aware and the following assertion is true:
static_assert(std::uses_allocator_v<
... | The scoped allocator protocol requires that every constructor of the type has a corresponding allocator-extended version (either by appending an allocator parameter to the parameter list, or by prepending two parameters - allocator_arg_t followed by the allocator).
That includes the copy and move constructors, for whic... |
67,649,985 | 67,650,031 | Opengl disable color interpolation | How to disable color interpolation in GLFW and OpenGL 3.3 so that left half of the screen is pure white and the other half is completely black instead of having smooth transition through all shades of gray?
| The interpolation of a vertex shader output can be changed with a Interpolation qualifier. Using the flat qualifier an output will not be interpolated.
e.g.:
Vertex shader
flat out vec3 color;
Fragment shader
flat in vec3 color;
|
67,650,290 | 67,650,342 | Is There A Way To Initialize Structure Variables Prior To Defining Them? C++ | Under this is my current code, I have a structure called 'SCENE' which holds information I can use to change the value of some Win32 windows in a different file, The struct is somewhat simple:
struct SCENE
{
LPCWSTR SceneButtonOneText; // Text For Button One
SCENE* SceneButtonOneDestination; ... | Thanks 'Elijay', Didn't realise it was that easy,
extern SCENE Scene4;
Worked perfectly!
|
67,650,466 | 67,650,661 | More templates in C++? | My assignment is to make a multimap_util template class that helps the using of multimap.
My main problem is that the multimap_util class should also work with custom sorted multimaps.
I don't know how to make it work with two different templates.
So with 2 template args like this:
std::multimap<int, int> m;
multimap_u... | Take in count that std::multimap has ever 4 template parameter. But with a default for the third and the fourth template parameter.
It seems to me that the best you can do is emulate the std::multimap signature that is
template<
class Key,
class T,
class Compare = std::less<Key>,
class Allocator = std:... |
67,650,506 | 67,650,618 | What is the difference between "Type *Name" and Type* Name"? | I am new to c++ and i couldn't find anywhere what is the difference between when you put the '*' after the type or before the name. For example waht is the difference between the two:
int *p;
int* p;
| C compiler ignores the whitespace (except whitespace inside character constants and string literals).
It means that
int * p;
int*p;
int* p;
int *p;
int * p ;
mean exactly the same.
The white space is only important in macros for example:
#define a(x) ((x)+(... |
67,650,579 | 72,280,330 | How to check whether elements of a range should be moved? | There's a similar question: check if elements of a range can be moved?
I don't think the answer in it is a nice solution. Actually, it requires partial specialization for all containers.
I made an attempt, but I'm not sure whether checking operator*() is enough.
// RangeType
using IteratorType = std::iterator_t<Range... | I understand your point.
I do think that this is a real problem.
My answer is that the community has to agree exactly what it means to move nested objected (such as containers).
In any case this needs the cooperation of the container implementors.
And, in the case of standard containers, good specifications.
I am pessi... |
67,650,602 | 67,650,877 | Checking how many times a number has been entered | I'm trying to solve one of the questions on a task sheet I've received, to help me further in my understanding of C++ code from my class.
It kept showing 100000 in output after I entered the values. Where is that 1 coming from?
I know there are better ways to write code for this but I just want to know were is my probl... | I don't recommend that you use goto:, it creates spaghetti code. you can put an i-- in your error clause, like so:
int temp;
for (int i = 0; i < count; i++){
cout << i + 1 << "- enter a number between 1 and 5 for value : " << endl;
cin >> temp;
if (temp >= 1 && temp <=5)
A1[i] = temp;
else
... |
67,650,671 | 67,650,965 | How do I write trait for a vector correctly? | I'm trying to practice in traits and SFINAE and try to write something like is_container for a vector:
template <typename... Ts>
struct is_container :std::false_type {};
template <typename... Ts>
struct is_container< std::vector<Ts...> >:std::true_type {};
template < typename T>
inline constexpr auto is_container_v ... | T&& is a universal reference. In this case it is matched as T = std::vector<int>&. Your is_container_v<T> currently returns
is_container_v<decltype(test_vec1)> // true
is_container_v<std::vector<int>> // true
is_container_v<std::vector<int>&> // false
is_container_v<std::vector<int>&&> // false
In order to evalu... |
67,651,040 | 67,651,322 | how to print an n-dimensional array in c++ | I would like to write a function that can print different arrays. For instance:
#include<iostream>
using namespace std;
int main(){
int a[10];
int b[3][2];
for(int i = 0; i < 10; i++){
a[i] = i;
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 2; j++){
b[i][j] = i * 2 + j... | You could create a function template that unwraps the array recursively.
Example:
#include <iostream>
#include <type_traits>
// only enable the function for arrays
template<class T, std::enable_if_t<std::is_array_v<T>, int> = 0>
void print_arr(const T& x) {
for(auto& in : x) {
if constexpr (std::rank_v<T> ... |
67,651,241 | 67,651,330 | In-class initialization of std::unique_ptr to an incomplete type | I can't get the following code to compile with clang-cl in Visual Studio 2019. Though VC++ compiles it successfully. Also it works with custom deleter. Is it supposed to work as it is in the example? And if not, why?
example.h
#include <memory>
class A;
class B {
std::unique_ptr<A> a{ make_a() };
std::unique_... |
Is it supposed to work as it is in the example?
Yes, the example should work. Defining B::~B after A is complete is sufficient (and necessary).
Some standard rules:
[unique.ptr.general]
... The template parameter T of unique_ptr may be an incomplete type.
[unique.ptr.dltr.dflt]
The template parameter T of default... |
67,651,270 | 67,651,338 | How Can I transform a array of char's in a string in C++? | I have
char array[5] = {'t', 'e', 's', 't'}
I would be
string text = "test"
I can't use any function of string.h to make this proccess.
|
const int size = 4;
string text = "";
char array[size] = {'t', 'e', 's', 't'};
for (int i=0; i<size; i++)
{
text+=array[i];
}
|
67,651,282 | 67,651,538 | To Find factorial of large number(number of digits >20) | I wrote some c++ code to find the factorial of int n. As factorial can be a very large number, so I decided to store the number in a vector. But My Code is not working as expected. Some please point out the bug and guide me. I lowkey feel like I messed with pointers.
And Please suggest if there is a more optimal approa... | Fixed version:
#include <vector>
#include <iostream>
using namespace std;
//define the length of the array, should be the maximum number of digits in the factorial(n)
#define MAX 20
void multiply(int x, vector<int>& res, int* res_size) {
int carry = 0;
for (int i = 0; i < *res_size; i++) {
int prod = ... |
67,651,303 | 67,651,608 | Recursive lambda: pass by reference or universal reference? | When I need to implement a recursive lambda, usually I do it like this:
auto factorial = [](auto& self, int n) -> int {
return n == 0 ? 1 : n * self(self, n - 1);
};
and call it with factorial(factorial, n). However, I've seen people declaring the parameter self with type auto&& instead of auto&. What's the differ... |
What's the difference?
The lvalue reference to non-const of your example cannot bind to rvalues.
and call it with factorial(factorial, n)
If you don't ever intend pass an rvalue, then the difference is of no practical consequence.
|
67,651,353 | 67,653,222 | How to have multiple source dirs? | After doing some research, I was able to found the following makefile to compile every cpp file in my project and place every object files in the obj directory. However, it still doesn't work. I have two directories, one called src and another one called lib. I'm not able to make it work for both of these directories. ... | Please see below code which will help you to compile from src and lib directory all C++ files:
TARGET = app
CC = c++
CFLAGS = -std=c++2a -Wall -I.
LINKER = c++
LFLAGS = -Wall -I. -lm
# change these to proper directories where each file should be
# SRCDIR = src lib
# I created a separate variable for sr... |
67,651,710 | 67,655,456 | Unable to open webcam video on raspberry pi 4 | I am trying to open a webcam for video streaming on my raspberry pi 4 with OpenCV 4.
The VideoCapture constructor in OpenCV takes the index/address of the location of the device. Using 'lsusb' I get this:
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 004: ID 046d:08c5 Logitech, Inc. Quic... | Solved by installing v4l2-ctl: https://askubuntu.com/a/848390/918858
VideoCapture constructor also takes a const string&(VideoCapture (const String &filename)) which can reference /dev/video*. The v4l2-ctl package provides you with the /dev/ mapping.
|
67,651,802 | 67,652,002 | Splitting a string with no spaces in C++ | I have the a string which consists of key value pairs but no delimiter character:
A0X3Y21.0
All values may be floats. How can I split this string up into:
A = 0, X = 3, Y = 21.0
My current method was to use strtof() which works generally except for one annoying case where an 0 is before an X and so the above string i... | For parsing, normally I use std::stringstreams, defined in the header <sstream>. An example use here:
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::stringstream parser("A0X3Y21.0");
std::stringstream output;
char letter;
double value;
while (parser>>letter&&parser>>valu... |
67,651,841 | 67,652,130 | What is the most intuitive layout for a class that manages pointers to different types? | I have a class that manages a map of strings and pointers as such:
class DebugTab
{
public:
void pushItem(std::string&& name, std::unique_ptr<DebugItem> item);
private:
std::map<std::string, std::unique_ptr<DebugItem>> items_;
};
The pointers should be able to point to different types so to achieve this I made... | Well, technically you can skip allocating them at callsite...
template<class T>
struct DebugConcrete: DebugItem {
T &t;
std::string asSring() const override {
return std::to_string(t);
}
};
class DebugTab {
template<class T>
void pushItem(std::string name, T &item) {
items_.emplace(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.