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,604,606 | 67,623,279 | I can't run this code to print distance between two points. I am just a beginner | I wrote the code given below to print distance between two points but it throws a lot of errors. As much as I know, the errors lie in "void formula(distance o1, distance o2)"and main. But I couldn't find exact errors as I am just a beginner. Please guide me.
#include<iostream>
#include<math.h>
using namespace std;
cla... | I compiled your code using g++, and here are some of the errors I found:
Spelling
#inclulde <math.h>
Friend Function
you defined formula outside of class distance, but declared it as a friend function inside. The easiest way to fix this is to just define formula where you declared it, ie inside the class.
class distan... |
67,604,756 | 67,606,461 | What filter should be used to filter TLS 1.3 client hello? | Currently using (tcp[tcp[12]/16*4]=22 and tcp[tcp[12]/16*4+5]=1), where =22 represents handshake and =1 represents client hello for both TLS 1.2/1.3 packets.
Since the above filter gives traffic to both TLS 1.2 and 1.3, I am not really finding a way/technique to differentiate TLS 1.3 or TLS 1.2 client hello traffic.
| TLS 1.3 support is announced in the supported_versions TLS extension. There is no clear offset for this extension in the ClientHello, i.e. one would need to properly parse the ClientHello structure. This is not doable with pcap filter rules.
|
67,605,019 | 67,606,760 | How to convert a 3D position in world space to 2D position using DirectXMath | I want to take advantage of the SSE intrinsics (mostly for the speed advantage) that DirectXMath provides
How would i do it? this is the current code im using
DirectX::XMFLOAT4 clipCoordinates;
DirectX::XMFLOAT4X4 WorldMatrix4x4;
DirectX::XMStoreFloat4x4(&WorldMatrix4x4, WorldMatrix);
clipCoordinates.x = pos.x * W... | If by 2D position you mean screenspace coordinates:
First transform from local space to world space:
XMVECTOR world_pos = XMVector4Transform(pos, world_matrix);
Then transform from world space to camera space:
XMVECTOR view_pos = XMVector4Transform(world_pos, view_matrix);
Then transform from camera space to clip spa... |
67,605,182 | 67,605,393 | Thread 1: signal SIGABRT for C++ Input | I am trying to read input from a file that looks like this:
7
3
5
1
6
2
14
10
I am trying to save the first number in the integer N but I am getting and error when using stoi() and it gives me the error "Thread 1: signal SIGABRT":
libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi... | You did
string str = line; // a variable of string data type
N = std::stoi(str);
without reading data from the file to line.
Add
getline (myfile, line);
before
string str = line; // a variable of string data type
to read a line from the file.
Adding check to see if file opening and reading are successful will make y... |
67,605,352 | 67,627,638 | How to set a size of Fl_Text_Editor? | At this moment, I have a target to write a simple text editor using C++. Due to the fact that I need my textbox to be inside of my window, so when I change my window size, it has to change it size too. Here's my code:
int main(int argc, char **argv) {
{ window_main = new Fl_Double_Window(624, 644, "Text editor");
... | The call to size_range() makes a window resizable as a side-effect (it only tells FLTK what the size range of the window is), you would still need to call the resizable() method.
I've modified your example to get a working piece of code:
#include <FL/Fl.H>
#include <FL/Fl_Menu_Button.H>
#include <FL/Fl_Double_Window.H>... |
67,605,355 | 67,605,828 | Const vs Final in C++ | I was learning OOPS in C++ and I came across keywords const and final. Now I am having a doubt what is the difference between them.
| I suppose this question needs an answer, given the other answers present.
You cannot apply final to variables in C++, so the question "which one is better" can only be answered with "const, because only this can compile".
final specifier was introduced to C++11 and can be applied:
to classes, in this case class canno... |
67,606,563 | 67,606,757 | What is the difference between iterator_category and iterator_concept in C++20? | C++20 brings a more powerful iterator system, one of them is to introduce iterator_concept on the basis of iterator_category.
I found that the iterator_concept and iterator_category of many iterators in C++20 are inconsistent. Take the most famous iota_view as an example:
using R = decltype(views::iota(0));
static_asse... | There are differences between the C++17 (C++98) iterator model and the C++20 Ranges iterator model that are not backwards compatible. The two big ones are:
The C++98 model requires that forward iterators have a reference that is either value_type& or value_type const&.
The C++98 model does not allow for contiguous ite... |
67,606,765 | 67,606,961 | Im Facing a Problem With Destructor Called Twice in C++ | EDIT: I had to use unique_ptr or follow the rule-of-five I'm still learning about it so I used unique_ptr and it worked. But I have a question, the destructor now is being called twice and I think that is no problem as long as the block of memory that the pointer is pointing to is not being freed twice, Right??
I made ... | Your destructor calls delete[] m_Buffer. A pointer may never be deleted twice. If you do delete a pointer twice, then the behaviour of the program will be undefined. You must avoid ever doing that. To achieve avoiding that, you must make sure that no two instances of the class have the same pointer value in the member.... |
67,606,956 | 67,607,046 | Standard or idiomatic empty object in C++ | I often need to define an empty object in C++, which is typically a structure without any members or methods:
struct Dummy {};
Reincarnations of the same idea include classes like nill_t, null_t, Empty, None etc.
I was wondering if there is a standard library object that fits this description (empty class, used as tag... | The best practice is to do it this way:
struct Dummy { explicit Dummy() = default; };
Which you can then create an instance of:
inline constexpr Dummy dummy;
The advantage of this is that Dummy is not an aggregate (in C++20), which prevents this from compiling:
void f(Dummy);
f({}); // error
f(Dummy{}); // ok
f... |
67,607,010 | 67,607,440 | Remove negative values from linked list | I have a program that lets the user create a linked list. It can add elements in the front, middle and end, and print said list.
I need a function to remove any negative numbers in that list.
I tried the following, but it removes some positive numbers in the middle.
I've been stuck at this for like 3-4 hours trying dif... | That code is WAY over-complicated for a simple traverse+removal operation. Mainly because each time you find an element that you want to remove, you are having to re-traverse through the list again just to find the previous element whose next field needs to be updated. You don't need that extra traversal at all, just... |
67,607,403 | 67,618,374 | Changing project's dirs breaks precompiled file creation | I use MSVC2017 (with MSVC2013 toolchain, if it's matters).
So, I have created new solution with "static lib" project and a console app. At this step it works.
Now, I changed some project's paths for the lib project:
Output directory: $(SolutionDir)BuildDebug
Intermediate directory: $(OutDir)\Debug
I added following inc... | "Pre-compiled headers" are a build-speed optimization. If they're giving you problems, you can always turn off their use temporarily. When they're turned off, the .pch is no longer used, but the .h is still used.
I expect you'll still have the missing LONG, since it's not even in the .h
For your sanity, it might be use... |
67,607,447 | 67,610,096 | Can zlib remove padding without compressing the rest of the file? | I'm looking for a way to apply a specific compression strategy using zlib-1.2.5.
I need to force zlib to pack a file without actually compressing it. The only part I want to compress is 0 padding at the end of the file, so that the output file does not have it. The size of input files ranges from 1MB to 1GB, padding is... | No, there is not.
If all you want to do is strip the zeros at the end, then that is trivial. It's a few lines of code. You don't need zlib's 18,000 lines of code to do that.
If you also want to restore those zeros to the file at the other end ("decompressing it"), that is trivial as well. Just send a count of the zeros... |
67,607,600 | 67,608,638 | Spatial locality in CUDA loops | I was reading the Even Easier Introduction to CUDA, and I was thinking about examples like this:
__global__
void add(int n, float *x, float *y)
{
int index = threadIdx.x;
int stride = blockDim.x;
for (int i = index; i < n; i += stride)
y[i] = x[i] + y[i];
}
In which each thread strides through the array. I... | The reason a grid-stride loop is beneficial for memory access is that it promotes "coalesced" access to global memory. In a nutshell, coalesced access means that adjacent threads in the warp are accessing adjacent locations in memory, on any given read or write cycle/operation, considered warp-wide.
The grid-stride lo... |
67,608,049 | 67,608,086 | polymorphism between set and multiset in c++ | Is there a way using polymorphism to have a generic for set and multiset? as follows.
Note: but only for sets, (set, multiset)
template<typename T>
void foo(parent_set<T> &s) {
// do something
}
// main
set<int> s1 = {1, 2, 3, 4, 5};
foo(s1);
multiset<int> s2 = {1, 2, 2, 2, 2, 3};
foo(s2);
| Well, why don't you make the whole container your template parameter?
template <class SetType>
void foo( SetType& s)
{
using T = typename SetType :: value_type;
enter code here
....
}
The restriction for the parameter to only be a set or multiset, as is usually done with templates, is enforced by the usag... |
67,608,335 | 67,608,413 | How cast char symbol "+" directly to an operation + (addition) ? C++ | Here is the issue, I have a char symbol:
char a = '+'; //- * % whatever arithmetic symbol
I want so that I could use the value of a as an operation. I don't want to use a switch to check if a is '+', etc, and then write a lot of similar lines for each case. I need just to change the operation, depending on the value ... |
I want so that I could use the value of a as an operation.
Sorry, but that is simply not possible. Well, not the way you have written it, anyway (there probably are low-level ways to implement something like that using self-modifying code at runtime, but that is an advanced technique I won't get into).
I don't want... |
67,609,825 | 67,610,062 | Unable to hold QQmlContext in std::shared_ptr | I noticed some quite strange behavior when working with Qt 5.15/C++.
I was working on a small application when I wanted to set a context property for my root context.
My application is a QtQuick app which uses QQmlApplicationEngine instead of QQuickView (which was, for whatever reason, the default when creating a Qt Qu... | Qt clearly indicates when the developer must manage the memory of an object, if it does not indicate it then it must be assumed that Qt will eliminate it when necessary.
In this particular case the QQmlContext is created by QQmlApplicationEngine so it is the responsibility of that class to manage its memory. For exampl... |
67,609,832 | 67,609,915 | Unexpeced value upon accessing an SSBO float | I am trying to calculate a morph offset for a gpu driven animation.
To that effect I have the following function (and SSBOS):
layout(std140, binding = 7) buffer morph_buffer
{
vec4 morph_targets[];
};
layout(std140, binding = 8) buffer morph_weight_buffer
{
float morph_weights[];
};
vec3 GetMorphOffset()
{
... | Upon doing a little bit of asking around.
The issue is the SSBO is marked as std140, the correct std for a float array is std430.
For the vulkan GLSL dialect, an alternative is to use the scalar qualifier.
|
67,609,997 | 67,692,218 | How can I load struct fields from Matlab to C++? | So I have a struct called stf with multiple fields; each field is a vector. I tried using the Matio library to get reach for those variables, but all I get is one variable, namely the struct stf. As the stf struct has 4 fields, I get 4 double variables. But how do I access the fields themselves? I want to store each of... | Alright, I figured it out. I made a function that loads the struct fields and then stores them in a matrix from the Eigen library. t looks something like this:
MatrixXd load(string workspace_name, const char* variable_name, const char* field_name)
{
const char* filename = workspace_name.c_str();
mat_t* mat;
... |
67,610,171 | 67,610,261 | Getting area of a line circle intersection | I have a circle and I have two parallel lines which go through straight through it (always 2 intersections).
The radius of the circle is 500, meaning its area is 500 * 500 * pi.
Quick paint image of example above. The red area is the overlapping area, which I want to calculate. However I'm not sure how to, this is what... | Claculate the green area, subtract it from the area of the circle.
https://en.wikipedia.org/wiki/Circular_segment
|
67,610,435 | 67,610,976 | OpenSSL AES_CBC-256 decrypting without original text length in C++ | I have this code that I found on SO and it works. My problem is that encryption and decryption are in the same file. Naturally, I want to separate them into two functions. The problem is the decoder needs the original input length. Isn't it a security vulnerability? How can I decrpyt without knowing the original length... | First of all, AES encryption takes place 1-to-1 in blocks of 128 bits, so you already know the message size with a 16-byte accuracy by just looking at the ciphertext.
Then, for the last block you just need to determine where the message ends. The standard solution for that is to use padding (e.g. PKCS#7). Or just store... |
67,610,480 | 67,610,570 | Can you programmatically know the max blocks and threads per block in a GPU? | I am writing a CUDA program that will probably run on many different GPUs. I would like to know if CUDA provides some way of reading from code (either runtime or compile time) the capabilities of the current GPU, meaning the number of threads a single block can contain, and the maximum number of blocks, so I can tailor... | I guess cudaGetDeviceProperties seems to be what you are looking for.
|
67,611,037 | 67,611,512 | Code for counting frequency of element in array not working | I'm trying to find the frequency of elements in an array. I have found lots of programs on Google that can do just this, but I can't get them to count right for my array.
This is the code I use:
#include <iostrem>
#include <cmath>
const int nmax = 50;
int main() {
int afk[nmax], count;
const int N = 40;
... | You are counting the frequencies just fine (well, not as efficiently as you could be), but you are not displaying them correctly.
The afk[] array is storing each number's frequency at the same index as its first occurrence in the dn[] array.
In your final display loop, you are printing the loop counter i itself instead... |
67,611,498 | 67,611,642 | When are non-static C++ data members allocated? | I have a class which passes the address of one data member to the constructor of another:
class MemberA {
public:
MemberA(MemberB* ptr) : ptr_(ptr) {}
private:
MemberB* ptr_;
};
struct MemberB {
public:
MemberB(int x) : x_(x) {}
private:
int x_;
};
class Foo {
public:
Foo() : a(&b), b(1) {}
private... | The data members are allocated within the object itself. Most of this is not specified in the standard, but that's how most compilers do it:
-- FOO --------------------------------------------
| --MemberA--- --MemberB--- |
| | | | | other stuff follows |
| ------------ ------... |
67,611,502 | 67,611,845 | Erasing while traversing in C++ stl map giving runtime error | Following lines of C++ code gives runtime error but if erase operation mymap.erase(v) is removed it works:
map<int,int> mymap = {{1,0},{2,1},{9,2},{10,3},{11,4}};
for(auto it=mymap.rbegin();it!=mymap.rend();){
int v=it->first;
++it;
mymap.erase(v);
}
demo
Here iterator it is changed before deleting its val... | When you are calling erase(v), you are invalidating the base iterator that the next reverse_iterator (from ++it) is using. So you need to create a new reverse_iterator from the base iterator that precedes the erased value.
Also, rather than erasing the value that the reverse_iterator is referring to, you should erase ... |
67,611,936 | 67,612,075 | Derived template class can't find move constructor for base template class | I have a pretty large class which is reduced to a minimum failing example below:
#include <vector>
template <typename T> class Base {
public:
Base(std::vector<T> &&other) : map{other} {}
private:
const std::vector<T> map;
};
template <typename T> class Derived : public Base<T> {
public:
Derived(std::vector<T> ... |
since I am passing in other which is declared in Derived's constructor argument to be an rvalue (std::vector && other)
Actually, in the scope of Derived(std::vector<T> &&other), other is an lvalue, with a type that is rvalue reference. This is a common point of confusion. Behold the mighty cppreference:
The followin... |
67,612,095 | 67,616,402 | Build error: make: Nothing to be done for 'compile' | I need to add my own package to the openwrt image. On the wiki of the project I found this article.
I tried to follow the instructions for it, but in the end I did not manage to add my own package to the source code tree (the build ignored its presence).
Because of this, I tried to find some other way. And it turned ou... | In order to copy files and directories you can use below step:
# copy all files and directories using **cp -r -f **
define Build/Prepare
echo $PKG_NAME
mkdir -p $(PKG_BUILD_DIR)
cp -r -f $(SOURCE_DIR)/* $(PKG_BUILD_DIR)
$(Build/Patch)
endef
In order to execute the local makefile use below step:
# Execu... |
67,612,159 | 67,612,931 | How can I solve this "cannot remove *.log" error in a GoLang backend project? | I have a GoLang backend project. I have an issue when building this project.
# pkg-config --cflags -- vips vips vips vips
pkg-config: exec: "pkg-config": executable file not found in %PATH%
I am working on Windows 10.
How can I solve this issue?
| I've found the solution from this link.
How to install pkg config in windows?
You have to install G++ and other relevant libraries on your computer and register the system environment variable.
|
67,612,345 | 67,613,199 | How to change class member value in vector | #include <iostream>
#include <string>
using namespace std;
class Owner{
protected:
string ownerName;
int balance;
int numPetsCheckin;
string pet[100];
public:
Owner();
Owner(const string& ownerName, int balance);
string getOwnerName(){return ownerName;}... | Q: why owner[0].getNumPetsCheckin() and A.getNumPetsCheckin() are different?
They are different objects, after the satement owner[people] = A;, the object A is copied to owner[people]. You can verify it with print the address:
std::cout << &owner[people] << ' ' << &A << std::endl;
Got output on my machine, they ar... |
67,612,673 | 67,612,825 | How to create MIDI file using hexadecimal information in C++ | I'm trying to create a MIDI file from scratch in C++.
I'm using this website as a resource: https://intuitive-theory.com/midi-from-scratch/ .
Since MIDI requires it to be encoded in Hex, i've written a program that creates a MIDI file and pastes HEX code in it like this:
#include <cstdlib>
#include <iostream>
#include ... | char buffer[] = {static_cast<char>(0x4D,0x54,0x68,0x64,0x00,0x00,0x00,0x06,0x00,0x01,0x00,0x01,0x00,0x80,0x4D,0x54,0x72,0x6B,0x00,0x00,0x00,0x16,0x80,0x00,0x90,0x3C,0x60,0x81,0x00,0x3E,0x60,0x81,0x00,0x40,0x60,0x81,0x00,0xB0,0x7B,0x00,0x00,0xFF,0x2F,0x00)};
does not cast all of the comma separated values to char. Inst... |
67,612,767 | 67,612,790 | How to fix error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'void') while using strings and stack | I am a beginer learning Data Structures and Algorithms.
I was trying this :
#include<iostream>
#include<ostream>
#include<stack>
#include<string>
using namespace std;
int main (){
string original ;
string a = "";
std::stack<string> library;
cin >> original;
for(int i=1; i < original.size() -... | Contrary to your intuition, std::stack::pop() doesn't return anything (void). https://en.cppreference.com/w/cpp/container/stack/pop and void cannot be printed.
You probably want this:
for(int j=0; j < library.size(); j++){
cout << library.top() ;
library.pop();
}
|
67,612,811 | 67,612,907 | std::forward acting differently | I'm currently learning perfect forwarding in c++ and I came across something that confused me. Pretty sure it's something stupid. When I used std::forward on a lvalue, it used the rvalue function. This is a pretty bad explanation so I'm just gonna show the code.
#include <iostream>
void check(int&& other) {
std::c... | "Perfect forwarding" is used in templates, i.e.:
template<typename T>
void func(T && arg)
{
func2(std::forward<T>(arg));
}
Outside of template context the end result drastically changes. All that std::forward does is return static_cast<T &&>, so your call function becomes nothing more than:
void call(int& other) {... |
67,612,822 | 67,612,934 | how to read this declaration int (*(*f2)(int n))[3]; | I got this declaration from https://en.cppreference.com/w/cpp/language/scope, but don't know how to parse this declaration even there is a comment below.
my questions is
how to parse the declaration statement (I see it as a function pointer to a function protocol like "int[3] foo(int n)" or "int foo(int n)[3] --- they ... | It's a pointer to a function taking an int and returning a pointer to an int array of size three.
All the comment is saying is that there are two n identifiers in play here. The [n] (in array declarator) is using the const int 3, not the parameter to the function (which is in the function declarator).
Starting in the m... |
67,612,941 | 67,613,840 | When two libraries have variable types with the same name, how to define the variable type correctly? | I need to use the armadillo library and opencv library, but I find that both have mat type variables. How can I use them correctly when I use them?
| opencv places type definitions in a namespace named cv, and armadillo places type definitions in namespace arma. The reason that libraries use namespaces is to provide a means of avoiding name clashes that results from two libraries using the same name.
The simple approach is then to avoid ANY using directives (e.g.... |
67,613,022 | 67,613,768 | Initializing a 2D array with operator new | I am trying to declare a 2D array, where each element in the inner array has type uint64_t*. I want to do this in a single line using new, which should be possible in C++11 or later. I tried this:
uint64_t ***db = new uint64_t*[2][64];
However, this is incorrect:
cannot initialize a variable of type 'uint64_t ***' (ak... | If you want a pointer to an array on heap, you use a pointer to the first element. This means it's the same type as if you would allocate a single element:
uint64_t* p1 = new uint64_t;
uint64_t* p2 = new uint64_t[2];
You should one the second line only use p and p+1, because p+2 is in this example out of range. This g... |
67,613,142 | 67,613,250 | turn off c++ loop optimization | I am wondering how to turn off optimization for the following loop. I have searched and tried some flag but not working. Thanks.
#include <iostream>
int fun(int i) {return ++i;};
int main ()
{
int res = 0;
for (long i = 0; i < 10000; i++)
{
res += fun(i);
}
std::cout << res;
}
-O1 will r... | You can use something like Google Benchmark's DoNotOptimize() function. This function uses an empty asm block to lie to the compiler that the given variable was read from. Adapted from here:
template <class Tp>
[[gnu::always_inline]] inline void DoNotOptimize(Tp const& value) {
asm volatile("" : : "r,m"(value) : "mem... |
67,613,450 | 67,614,132 | Is there a way to find what build command visual studio code is using internally? | I am compiling a program with visual studio and I need to figure out an equivalent cmd command so I can use Emscripten. I have tried to figure it out by pointing to the same libraries but it is not working. Is there a way to find what build command visual studio is using internally?
Output messages:
cl /c /IC:\Users\Dr... | In project properties for C/C++ / General. Locate "Suppress Startup Banner" and force it to No. (Equivalent to not specifying /nologo as a command line param)
When the project builds, you'll see the command line arguments passed to cl.exe in the output window.
You can achive the same effect with the linker showing th... |
67,613,579 | 67,613,853 | Is it allowed to include a precompiled header into a header file? | I know what precompiled headers are, but I found nothing about pch-s being included in header files. Can you do that? I tried it and it worked. Does it have some drawbacks?
| You can do that. Just check to see if your compile times actually go down.
This question is similar.
stdafx.h to header files
|
67,613,670 | 67,813,358 | How to create an array of pointers in c++ | So I have a base class called items, 2 inherited classes from items called consumable and equipment, and 2 more inherited classes from each of those. Each have the function toString(), with it building up as you go down the inherited list. But here is my issu. I need to put 4 objects inherited from consumable and equip... | As mentioned in comments above; the array should be an Item* type. Since question is posted as C++14, using <array> allows you to access the values by reference; instead of manually indexing. This is more scalable as the for loop doesn't have to be updated in the future. It also eliminates possible bugs or errors when ... |
67,613,878 | 67,614,008 | Why pointer to arr[i] cannot be assigned while pointer to arr+i can be assigned directly? | #include<stdio.h>
int main()
{
int n;
printf("Enter number of elements you want in array:");
scanf("%d",&n);
int arr[10],*a;
//taking input from user
for(int i=0;i<n;i++)
{
printf("Enter element %d: ",i);
scanf("%d",arr+i);
}
//stroing values in array and s... | A pointer points to an address in memory.
If you add an integer, you move the pointer:
int v = 10;
int *p = &v;
p = p + 3 // 3 addresses further. Which is currently nothing.
If you use the asterisk, you get the value at the particular address.
int v = 10;
int *p = &v;
*p == 10; // true
Using brackets is like both pla... |
67,614,091 | 67,615,720 | Clarification needed on LookAt matrix calculation in DX9 | I am going trough these 2 methods to calculate the lookat matrix
D3DXMatrixLookAtLH
zaxis = normal(At - Eye)
xaxis = normal(cross(Up, zaxis))
yaxis = cross(zaxis, xaxis)
xaxis.x yaxis.x zaxis.x 0
xaxis.y yaxis.y zaxis.y 0
xaxis.z yaxis.z za... | TL;DR: The Microsoft Doc page for D3DXMatrixLookAtRH is wrong. I've filed a PR to fix it.
In the actual implementation of D3DXMath, it's clear that in both cases the Translation should be -dot(xaxis, eye) -dot(yaxis, eye) -dot(zaxis, eye) for both LH & RH.
The only difference is the zaxis computation.
D3DXMATRIX* WIN... |
67,615,213 | 67,616,410 | Externing a C++ class to avoid including its header file | I have created a static library for the following class, libtgbotengine.a and externed the class to be used in a different project.
tgbotengine.h
#include <tgbot/tgbot.h>
// Other headers
// ...
class TgBotEngine{
public:
// Class constructors and functions
// ...
void start();
private:
TgBot::Bot ... | The upcoming modules will probably allow what you want to do. Unfortunately, they are still experimental...
The only portable way I know to fully hide the implementation details is to split your class between a public interface and a private implementation. This is common to Java developpers.
Here it would look like:
... |
67,615,330 | 67,615,606 | Why std::function is too slow is CPU can't utilize instruction reordering? | While i develop my project, I found std::function is really slow.
So I tried to know why it's really slow.
But I couldn't find obvious cause of that.
I think What Cpu can't utilize instruction reordering optimization and cpu pipeline because it doesn't know which function is called is cause of poor performance.
It make... | Code wrapped into std::function is always slower than inlining code directly into calling place. Especially if your code is very short, like 3-5 CPU instructions.
If your function's code is quite big, hundreds of instructions then there will be no difference whether to use std::function or some other mechanism of calli... |
67,615,476 | 67,615,619 | "using" keyword when defining member functions and non-member functions | Does the "using" keyword have different effects in the context of defining member and non-member functions? The example code below suggests to me that it might.
main.cpp
#include "baz.h"
int main()
{
foo::bar x;
x.baz();
foo::foo_non_member();
}
baz.h
namespace foo
{
class bar
... | For this part:
using namespace foo;
void bar::baz()
{
std::cout << "baz\n";
}
The using namespace foo; is used for the lookup of the bar:: part, and due to that the compiler is able to tie the definition of void bar::baz() to the declaration in the namespace foo.
And if you remove using namespace foo; it is not abl... |
67,615,611 | 67,615,727 | Alloc memory in constructor or init function? | I'm new to C++, I have a class hold some memory, the class looks like:
class MyClass
{
public:
MyClass (int s)
{
if (s <= 0) _size = 1;
else _size = s;
data = new int[_size]; // may throw exception
}
private:
int *data;
int _size;
};
To my knowledge, throw exception in c... |
To my knowledge, throw exception in constructor is unsafe, so I put the malloc to a init function.
No, it is not "unsafe". It's the way to fail a constructor. You may be thinking about destructors aborting or other issues with exception safety guarantees.
"Init" functions introduce a two phase approach to constructor... |
67,615,668 | 70,293,013 | Is pimpl idiom better than using always unique_ptr as member variables? | In my workplace we have this convention: almost every class (with very few exceptions) is implemented with unique_ptrs, raw pointers or references as member variables.
This is because of compilation times: in this way you just need a forward declaration for the class in your header file and you only need to include the... | After a while I have a broader understanding of the problem and finally I can answer to my own question.
It turned out that what I was saying was not completely correct.
In fact in the code below only Bp class is pImpl. If we change Ap to be pImpl aswell we obtain that, if we change Bp.h we need to recompile only Ap.cp... |
67,615,709 | 67,615,770 | Why copy method of std::string in C++ is showing weird behavior in this program? | #include<iostream>
using namespace std;
int main()
{
string str1 = "geeksforgeeks is for geeks";
string str2 = "geeksforgeeks is for geeks";
char ch1[100];
char ch2[100];
cout<<str1.size()<< endl << endl;
str1.copy(ch1,23,0);
str2.copy(ch2,24,0);
cout << ch1 << endl << endl... | It's because your char[]'s are uninitialized and you don't place a \0 at the end of the strings after the copy.
Another solution is to initialize the char[]'s at construction:
char ch1[100]{};
char ch2[100]{};
|
67,615,769 | 67,616,780 | Getting terminate called after throwing an instance of 'std::length_error' | I am getting this above error and I am unable to debug the cause for it. Can anyone help me with this (what's causing this error)?
Problem Statement: Finding Longest Common Prefix
Source: https://leetcode.com/problems/longest-common-prefix/
Code(Using Divide and Conquer):
#include <iostream>
#include <unordered_map>
#i... | You have two issues in your code.
your initial value for r is strs.size(), after a few recursions you get to the line if (l == r) return a[l]; with r still at its initial value. a[a.size()] leads to undefined behaviour. The initial value for r should be strs.size() - 1.
In common_prefix if the whole of the shorter st... |
67,616,695 | 67,616,967 | why is my output not coming in double form, when everything that i've declared is in double form? | #include <iostream>
using namespace std;
int main()
{
double d = 4, b, e;
cin >> b;
e = b + d;
cout <<e<< endl;
}
why is my output not coming in double form, when everything I've declared is double?
I've already tried typecasting it, but still, it's not working as I want it to work.
When I give 4.... | There is no double form. Printing necessitate a format, a specification of the way the result is outputted, whatever you print.
ostreams does have an internal states to decide the way a given argument is printed. Basically, these can be controlled through input/output manipulators. There is some that can be applied to ... |
67,616,994 | 67,617,380 | Call global instance of a class object inside its constructor | It may sound weird as what the title says. Why not just use this to call any members than use a global instance of the class itself. But in a project, I just realized I do write such kinds of codes after I finished and reviewed them.
Here is a piece of prefabricated sample codes.
// header.h
#ifndef HEADER_H
#define HE... | In fact, the standart (n4659 15.7 [class.cdtor] §3)explicitely allows that
member functions, including virtual functions (13.3), can be called during construction or destruction
Apparently, this code uses the object foo in its constructor before that object is fully constructed which should be UB. But as the shown co... |
67,617,097 | 67,624,124 | win32 c++ acces violation when executing shellcode | I wrote this function to find out the length of an assembly instruction based on this talk about breaking the x86 instruction set.
/* shellcode is a pointer to a buffer contains assembly instructions
size is the size of that buffer */
DWORD GetInstructionLength(BYTE* shellcode,SIZE_T size) {
LPVOID RWXBuff = nul... | rwx at ...80000 /
rw- at ...80010 - those are in the same page.
x86 memory protection works at page granularity (4096B), so you just changed the whole page to non-executable, including the RWXBuff.
The end of the ...80000 page is 80FFF, and the start of the next is ...81000.
(12 offset-within-page address bits = 3 hex... |
67,617,211 | 67,617,305 | Debugging from visual studio does not find file next to executable. When program ran manually, it does | I am trying to test an SFML program and I have a problem when debugging it. I am loading two files that are located next to the executable; an image and a configuration file.
If I run the program from inside the output folder manually, it all runs ok.
If I try to run the program from inside Visual Studio (using the loc... | As @Bathsheba pointed out, one needs to set the working directory in Properties->Debugging->Working Directory
|
67,617,225 | 73,347,873 | CMakeLists add_library according to option | I am trying to build a project (c++ code files) that is to be applied on different type of target machines, and I am trying to include cpp files according to the machine type, for this I created options in the CMakeLists file in order to use them to whether include the cpp file or not.
option (MACHINE1 "MACHINE1 DESCRI... | cmake_minimum_required(VERSION 3.1)
option (MACHINE1 "MACHINE1 DESCRIPTION" OFF)
option (MACHINE2 "MACHINE1 DESCRIPTION" OFF)
add_library(SO_LIBRARY SHARED)
if(MACHINE1)
target_sources(SO_LIBRARY
PRIVATE
FILE2.cpp
)
endif()
if(MACHINE2)
target_sources(SO_LIBRARY
PRIVATE
FILE3.... |
67,617,782 | 67,887,591 | [Boost::ext].SML: How to get the "real" event in "on_entry<_>" and "on_exit<_>" when using the '_' (underscore) placeholder | Precondition:
I used the Compiler Explorer https://godbolt.org/ to run the code snipped below.
Problem description:
I tried to access the events members when using the generic event ('_' underscore) handling for on_entry/on_exit definitions.
This is working only for the newest gcc compiler x86-64 gcc 11.1 available on ... | Answer for question A
If you remove the following overload, then invalid memory read would happen.
That is a pitfall.
// Used to handle non BaseEvent's
void operator()(const e2& event){
printf("[OnEntry] %s | other events\n", sml::aux::get_type_name<decltype(event)>());
}
Answer for question B
C++17
You can solve ... |
67,618,054 | 67,622,901 | Do C++ ranges support projections in views? | I know algorithms (e.g. sort) in ranges support projection, but it seems to me that there is no way to get that functionality for views...
Am I right?
As an example consider following working code:
#include <algorithm>
#include <ranges>
#include <vector>
#include <iostream>
enum Color {
Red,
Green,
Blue
};
s... |
Do C++ ranges support projections in views?
No (although range-v3 did†).
Is there a way to remove the lambda and do something like:
std::views::filter(&Cat::color, Color::Red)
That wouldn't really be how this would work with projections anyway. It would have been:
filter([](Color c){ return c == Color::Red; }, &Ca... |
67,618,316 | 67,619,041 | Convert struct sockaddr_in6* to boost::asio::ip::address_v6 | I am implementing a host name / ip address parser for a TCP/IP client / server program.
I can successfully cast IPv4 addresses from sockaddr_in* to boost::asio::ip::address_v4 but I fail to get the IPv6 conversion from struct sockaddr_in6* to boost::asio::ip::address_v6 right:
#include <iostream>
using std::cout;
#inc... | Got it working:
vector<address> getAddresses(string const &hostname)
{
struct addrinfo req = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM};
struct addrinfo *pai;
int error = getaddrinfo(hostname.c_str(), nullptr, &req, &pai);
if (error)
throw domain_error("Could not resolve host name.");
... |
67,618,355 | 67,621,643 | How can I vary this template class to take an additional template parameter? | I'm having trouble having an extra template parameter to my class template. I'm not sure if this is possible but I think it's clear what I'm trying to do:
struct NullableType { };
template <typename value_t>
struct ArrayMap
{
static inline constexpr bool bIsValueNullableType = std::is_base_of_v<NullableType, value... | As you haven't specified if you are limited to an old C++ standard I will propose a solution in C++20.
You can use template specialization. Your primary template will have to take two arguments (a type and a non type argument):
template <typename value_t = int, auto null_v = 0>
struct ArrayMap;
Then, a specialization ... |
67,618,388 | 67,618,544 | Managing VS_VERSION_INFO FILEVERSION from external resource | I am using VS2019. I one solution I have few c++ projects sharing a common static library. For managing version info I use Version resource.
The only modification on executables I do perform is changing the library's code. So I would like for the exec's version to be determined by the version of my lib.
I was thinking ... | One solution would be to factor out the library's version into one of its headers, and include that.
include/MyLib/Version.rh:
#pragma once
#define MYLIB_VERSION_STR() "1.0.0"
#define MYLIB_VERSION_COMMA() 1, 0, 0, 0
Then you can #include it into the library's RC file, as well as your project's, and use it within t... |
67,618,483 | 67,618,543 | Need to find the minimum value of a 4x2 array while ignoring the diagonal | I need to find the lowest value in an array that isn't in the main diagonal, I have written some code but it seems to pick either the second or the last value only (depending on which one is the lowest).
here is my code:
#include<iostream>
using namespace std;
int main()
{
int arr[4][2];
int Min,i,j;
cout<<... | The line
Min=arr[0][1];
is bad because
It reads uninitialized arr[0][1] when i = 0, j = 0.
It writes arr[0][1] to Min unconditionally, even if current Min is smaller than that.
Instead of this:
Min=arr[0][1];
if(i!=j and Min > arr[i][j])
{
Min=arr[i][j];
}
This will work, for example:
if(i!=j and ((i==0 and j==... |
67,618,740 | 67,618,870 | How to add timer in c++? | I am making a c++ project having a login program. I want to add timer such that if the user enters login details wrong three times then user have to wait for 10 minutes. Can anyone suggest a way?
| You don't need a timer. You may do a delay.
This is how it works on windows
#include "windows.h"
Sleep(5000);
and how on linux
#include <unistd.h>
sleep(5);
|
67,618,961 | 67,619,106 | Why does friend function not able to access private variables of a class? | #include <iostream>
using namespace std;
class base_A {
int a = 5, b = 6;
friend void derive::print(base_A);
};
class derive {
public:
void print(base_A obj) {
cout << obj.a << " " << obj.b;
}
};
int main() {
base_A obj1;
derive obj2;
obj2.print(obj1);
}
Though I've used friend key word I c... | You need correctly to place declarations relative to each other in the program. Otherwise the compiler will issue an error that either a name is undeclared or a type is incomplete. For example
#include <iostream>
using namespace std;
class base_A;
class derive {
public:
void print(base_A obj);
};
class base_A {
... |
67,619,049 | 67,619,050 | Installing the Windows SDK 8.1 version in Azure Pipelines | I want to upgrade my Azure Pipeline vmImage to 'windows-2019' in order to compile my project with Visual Studio 2019.
pool:
vmImage: 'windows-2019'
variables:
solution: '**/*.sln'
buildConfiguration: 'Release'
appxPackageDir: '$(build.artifactStagingDirectory)\AppxPackages\\'
steps:
- task: VSBuild@1
displa... | I used choco in order to get the Windows 8.1 SDK:
- task: PowerShell@2
displayName: 'Install the win 8.1 SDK'
inputs:
targetType: 'inline'
script: |
choco install windows-sdk-8.1
|
67,619,087 | 67,619,217 | Inheriting a template base class - scope resolution of base class members | I have written a template base class as below:
template<typename T>
class Base {
public:
Base(T x);
void print_base();
virtual ~Base();
protected:
T data;
};
template<typename T>
Base<T>::Base(T x) : data(x) {}
template<typename T>
void Base<T>::print_base()
{
std::cout << data << std::endl;
}
te... | You can use this inside constructor body, during initialisation of base class this is unavailable and you just use base class name to initialise it as you did in changed code snippet of yours. Constructor of your derived class should look like this:
template<typename T>
Derived<T>::Derived(T x) : Base<T>(x) {}
|
67,619,218 | 67,619,378 | Calling the system through C++ inconsistently fails | I'm trying to launch a Python script by using the system call through C++, on Ubuntu. The problem is that this command sometimes works, but more often than not, it fails and throws one of two errors:
sh: 1: Syntax error: EOF in backquote substitution
sh: 1: xK-��: not found
The code I'm using:
std::string pythonPath =... | The data buffer returned by c_str is only guaranteed to be valid until the next time you access the string in various ways, in particular destroying it. So if command is about to go out of scope, it's a race between this thread destroying the buffer, and the new thread using the buffer in system.
Rather than making a t... |
67,619,338 | 67,621,143 | Error trying to implement type checking with SFINAE | I was following Jean Guegant's SFINAE blog post, where he implements a type trait using sizeof() which checks if there is a serialize function in the class. Inside which he has this reallyHas struct which checks if serialize is just a member of the class or an actual member function, by doing this
template<typename T>
... | Simplifying, the principle of SFINAE is to provide a few candidates for a symbol (overloads, template specializations etc.). Then, for a given argument the compiler will try out every candidate one at a time, until it finds the best match.
In this case, the test function is used for SFINAE. The goal is to have it defin... |
67,619,779 | 67,620,125 | (C++) Array as member of struct: how to get its size? | I have a struct which has a pointer to array as a member and I'd like to determine the size of this array.
#include <stdio.h>
int array[]={1,2,3,4,5};
struct myStruct {
int *array;
};
struct myStruct my_struct={.array=array};
int main() {
printf("A: %d\n",sizeof(array)/sizeof(*array)); // this works
pri... | As discussed here the compiler does not know that int* array points to an array of type int and as such sizeof() only returns the size of the pointer.
So either use std::vector or add a size member to your struct.
|
67,619,954 | 67,620,680 | how to convert a cc_binary to cc_library? | I have some sample code on openssl which I found on the documentation. (https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption under C++ section)
They suggested to compile with
g++ -Wall -std=c++11 aes_binary.cxx -o aes_binary.exe -lcrypto
I adapted this into bazel as:
cc_binary(
name = "aes_bi... | Each user of aes target needs to link to the crypto lib, thus you should add your linktopt here:
cc_library(
name = "aes",
hdrs = ["aes.h"],
srcs = ["aes.cpp"],
linkopts = ["-lcrypto"]
)
By the way it is better to compile as much as you can with Bazel, because it makes your build reproductible and herm... |
67,619,978 | 67,620,045 | Error : invalid conversion from 'const char*' to 'char*' [-fpermissive] |
first of all this is not duplicate one because same error Question
asked before but in different context
1
code
#include<iostream>
#include<cstring>
int main()
{
const char *s1;
const char *s2="bonapart";
s1=new char[strlen(s2)+1];
strcpy(s1,s2);
std::cout<<s1;
}
Output
[Error] invalid... |
Why such error ?
Look at the declaration of strcpy:
char* strcpy( char* dest, const char* src );
Pay particular attention to the first parameter. And very particular attention to the type of the first parameter: char*. It isn't const char*.
Now, look at the type of the argument that you pass.
const char *s1;
It... |
67,620,041 | 67,620,119 | What is the point of declaring the constructor explicit in an empty struct? | I was browsing a GCC header file recently and found this:
struct defer_lock_t { explicit defer_lock_t() = default; };
Why is the constructor declared explicit versus just being an empty struct defer_lock_t {}?
My understanding is that this type is used with a constexpr for constructor overloading. I'm a bit fuzzy abou... | The point is that defer_lock_t construction is never implicit. While if the constructor was not declared as explicit it would participate in implicit construction.
Consider this example:
struct explicit_t { explicit explicit_t() = default; };
struct implicit_t { implicit_t() = default; };
void foo(explicit_t){}
void b... |
67,620,272 | 67,684,446 | Import Python module from path in embedded Python | I'm using embedded Python in C++. I can import a module like so, given my_module.py is a file:
PyObject* pName PyUnicode_DecodeFSDefault("my_module");
PyObject* pModule = PyImport_Import(pName);
This works nicely for the most part, except that I have no control over where I can put the files containing the module; it ... | Assuming you've already called Py_Initialize at some point, you should be able to do:
PyObject* sysPath = PySys_GetObject((char*)"path");
PyList_Append(sysPath, (PyUnicode_FromString(pathToModuleDirectory)));
Where pathToModuleDirectory is a string containing the path to the directory containing the module you want to... |
67,620,813 | 67,623,181 | Alternatives to std::atomic_ref | I'm looking for an alternative to std::atomic_ref which might be used without needing C++20 support. I've considered casting pointers to std::atomic but that does not seem like a safe option.
The use-case would be to apply atomic operations to non-atomic objects for the lifetime of the atomic reference to avoid race. T... | In GCC/clang (and other compilers that implement GNU C extensions), you can use the __atomic builtins, such as
int load_result = __atomic_load_n(&plain_int_var, __ATOMIC_ACQUIRE);
That's how atomic_ref<T> is implemented on such compilers: just wrappers for those builtins. (That's why atomic_ref is super light-weight,... |
67,620,937 | 67,621,188 | Set of pointers to objects with custom comparator | I have a set of pointers and I want the set to be sorted in a specific order.
I came up with this code and it works as expected:
#include <string>
#include <iostream>
#include <set>
class Data
{
public:
std::string name;
int data;
bool operator < (const Data& other) const
{
return name < other.name;
}
... |
Is there some way to implement the custom comparator directly in the Data class so I can just have [stuff]:
No. I'd write a template
template <typename T>
struct PointerLess
{
bool operator()(const T * lhs, const T * rhs) const
{
return *lhs < *rhs;
}
};
Then you'd have std::set<Data*, PointerLes... |
67,620,952 | 67,622,120 | Check if folder pointed by StorageFolder still exist | How can I check if a folder pointed by a StorageFolder still exist?
| Assuming your app has the appropriate permissions, you could use the StorageFolder.GetFolderFromPathAsync API.
The following sample code is in C# but should give you the idea:
public static async Task<bool> ExistsAsync(StorageFolder folder)
{
try
{
await StorageFolder.GetFolderFromPathAsync(folder.Path)... |
67,621,224 | 67,621,511 | Overloading Ostream operator | I found that when i create ostream operator within a class or a struct
it only accepts one parameter as the second is This pointer
so i tried to do it this way and it is not working though
P.S I know that i should create it outside the class or the struct as a free function But I am trying to understand why ?
struct Ve... | When << is overloaded, a << b means either
operator<<(a,b)
if the overload is a free function, or
a.operator<<(b)
if it is a member.
That is, for an operator defined as a member, the left-hand argument is *this, and you need to write
Vector2 v;
v << std::cout;
wihch is equivalent to
Vector2 v;
v.operator<<(std::cout... |
67,621,677 | 67,622,452 | Interpolating frequencies | This is more of a math problem than a programming problem, but it has now come up for me twice in two different programming projects.
I would like to create a function, w_sweep(t, f0, t0, f1, t1), that samples at time t a sine wave that sweeps through frequencies from f0 when t == t0 to f1 when t == t1. (You can assum... | You have to think about it in terms of phase. For a constant frequency the phase ist just the product of time and frequency. But in general it's the integral over the frequency function across time.
The easiest way to show how this works is with a diagram, but its also possible with formal math. Unfortunately SO markdo... |
67,622,200 | 67,622,633 | Finding max height/depth in Binary Tree | After going through the basics of Binary Tree, I define it in C++ as below :
struct Node
{
int key;
Node *left;
Node *right;
}*left=NULL,*right=NULL;
int getDepth(Node* t)
{
if (t == NULL)
return 0;
else
{
int lDepth = getDepth(t->left);
int rDepth = getDepth(t->right);
if (l... | Two issues:
1. You're incorrectly setting up the struct Node.
To define a type Node where the members have initial values, your syntax is slightly wrong. Instead, do:
struct Node {
int key = 0;
Node *left = nullptr;
Node *right = nullptr;
};
2. The height of the tree is 3.
Here's a visual representation of... |
67,622,370 | 67,622,841 | C++: How do I create a vector of objects and insert an object in 3rd place? | I'm trying to make a vector of objects and insert an object into 3rd place. I've been unsuccessful so far. Here's my code. I made an array and added couple of objects to it and then made a vector and loaded it with the array. Also to note, MobilniTelefon is child of Proizvod. Here's my code:
Main.cpp:
#include <iostrea... | std::vector::insert accepts a const reference to value type, which can only be assigned to other const references.
Your operator=, though, accepts a non-const reference, so it cannot be used in overload resolution.
General solution: Make operator= accept a const reference.
Specific solution for your case: Just drop you... |
67,622,693 | 67,625,460 | Write allocated memory to disk | I have an allocated memory and I want to write it to a file. How can I do that in C++ 20?
I know I could do the following sequence, just like in C. However, in C++ there is the std::filesystem, can't I do that with it?
CreateFile
VirtualAlloc
memcpy
WriteFile
VirtualFree
CloseHandle
auto* const data = VirtualAlloc(nu... | Here is the tried and true method for writing memory to a file:
// Open your output_file as binary
static const size_t DATA_CAPACITY = 0x1000;
output_file.write(data, DATA_CAPACITY);
This is known as block writing to a binary file (or a file in binary mode).
|
67,622,857 | 67,623,033 | How to write predicate for file count using std::filesystem? | I have such a method that count all the files by the given dir
std::size_t number_of_files_in_directory(std::filesystem::path path)
{
using std::experimental::filesystem::directory_iterator;
return std::count_if(directory_iterator(path), directory_iterator{}, [](auto) { return true; });
}
there is a predicate ... | You forgot to name your parameter.
Because the scope of the lambda has another parameter with the same name path, the compiler thinks you forgot to scope that variable in your lambda.
You could change the signature of your lambda to [](const std::filesystem::path &path)
But better is to not re-use path as a variable na... |
67,622,976 | 67,644,671 | What is the maximum (and minimum) 16-bit double value? | I am working on audio data manipulation (from/to WAV files, 16 bits), representing samples with double values (64 bits).
Since I am working with a lot of amplitude-domain convolution, a lot of time my resulting samples have (positive or negative ) values that go "above" the "maximum data" that can be represented on 16 ... | The simple answer is that your denominator (for normalizing 16-bit data) is 2^15 assuming signed PCM.
Divide all your incoming 16-bit data by 32767 is my solution for normalizing. Maybe a case can be made for 32768, as the data ranges from -32768 to 32767. But I've always used 32767.
|
67,623,358 | 67,623,846 | CRTP pattern with variable Base | Assume that one has two base classes Base1 and Base2 for which CRTP pattern is desired.
template <typename TDerived>
class Base1 {
};
template <typename TDerived>
class Base2 {
};
Now I would like to define a Derived class such that it can be "parametrized" with a base one.
What would be the proper way to define it i... | From your comment:
The problem I think still exists.
Consider your own pseudo-code when fed to a compiler (and some addition):
template <typename TDerived>
struct Base1 {
auto get() const -> int {
return static_cast<TDerived const*>(this)->a;
}
};
template <typename TDerived>
struct Base2 {
auto ... |
67,623,714 | 67,624,153 | This might be a naive question but in simple terms how to implement a copy constructor same as std::vector? | I have a simple Box container with a naive implementation that takes Car
#include <iostream>
#include <vector>
struct Car {
Car() { puts("def"); }
Car(Car const& other) { puts("copy"); }
Car& operator=(Car const& other) {
puts("assign");
return *this;
}
};
struct Box {
size_t siz... | new[] combines allocating memory with starting the lifetime of the elements in the array. This can be problematic, as you've seen, because it calls the default constructor of each element.
What std::vector does is use std::allocator (or whatever allocator you provided as the second template argument) to allocate memory... |
67,623,843 | 67,623,887 | c++ returning object from a function | The code below shows a class representing complex numbers. My interest is in understanding the operator+ function. As I understand Complex res should be allocated on the frame of the function operator+. Is it correct to return this object to the caller? By the time this function returns the frame would have been popped... |
Is it correct to return this object to the caller?
C++ supports both return by reference and return by value. Since you are not using return by reference, you are not returning a reference to the object to the caller. You are using return by value, so you are returning the object's value to the caller. Consider:
int ... |
67,624,353 | 67,624,648 | c++ Multiple inheritance from 2 functions, while one of them is pure virtual | Let's say we have a class which inherits from 2 other classes which have both a virtual function with the same signature.
Because the signature is the same, there will be an error because the main class doesn't know who to inherit the virtual function from.
adding to that, if a function is pure virtual, it needs to be ... |
if the main class inherits from 2 classes with same virtual function but one of them is a pure virtual, will it just use the second one?
No. C++ will not assume that you want that behavior.
Or something else needs to be done?
You must implement the function if you don't want the derived class to be abstract.
void ... |
67,625,006 | 67,626,181 | How to convert a Pascal TDateTime(double) time to a Unix epoch in C++ | I need to convert from a Pascal TDateTime object which is a double value to Unix epoch using c++.
A possible solution is proposed (https://forextester.com/forum/viewtopic.php?f=8&t=1000):
unsigned int UnixStartDate = 25569;
unsigned int DateTimeToUnix(double ConvDate)
{
return((unsigned int)((ConvDate - UnixStartDat... | The Delphi/C++Builder RTL has a DateTimeToUnix() function for this exact purpose.
In a TDateTime, the integral portion is the number of days from December 30 1899, and the fractional portion is the time of day from 00:00:00.000. Using raw math involving more than just whole days can be a little tricky, since floating-... |
67,625,166 | 67,625,277 | How does C++ handle vectors when passing from a function to main? | I'm seeing strange behaviour in the output of a 'simple' function that generates the binary representation of an integer. I aim to use the function in another code, but first want to see it working by printing to the console. I first define the function dec2bin to take a number and the length of the required bitstring.... | On this line:
myvec[N-i-1] = 1;
You are invoking undefined behavior for any index other than 0.
myvec.push_back(N); pushes a single element to the vector, and you never add more elements to the vector. When you access a vector out of bounds, you will not get a compiler error or runtime exception, but your code has und... |
67,625,845 | 67,625,961 | Assistance with understanding Copy Constructors | I'm attempting to tackle some Hackerrank challenges, and i've just learned about copy constructors. However i can't get my head around its use. Here is the completed working code.
#include<bits/stdc++.h>
using namespace std;
class Box
{
private:
int l,b,h;
public:
Box()
{
... | The copy constructor is pretty straight forward. Construct the object by copying data from another class of the same type. Usually copy construction is done like this,
Box b1;
Box b2 = b1; // Here the copy constructor is called for the b2 object.
Box b3 = Box(b1); // Here the copy constructor is called explicitly for... |
67,626,270 | 67,631,211 | Inheritance and std::shared_ptr in Cython | Suppose I have the following simple example of C++ inheritance in file.h:
class Base {};
class Derived : public Base {};
Then, the following code compiles; that is, I can assign std::shared_ptr<Derived> to std::shared_ptr<Base>:
Derived* foo = new Derived();
std::shared_ptr<Derived> shared_foo = std::make_shared<Deriv... | It should work for Cython>=3.0 as @fuglede made this PR fixing the issue described below (which is still present for Cython<3.0).
The issue is, that the the wrapper of std::shared_ptr misses
template <class U> shared_ptr& operator= (const shared_ptr<U>& x) noexcept;
of the std::shared_ptr-class.
If you patch the wrap... |
67,626,418 | 67,626,770 | C++ is Unique_ptr pertinent for vectors of vectors | I'm in a case where i use a builder to use factory to create CombatUnit for my project, as show in the schema (please note that I have an abstract factory, but i wouldn't complexify it for nothing).
The thing is, i'm creating arrays of arrays and i'm using unique_ptr to protect from memory leaks.
But i can't find if i... |
C++ is Unique_ptr pertinent for vectors of vectors
That's for you to decide, but only rapidly looking at the code without other knowledge of the infrastructure, I would say that this is a heavy, terrible code smell. I would simply use the vector as is. It's lighter, safer, simpler, and faster.
A pointer to a STL cont... |
67,626,791 | 67,626,890 | It seems to me as if std::getline doesn't handle new lines correctly? | With the code below, I want the user to write a text in the terminal, and then print out the last sentence of the text. Maybe I should mention that I'm running on a Linux desktop.
#include <string>
#include <iostream>
int main()
{
std::string user_text{};
while(std::getline(std::cin, user_text))
{
}... | std::getline() erases the output std::string before attempting to read from the stream.
In your second case, the first 2 calls to std::getline() have already read everything you have typed in, there is nothing left when you press CTRL-D during the 3rd call, so there is nothing for std::getline() to output into the std:... |
67,627,501 | 67,627,525 | Can I use Flutter without Dart? | Before you give me answers like: "Just use dart it is really easy to learn" you must know that I already KNOW Dart and Flutter. And I also KNOW that you can communicate between those 2 languages. However, I really don't like this language and I wonder if I could write a Flutter App without any single peace of dart line... | You cannot. Flutter is a dart framework. Dart is the language. Flutter is not a language by itself at all. If you're writing "Flutter code", you're writing "Dart code"
|
67,627,892 | 67,627,928 | How do I create a function in C++ that has multiple parameters but only one is required? | I have a function takes two "optional" parameters, but the logic of the function expects that at least one be specified. If a is provided, then a is used. If b is provided, then b is used. If neither parameter is provided, then an exception is thrown because this function needs at least one of the parameters to be give... | You can overload this like so:
void print_it(A a, B b)
{
//use a and b
}
void print_it(A a) {
//use a
}
void print_it(B b) {
//use b
}
Or, you can use std::optional like explained here: https://en.cppreference.com/w/cpp/utility/optional.
Example:
void print_it(std::optional<A> a, std::optional<B> b)
{
if (a.has_v... |
67,627,914 | 67,628,108 | Can you enumerate and call different subclass constructors through a for loop? | If I have several subclasses of the same Base class that take the same type and amount of arguments in there constructors similar to:
class Base {};
Class A : public Base
{
A(arg1, arg2){};
};
Class B : public Base
{
B(arg1, arg2){};
};
Class C : public Base
{
C(arg1, arg2){};
};
I am wondering if there... | The question at face-value seems to be a bit of an x-y problem, since you mention that you are trying to create and store a large number of these in a container.
There is no way to simply call different instances of the derived constructors directly like you ask in your question, but there may be a better approach foll... |
67,628,126 | 67,682,916 | Generating an edge graph using four values a,b,c,d in c++ | I'm having a trouble solving a question which asks me to generate an edge graph using 4 random numbers a,b,c,d , so the formula is as follows , to generate the nodges of the graph we'll use variable d , if we divide d with 3 and we get a remainder of 0 then 10 nodges are generated , if d/3 = 1 then 11 nodges if d/3 = 2... | At first you do not handle the case of d being outside of desired range. If d is e. g. 37, then you leave Nodges uninitialised, invoking undefined behaviour afterwards by reading it. You might add a final else to catch that case, printing some representation for an empty graph or a message and then return, so that you ... |
67,628,133 | 67,628,194 | Unable to create a Two Dimensional Array with random parameters | So I am a Beginner in C and I was going through Arrays and i was having success with arrays restricted to bounds of constant integers...
But i also wanted to find out what happens if we give in a random number for the Numbers of Rows and columns..
However when i executed the program all was fine until the 4th element w... | int m,n;
int matrix[m][n];
There are two big problems here.
Problem 1: You don't give any value to m nor n. Then you use these ungiven values as the size of an array. C++ is not a "dataflow" language. If you use a value, the program won't stop, and wait for you to initialise the value later. If you use an uninitialise... |
67,628,186 | 67,628,248 | How to write the result of a function to a file C++ | I think this is a pretty simple question, but I didn't find the answer.
I wish to write the result of a function to a file.
The file is open, and I'm able to write a simple string to it, but not the result of the function.
What I am missing?
#include <iostream>
#include <fstream>
using namespace std;
void addingtext()... | addingtext() returns nothing, and writes to std::cout.
You have two options:
Option 1: Make addingtext() return a string, and then write that to the file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
std::string addingtext() {
std::string result;
for (int i = 0; i < 8; ++i)
... |
67,628,339 | 67,640,372 | Is there a way to log the output of a process create via boost::process::spawn? | I know that there is a way with a boost::process::child as described here:
boost::asio::boost::asio::io_service ios;
std::future<std::string> data;
child c("g++", "main.cpp", //set the input
bp::std_in.close(),
bp::std_out > bp::null, //so it can be written without anything
bp::std_err > data,
... | No that is not possible. It's implied in the documentation:
This function does not allow asynchronous operations, since it cannot
wait for the end of the process. It will fail to compile if a
reference to boost::asio::io_context is passed.
Maybe you can use child::detach instead?
#include <boost/process.hpp>
#include... |
67,628,518 | 67,628,695 | Can I pass a lambda to a constexpr constructor? | I have this constexpr class:
class ParamType {
public:
constexpr ParamType(std::string_view name, std::string_view uuid,
float minVal, float maxVal, float defVal,
std::function<void(float)> onValue) :
kName(name),
kMinVal(minVal),
kMaxVal(maxVal),
... | This is nothing to do with lambdas. The actual error message from clang - just compiling your class, without even trying to instantiate it - is:
'function<void (float)>' is not literal because it is not an aggregate and has no constexpr constructors other than copy or move constructors
which is pretty much self-expl... |
67,628,857 | 67,632,769 | Procedure Entry Point could not be located: Qt MinGw CPP Desktop App crashes when run | In my Qt Desktop app, I have included the <filesystem> in one of my .cpp files. When I compiled it with the MinGw 8.2 version there were errors everywhere. I tried downloading MinGw through MSyS2 and now the application compiles successfully. However, when I try to run it, it crashes, and shows me this error:
| Your application is loaded with a dynamic library which is not same version with the dynamic library that you build your application against。
You can find out the dll which your application was built against and put it into the directory where your application is
|
67,628,949 | 67,629,058 | Determining if input data is "balanced" | I have been creating a program that checks if an input file (passed in using file redirection) has all matching parentheses, brackets, and/or braces. (Ex: [][]{}() is "balanced", while [[}] is "not balanced").
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int main() {
stack<ch... | You don't actually need a stack for this - you can just keep track of the number of open and close brackets that you see as you work your way through the input string.
So, on the assumption that different types of bracket must be differentiated, you could do something like this (I also fixed your ranged for loop):
#inc... |
67,630,663 | 67,630,987 | Which sections of the C standard prove the integer type correspondence? | In one of the late drafts of C11 ([C11_N1570]) I fail to find a proof to the following statements (which, I believe, are commonly known), see below. Can anybody refer me to particular sections of the C standard that prove the sentences below? (or correct me if I'm wrong)
Type short is the same as signed short (TODO: li... | Link to the online HTML version of the C standard: section 6.7.2/2. Possibly, together with section 6.2.5/4.
Link to the online HTML version of the C++ standard: [tab:dcl.type.simple].
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.