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 |
|---|---|---|---|---|
64,618,991 | 64,619,055 | What is the meaning of "const Allocator& alloc = Allocator()"? | I refer to c++ std::string constructor on both cplusplus.com and cppreference.com.
And I find the syntax on cppreference.com is more complex to me. On the contrary, cplusplus.com is clearer and easier to understand.
For example:
// cplusplus.com
string (const string& str, size_t pos, size_t len = npos);
// cppreferenc... |
What is the meaning of “const Allocator& alloc = Allocator()”?
In this context, this is syntax for a function parameter. It allows arguments to be passed into functions.
I wonder why "const Allocator& alloc = Allocator()" appears here
It appears so that an allocator could be passed as an argument.
and why it is ne... |
64,619,242 | 64,619,315 | Dereferencing through pointer and incrementing gives a different value and decrements it instead C++ | I was trying to do some experiments with pointers in C++, I did understand the concepts of precedence a bit but the following program is mingling with my mind and am unable to comprehend it
CODE:
#include <iostream>
using namespace std;
int main() {
int x = 9;
int* ptr = &x;
cout << "The value of x is " <<... | Use ++(*ptr) instead of (*ptr)++ to achieve result that you want.
++x increments value of x and then returns new incremented value, while x++ increments x but returns previous value (copy) of x.
And according to your expectations to have 9, Address, 9, 10, 11, 12 you really wanted to have behavior of ++x hence using of... |
64,619,312 | 64,638,327 | Why would I write custom allocators for STL containers when I could just overwrite new and delete? | I want to write a custom memory manager/allocator for learning. I'm tempted to have a master allocator that requests n bytes of ram from the heap (via new). This would be followed by several allocator... Adaptors? Each would interface with the master, requesting a block of memory to manage, these would be stack, linear... | Answering the two questions in-order:
Should I write custom allocator_traits to interface my allocators for the various STL containers?
Yes, for easy manipulations. Pretty soon in the implementation, situations such as controlling memory overlaps would arise. For example, while stress-testing the implementation at full... |
64,619,349 | 64,619,359 | "// \" Next Line automatically commented out in C++ after putting this? | Why the next line after //\ is commented out in C++ ? Like I know about "//" and "/* ... */ " but after putting //\ the next line is automatically commented out !
| \ at the end of a line is line continuation for comments and preprocessor.
|
64,619,741 | 64,633,099 | Should you use curl through commandline or include the library? | This one i feel is hard to justify one over another. I see so many here at stackoverflow do both the variants. Some just call cURL console commmands externally from their programs(example: curl "content=hello world" -X POST https://example.com -H "charset=UTF-8"). And others import the library and call it programmatic... | Whenever possible use the library. Not just for cURL, but in general.
You should definitely avoid system() calls or creating separate processes launching the external command line application. This adds overhead and can cause issues when porting your code between different platforms.
Also libcurl has a ton of features.... |
64,619,752 | 64,622,926 | MFTEnumEx cannot find MFAudioFormat_MP3 decoder on Windows 7? | As an offshoot question from: IMFTransform SetInputType()/SetOutputType() fails
When I try to enumerate MP3 decoders on Windows 7 it fails to find any MP3 decoders? However it appears to find one when I set a partial media type for a IMFSourceReader for an MP3 file created by MFCreateSourceReaderFromURL.
I have tried:... | Windows 7 SP1 decoder:
MP3 Decoder MFT
MFT_TRANSFORM_CLSID_Attribute: {BBEEA841-0A63-4F52-A7AB-A9B3A84ED38A} (Type VT_CLSID)
MF_TRANSFORM_FLAGS_Attribute: MFT_ENUM_FLAG_SYNCMFT
MFT_INPUT_TYPES_Attributes: MFAudioFormat_MP3
MFT_OUTPUT_TYPES_Attributes: MFAudioFormat_PCM
The decoder does not advertise support for MFA... |
64,620,100 | 64,626,428 | Call one of multiple variadic functions based on params | How can I defined the Add() templates below such that the correct ones get called, based on the arguments.
Both are variadic functions.
Add2 always has 2nd param that is a struct of base BaseB.
struct BaseB {};
struct B1 : BaseB {};
struct B2 : BaseB {};
Add<Foo1>(a); // Call Add1
Add<Foo2>(a, "str... | For C++17 you can use @Jarod42's answer with overloaded Add function.
struct BaseB
{
};
struct B1 : BaseB {};
struct B2 : BaseB {};
template <typename R, typename A, typename ... Params>
void Add1(A& a, Params&&... args)
{
std::cerr<<"Add1 called"<<std::endl;
}
template <typename R, typename A, typename B, typena... |
64,620,123 | 64,620,411 | What is the memory lay out of a C++ structure? | I was learning about the structures in C++ and got to know that if a structure in C++ has 3 variables (let each one be of some data type), then all of them are not allocated in a contiguous fashion. Is this correct?
If yes, then how much memory would be allocated to an object to that structure type?
For e.g. Let's say ... | When it comes to structs and classes, The layout is implementation-defined between compilers, os, and architecture... Some will use automatic alignment, others will use padding, some may even auto arrange it's members. If you need to know the size of a struct, use sizeof(Your Struct).
Here's a code snippet...
#include ... |
64,620,266 | 64,620,652 | how to delete a single node in linked list c++ | *Edited: My problem is that I did not handle the special case in which the value to delete is the head of the LinkedList. Someone fix it in the answer section.
I have a class of Node, and a function to delete a node in which the value of String matches with any node.
class Node
{
public:
string getName(... | Your code seems to work as expected, but you must handle a special case for the case the deleted node is the head :
#include <iostream>
class Node
{
public:
Node(std::string n) {
name = n;
}
std::string getName() const
{
return name;
}
Nod... |
64,620,530 | 64,621,246 | How can I watch more than one QFuture? | The QFutureWatcher class emits the signal finished() when the QFuture it is watching has finished.
How can I watch more than one QFuture?
I am running two threads in parallel using QtConcurrent::run() and would like to get a signal when both threads have finished.
| I would approach the problem like this:
Create as many QFutureWatchers as needed
Add all QFutureWatchers to a list, resp. vector, e.g. m_futureWatchers:
m_futureWatchers.append(futureWatcher);
Connect the QFutureWatcher::finished signals to the same slot, e.g. handleFinished:
connect(futureWatcher, &QFutureWatche... |
64,621,522 | 64,621,990 | C++: Static assert that a parameter pack matches a function type | Given the function type void(), void(int), and so on..., can we static_assert() that Args&&... args is compatible with the function type?
template <typename F = void(), typename... Args>
auto call(Args&&... args)
{
// TODO: check if F is compatible with Args
if constexpr (std::is_same_v<void, decltype(func(arg... | You have tagged C++17, so... what about using std::is_invocable?
I suppose something as follows
template <typename F = void(), typename... Args>
auto call (Args && ... args)
{
static_assert( std::is_invocable_v<F, Args...> );
// ...
}
|
64,621,908 | 64,622,092 | non-trivial rvalue and lvalue example | I am not sure about some rvalue/lvalue non-trvial examples.
are std::vector<int>({1,2,3})[0] and std::vector<int>() expressions below lvalue or rvalue?
the code has no actual usage but it surprises me a bit that the code is valid. It looks like they are both lvalues. or not?
#include <vector>
int main()
{
std::vec... | std::vector<int>() is an rvalue, because the syntax type() always produces an rvalue. std::vector<int>() = {1,2,3}; is allowed because assigning to rvalues of class type is allowed in general, but can be disabled for a specific class by defining operator= with a & qualifier, which std::vector doesn't do.
std::vector<in... |
64,621,984 | 64,622,117 | Making a for loop faster by splitting it in threads | Before I start, let me say that I've only used threads once when we were taught about them in university. Therefore, I have almost zero experience using them and I don't know if what I'm trying to do is a good idea.
I'm doing a project of my own and I'm trying to make a for loop run fast because I need the calculations... | (1).
The question @François Andrieux asked is good. Because in the original code there is a well-structured for-loop, and if you used -O3 optimization, the compiler might be able to vectorize the computation. This vectorization will give you speedup.
Also, it depends on what is the critical path in your computation. A... |
64,622,410 | 64,622,760 | Why do you need to use both fixed and showpoint manipulators to show decimal point and trailing zeros when only fixed does the job? | I understand what the fixed and showpoint manipulators do on their own, but why would you want to use them both at the same time? This is what DS Malik's C++ Programming textbook says:
Of course, the following statement sets the output of a floating-point number in a
fixed decimal format with the decimal point and tra... | With fixed you set a number of decimals that you want to see in all cases. So you will always see the decimal point. Combining with showpoint makes no difference, unless...
Unless... You setprecision(0), in which case you'll never see a decimal and hence no decimal point. In this case showpoint will have the effect ... |
64,622,764 | 64,625,443 | Number of seconds between two dates including leap seconds | I'm fiddling around with time representation in C++.
I would like to have a strictly monotonic representation of time, that handles leap seconds well. The utc_clock in C++20 should be able to do that, and since my compiler doesn't support this version yet, I'm using HowardHinnant/date.
To understand the library better ... | It looks like you're using the OS supplied timezone database (USE_OS_TZDB=1), and that the leapseconds aren't being read. This can be confirmed with:
cout << get_tzdb().leap_seconds.size() << '\n';
This should output 27 (currently), but for you I imagine it is outputting 0. This means leapsecond data is missing.
Wit... |
64,623,624 | 64,623,745 | How to access friend function from another class? | When I compile the following code,
#include <iostream>
using namespace std;
class class1;//forward declaration
class class1{
int var;
public:
void setter(int);
friend void getter(class1 o1);
};
class class2{
public:
void getter(class1 o1)
{
o1.var;
}
};
void class1::setter(int v)
{
va... | The other answers tell you how to solve the problem in the easiest (and probably the best) way. However, if you really want to only grant the friend privilege to single member function, more work is required:
class class1;
// To befriend a member function of class2, it must be defined before the friendship declaration... |
64,624,750 | 64,628,588 | I cant get GLEW to work on netbeans in ubuntu 20.04 (C++) | I managed to get GLFW3 to work and properly display a window, however when i add glewInit() to my project it tells me undefined reference to glewInit'. I am using g++ as my compiler with -lglfw3 and lGl as flags. Below is a simple project to demonstrate my issue. I am on linux. Any help is much appreicated.
#include <G... | There is a standard way on Linux to get a correct set of libraries to link with your program - please look at man pkg-config. In your case you need to link everything, which is needed by both GLFW3 and GLEW - so you should call the pkg-config two times:
hekto@ubuntu:~$ pkg-config --libs glfw3
-lglfw
hekto@ubuntu:~$ pkg... |
64,624,803 | 64,901,948 | Problem with compiler for bootloader of Pyinstaller | easy question here (I hope), I am a noob about this topic.
I am facing problem of "virus" with the ".exe" file generated by pyinstaller.
I read that a new bootloader of pyinstaller could help.
So following these links:
how to recompile the bootloader of Pyinstaller
https://pyinstaller.readthedocs.io/en/stable/bootloade... | I installed this version of Visual Studio package:
and the g++ compiler has been installed correctly.
I followed the procedure written here:
how to recompile the bootloader of Pyinstaller
and I obtain a perfect version of pyinstaller with no virus checked with virustotal.com
|
64,624,920 | 64,625,148 | Recursion to count words and redundant words in a sentence in c++ | Hi i'm trying to count the words in a sentence that is input by the user and this is the code i've written
void Count_Words( )
{
int count=0;
for (i = 0; inserted_text[i] != '\0';i++)
{
if (inserted_text[i] == ' ')
count++;
}
... | I agree with Hatted Rooster (this is not a good fit for recursion). I guess it serves a teaching purpose. So here is another option.
countWords() returns the number of words for the given substring until its end. To calculate the words for substring 0..n, we can calculate the words for substring 1..n first. And if char... |
64,625,340 | 64,668,552 | How to open sub-menu on right hand side in rtl alignments? | I have a menu that consists of Items and sub-menus. the texts and titles of items should be shown from right to left. I achieved this by using LayoutMirroring.enabled = true.
Menu {
id: right_menu
property var rtl: true;
MenuItem {
text: "گزینه ۱"
LayoutMirroring.ena... | You can use the overlap property to shift the submenu over to the position you want.
Note that if the position of the menu is too close to the left or right edge of the window, it will still open on the opposite side.
Menu {
id: right_menu
property var rtl: true;
MenuItem {
text: "گزینه ۱"
... |
64,625,905 | 64,641,502 | My app won't run unless I declare main as wmain. Why is that? (Visual Studio 19) | I've been working on the prototypes of an app that makes use of SDL and winsock libraries when I was suddenly met with this error on compilation:
LNK2019 unresolved external symbol main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)
I tried changing the "SubSystem" option to Windows a... | The problem was caused by the SDL macro that extends "main" to "SDL_main". The solution was to either use
#undef main
or use the official SDL way of undefining main. Using "wmain" seemed like it solved the problem not because of unicode dependency, but because SDL does not have a macro for "wmain".
|
64,625,909 | 64,632,087 | Convert arguments to types expected by wrapped function | Let's say that I want that I have a generic function F taking arguments of types Args and returning R. I want to wrap this function so that it fits the form:
using gen_type = void (*)(struct value *values,
size_t num_args,
struct value *return_value)
I also have func... | Below is an example how it could be done using Boost.Hana with func as a template argument.
#include <iostream>
#include <math.h>
#include <boost/hana.hpp>
namespace hana=boost::hana;
// sample value type
struct value
{
size_t content;
};
// sample conversion functions for sample value type
template <typename T... |
64,626,007 | 64,626,094 | Whats the difference between using () or {} for an initializer list | I was looking at the cppreference for constructors and I came across this:
class X {
int a, b, i, j;
public:
const int& r;
X(int i)
: r(a) // initializes X::r to refer to X::a
, b{i} // initializes X::b to the value of the parameter i
, i(i) // initializes X::i to the value of the paramete... | In your example there is no difference, you can use either of them, but, there exist some differences in some other context, for example, you can use curly braces to initialize a vector see below program.
#include<iostream>
#include<vector>
int main(){
std::vector<int> first(12,3,5,6); // Compile time error
... |
64,626,504 | 64,626,635 | mmap syscall fails with errno 14 | I was trying to do a syscall injection with MMAP on another process and it was failing. I noticed the syscall was executing properly, so the problem should be something else. I decided to run the syscall directly through the target program to make it more simple to understand. Unsurprisingly, it wasn't working either, ... | The legacy __NR_mmap syscall on 32-bit (at least 32-bit x86 anyway) does not have that signature. It takes a single argument that's a pointer to a struct mmap_arg_struct32; see https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/arch/x86/kernel/sys_ia32.c?id=v5.9#n214. This syscall is deprecated sin... |
64,626,762 | 64,653,057 | Why can’t windbg display my user-mode call stack in a kernel mode dump? | I wrote a program with Visual C++ and it crashes Windows. Luckily, I have a crash dump!
!analyze -v states that the faulty process is indeed my program and shows me a kernel-mode call stack. However, I need to understand the state of my user-mode program to make sense of it.
According to some other answers here (e.g. t... | RbMm was right – the dump doesn’t include any user address space, so there’s nothing for windbg to show.
When opening a dump file with windbg, watch the first few lines of output. There should be a message like Kernel Bitmap Dump File: Kernel address space is available, User address space may not be available, which sa... |
64,627,068 | 64,631,212 | C++ and SFML, no instance of the overloaded function "sf::RenderWindow.draw()" matches the argument list | I am currently trying to make a simple pong game with SFML in C++. I consistently get the error in the main file.
#include <iostream>
#include "Ball.h"
Ball b;
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(1200, 600), "My window");
// run the program as long as the window is ope... | You had not call function of render, you just wrote window.draw(b), and programm dont know what do you mean. In Ball.h you should write:
#pragma once
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class Ball
{
public:
double x, y;
int Radius;
... |
64,627,116 | 64,627,178 | Can I convert my 1D vector to a 2D vector faster than this? | The question is quite straightforward. After some trials, here is the most efficient code I found:
//For the sake of the example, I initialize every entry as zero.
vector<float> vector1D(1024 * 768, 0);
vector<vector<float>> vector2D(768, vector<float>(1024,0));
int counter = 0;
for (int i = 0; i < 768; i++) {
fo... | It might be faster by using memcpy, as that is the lowest possible level of an API for copying memory and is likely that there are compiler optimizations which may use specific instructions, etc. and make if faster:
for (int i = 0; i < 768; i++) {
memcpy(vector2D[i].data(), &vector1D[i * 1024], sizeof(float) * 1024... |
64,627,314 | 64,627,588 | How to sample two textures onto the same object? | I have to reproduce an effect which consists of combining two textures (tiles + coin) to achieve the following:
The best result I achieved so far:
Visual Studio Solution to reproduce the problem
The link above will take you to the project and here what I tried to do in the pixel shader:
float4 PS(PS_INPUT input) : SV... | Well firstly you are blending them but not blending using an alpha-mask, when the example image seems to have been blended with an alpha-mask.
An example could be something like below; provided the coin has got an alpha-channel.
(Otherwise you'll have to calculate an alpha or add one in an image editing software.
f... |
64,627,423 | 64,627,473 | Struct pointers are overriding each other | I have a function:
void initGraph(node_t *node, const int orderedInputNodes[]) {
int index;
for (int i = 0; i < S * 2; i++) {
if (orderedInputNodes[i] == node->number) {
index = i % 2 == 0 ? i + 1 : i - 1;
node_t newNode;
newNode.number = orderedInputNodes[i... |
I thought by stating node_t newNode; a completely new node will be automatically created.
Correct. The problem is that the new node can replace the old node. Consider:
for (int j = 0; j < 1000; ++j)
{
int i;
i = 3;
}
You don't think after this loop runs, there's a thousand instances of i still sitting a... |
64,627,691 | 64,627,902 | How do I get code to read both first and last and values of a randomly generated array? | I was debugging my code when I realized my code constantly reads the same thing for one one function; it only reads the last value of an array. I want it to read both the first and the last value of the array. I've tried many methods only to have it read the same thing. How do I fix this?
Point of emphasis is below.
in... | Look at the rest of the code to understand it a little bit more. By calling the for-loop the first time the following happens:
arraysize[i = 0] && arraysize[i = 5];
First you are setting i to 0 and arraysize[i = 0] returns the first element. Than you are setting i to 5 and arraysize[i = 5] returns the fifth element of ... |
64,628,479 | 64,628,577 | Template argument functions as class members | I have a lot of methods defined in Transforms.h like this :
#ifndef TRANSFORMS_H
#define TRANSFORMS_H
namespace Transforms
{
long double asech(long double x);
long double acsch(long double x);
long double asechDerivative(long double x);
long double acschDerivative(long double x);
long double identi... | You need to pass values not types as your template arguments. Here is a reduced example using your code with all the unnecessary details removed and a couple methods added to demonstrate the usage of the template parameters.
long double sigmoid(long double x);
long double sigmoidDerivative(long double x);
using FuncT... |
64,628,742 | 64,629,083 | AddressSanitizer: heap-buffer-overflow on address 0x6020000000b4 at pc 0x0000003a86fc bp 0x7ffeebd5f9d0 sp 0x7ffeebd5f9c8 | Trying to solve a problem on leetcode and I keep getting an error saying:
==29==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6020000000b4 at pc 0x0000003a86fc bp 0x7ffeebd5f9d0 sp 0x7ffeebd5f9c8
READ of size 4 at 0x6020000000b4 thread T0
class Solution {
public:
bool uniqueOccurrences(vector<int>& arr... | In
for(int i = 0; i < count.size();i++){
if(count[i] == (count[i+1])){
return false;
}
}
i will reach count.size()-1 and count[i+1] becomes count[count.size()-1+1] which is count[count.size()] and out of range.
A better way to write this loop is
for(int i = 1; i < count.size(); i++){
if(count[i-1]... |
64,628,747 | 64,628,873 | Casting malloc to (void**) | Let's say, in C++ I use malloc to allocate memory for 4x void pointers:
malloc(4*sizeof(void*))
Since malloc returns a void pointer I assume that the following assignment is valid:
void *x;
x=(void*)malloc(4*sizeof(void*));
However, most of the code that I find on the forums casts to (void**) before assignment, like ... | lets say you are allocating memory for an integer variable then we use pointer to an integer int*
suppose if you want to allocate memory for pointer variable , then we use pointer to poniter int**
same goes for void* as well , hope below example helps you.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i... |
64,628,798 | 64,630,406 | How to get rid of initialization after first of two for-loops? | I have a for loop that is currently in the form
for (i=0; i<N; i++) {
y = 0.;
for (j=0; j<N; j++)
y += ...
}
And I'd like to rewrite it as
for (i=0; i<N; i++) {
for (j=0; j<N; j++)
y += ...
}
Where y is initialized at some prior point such that the two for loops are collapsed. Is there any way to... | This is not the same as the code that you've linked to. The original has y indexed, i.e., it is an array:
for (i=0; i<N; i++) {
y[i] = 0.;
for (j=0; j<N; j++)
y[i] += ...
}
This could be rewritten as:
for (i=0; i<N; i++)
y[i] = 0.;
for (i=0; i<N; i++)
for (j=0; j<N; j++)
y[i] += ...
}
In your cas... |
64,628,907 | 64,628,917 | Defining a function prototype in C++ based on requirement | I'm having a disagreement with my professor about the following function prototype:
Prompt: "function that takes pointer to a float, a pointer to a pointer to a char and returns a pointer to a pointer to a integer."
I say it is
int ** function(float * myFloat, char ** myChar)
but the options given are:
A. int **fun(flo... | You're right, and none of the 4 suggested answers matches what is stated in the prose.
|
64,629,099 | 64,629,244 | Saving/loading application data in Qt? | I have a Qt program that needs to save and load some files to persist some data between runs of the program. How do I locate the appropriate OS-specific directory in which to store these files? Does Qt provide an API for this?
(The SDL library has for example SDL_GetBasePath and SDL_GetPrefPath. Does Qt offer a simi... | QStandardPaths::AppDataLocation is probably what you're looking for. From the docs:
Returns a directory location where persistent application data can be stored. This is an application-specific directory.
|
64,629,289 | 64,629,422 | In custom reverse vector iterator don't see first element | The other day I wanted to try writing my own iterators for a vector, of course, the most primitive example, since there is a lot of confusing code in the c++ standards. So the usual iterator for a vector in the forward direction works fine, but there was a problem with the reverse iterator. I have it completely built o... | rBegin() returns an iterator to the first element:
ReverseIterator rBegin() { return ReverseIterator(data + size); }
But it's pointing one element beyond the end and can't be dereferenced. You need to dereference the element before it.
You could therefore adjust the dereference operator in the VectorRevIterator versio... |
64,629,378 | 64,634,922 | Is calling a function pointer to generated code undefined behavior? | Is there a way, in purely standard C++, to somehow call a function generated within a buffer?
Let's assume:
We've used implementation-specific knowledge (and obv. architecture-specific) to generate the byte sequence implementing some function in an array of char.
This implementation correctly matches the implementatio... | As I understand your question, you ask about code such as:
char buffer[200] = "some valid operations";
void (*func)() = reinterpret_cast<void(*)()>(buffer);
func();
I see in the standard in C++ expr.call 7.6.1.3 Function call:
A function call is a postfix expression followed by parentheses containing a possibly empt... |
64,629,630 | 64,629,667 | getting the length of array provided array is being accessed through pointer | For ex.
I have a function
void len(int *A){ // or we have its reference
// can I find the length of array here or
// we just need to pass the length along as the parameter
}
|
can I find the length of array here or we just need to pass the length along as the parameter
You can't find the length once the array has decayed into a pointer so one option is to supply the length as a parameter as you said yourself.
Another option is to not let it decay into a pointer:
template<size_t N>
void len... |
64,629,839 | 64,630,063 | Finding the minimum and maximum number from rearranging digits without using arrays and strings | So i have a task that i'm supposed to find the max and minimum number by rearranging given number.
The hard part is that, in this task especially i'm not allowed to use arrays,vectors and string into array way.
Example:
Input: 598
Output: 589, 985
I done that, but only using the array, that sort every number by desc an... | I did it in that way.
int a,b,c,temp,x=123;
a = x/100;
b = (x/10)%10;
c = x%10;
if(b>a){
temp=a;
a=b;
b=temp;
}
if(c>b){
temp=b;
b=c;
c=temp;
}
if(b>a){
temp=a;
a=b;
b=temp;
}
cout << "smallest: " << a+(b... |
64,629,891 | 64,629,892 | How to configure CodeLite IDE to use C++ and SFML library? (Windows/Linux) Configuration complete solution | How to configure "CodeLite" IDE for being able to develop in C++ with the library SFML?
Here below is my complete solution...
ENJOY
| This complete solution is described within Windows but this also works in Linux
1) Downloads on SFML Website (Download section) :
https://www.sfml-dev.org/download/sfml/2.5.1/
The needed compiler
The corresponding SFML libraries
Pay attention to :
The compiler name (here MinGW)
The compiler version (here 7.3.0)
The... |
64,630,036 | 64,631,084 | Confusion about the phenomenon of overriding | I am little confused about when to say that function is overriden.
My book says "When a derived class creates a function with the same return type and signature as a
member function in the base class, but with a new implementation, it is said to be overriding
that function."
I am clear what book saying but my questio... | The problem in above code reminds me a very interesting concept of CPP, Name Hiding which simply states that, if we try to overload a method in a derived class, then the compiler will hide the base class method unless we explicitly informs the compiler to include a base class method or we explicitly call the base class... |
64,630,335 | 64,630,447 | I can't understand this variable type in c++ vector declaration | In the C++ code, there is a declaration like
vector<void *( *)(void *)> t_list;
I have never seen void*(*)(void *) variable type before. Can somebody explain what that type means?
| This vector is declared to hold function pointers, that is, pointers to functions. As declared, it allows you to add pointers to functions that look like this:
void* someFunc(void* someArg);
Then you can use the function pointers stored in the vector to... call them, as
Here is a simple example. I don't do anything wi... |
64,630,435 | 64,630,736 | temporal removal on depth result in ghostly image | I'm trying to do temporarl removal on depth image, and I'm getting a ghosty image as shown in the video below
Single Image:
Video:
https://www.youtube.com/watch?v=5HBlpuihzks
and here is the code:
while (key != 'q') {
if (zed.grab(runtime_parameters) == ERROR_CODE::SUCCESS) {
zed.retrieveImage... | cv::addWeighted(depth_image_ocv, 1.0 - factor, last_image, factor, 0.0, result);
The above line only works correctly if depth_image_ocv and last_image matrices are both floating-point type (F32_C1). However, look here:
last_image = result;
This doesn't make a copy of result into last_image; it only co... |
64,630,571 | 64,631,276 | How to read dictionary file to a map<char, vector<bool> >? | I have a text file which is a dictionary of pair "character-binary code". I need to read that dictionary from the file and put the values to map<char, vector > to perform some other operations on it.
I decided to read each line separately first(because binary codes are variable length) and then I need to assign each ch... | I think this much code will suffice:
// include necessary files
#include <algorithm> // for std::copy
#include <fstream> // for std::ifstream
#include <iostream> // for std::cout
#include <iterator> // for std::ostream_iterator
#include <map> // for std::map
#include <string> // for std::string
#include <v... |
64,630,574 | 64,630,609 | expression must have arithmetic or unscoped enum type C++ | I am trying to make a password prompt using C++. My code is given below:
#include <iostream>
#include <string>
std::string operator * (std::string a, unsigned int b) {
std::string output = "";
while (b--) {
output += a;
}
return output;
}
int main(){
std::string pword;
std::string user;
... | in
std::string pword_asterix = ("*") * pword.length();
you multiply a pointer, you want something like :
std::string pword_asterix(pword.length(), '*');
after that :
pi@raspberrypi:/tmp $ g++ -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
Enter username: aze
Enter password for user 'aze': qsdqsd
Noted user 'aze' and pas... |
64,630,634 | 64,630,802 | How to do texture mapping for cylinder created by GL_TRIANGLE_STRIP in OpenGL and how to taper a cylinder | I am currently trying to create a model of squidward from spongebob squarepant's house.
I have created a cyllinder out of GL_TRIANGLE_STRIPs as I am not allowed to use any predefined OpenGL models to create the shapes.
I am trying to do texture mapping for each triangle on the cylinder but the texture comes out stretch... | The texture coordinates are 2-dimenional and have to be in range [0.0, 1.0]:
glBegin(GL_TRIANGLE_STRIP);
for (int i = 0; i <= 32; i++) {
double x_next = 1.0 * cos((i + 1) * 2.0 * PI/ (32 - 2.0));
double y_next = 1.0 * sin((i + 1) * 2.0 * PI / (32 - 2.0));
if (i % 2 == 0) {
glTexCoord3f((float)i / 3... |
64,630,939 | 64,631,029 | How do I use getline to output a string n times using getline? | I want to use this code with the getline function to output a string n times, but it only outputs blank lines instead of some string. Why is this so and how do I fix it?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n;
string str;
getline(cin, str);
for (int ... | When you enter a number to assign a value to n, do you then enter the string after a line break? If so, str is assigned a newline character instead of the corresponding string.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n;
string str;
// getline(cin, str);//Filter new... |
64,631,418 | 64,653,323 | Passing a pointer to MPI_Win_allocate_shared through a wrapper | I am having some difficulties to understand what is going on with my pointer passings:
I have the following minimal program
#include <mpi.h>
void ALLOC_SHM(double * arr, int sz);
void MPI_WRAP( MPI_Aint size, int disp, MPI_Comm comm, double * bufptr, MPI_Win* win ) ;
int main(int argc, char const *argv[])
{
int size... | Some reading of the MPI standard and understanding of C++ pointers and function arguments may help here. For example, reading the Open MPI manual page for MPI_Win_allocate_shared:
On each process, it allocates memory of at least size bytes that is shared among all processes in comm, and returns a pointer to the locall... |
64,631,562 | 64,631,743 | Creating a "class" definition using LLVM c++ API | I am working on a custom front-end language using the LLVM c++ api and am adding a "class" definition construct to the language. The lexer and parser are written in C++ and LLVM c++ api is being used to generate IR code and compile to different machine backends. I can already define functions and variables, call functi... | Looking at the source code of Module::getTypeByName, it looks up the name in the LLVMContext instance. This means you don't have to add your type to the module and name lookup should work just fine, even through a Module instance.
|
64,631,689 | 64,632,973 | Why I can't assign result of std::from_chars to std::tie? | I was thinking, that instead of auto [x,y] I can assign to std::tie made from existing variables but for some reason, it doesn't work. Can anyone tell why? I'm afraid that I don't understand compiler message. It seems to me that it tries to assign integer to the tuple (???)
#include <charconv>
#include <tuple>
int main... | These are two different kind of constructs.
auto [p, err] = std::from_chars(s, s+3, val); // this compiles
This is structured binding which can bind any structural element (Array, Structure, Tuple etc) to individual identifiers. See: Structured Binding
On the other hand this code:
std::tie(p,err) = std::from_cha... |
64,631,794 | 64,631,911 | GetWindowLong loses data of fields | I do a wrapper for Window and want to call window methods from WndProc.
For this I pass 'this' pointer to CreateWindwEx function.
In WndProc I assign hWnd field of Window class and store it by SetWindowLongPtr
But when I try to read it by GetWindowLong I get broken instance of the window (all the fields have undefined ... | My fault!
GetWindowLongPtr should be used instead of GetWindowLong
|
64,631,846 | 64,631,900 | My C++ Power Calculation is not outputing the calculation | This program is supposed to take two numbers (a base and an exponent) and calculate the power. For example, base 5 to the power of 2 should equal 25. But when I input these two numbers, it won't output the result. Here is my code:
#include <iostream>
#include <cmath>
using std::cout;
using std::cin;
using std::endl;
... | Your power() function has two issues. First of all, the condition in the for loop is wrong (it's i = exponent, which is an assignment, when it should be i < exponent). Secondly, the expression should be result = result * base to get the desired result.
double power(double base, int exponent) //declaring and defining
{
... |
64,632,038 | 64,633,249 | How to ensure correct destruction of vk::UniqueBuffer and vk::UniqueDeviceMemory | I have run into the following conundrum trying to use Vulkan Hpp unique handles to store a buffer and its allocated memory. I declare the handles
vk::UniqueBuffer vertex_buffer;
vk::UniqueDeviceMemory vertex_buffer_memory;
and populate them using vk::Device::createBufferUnique and vk::Device::allocateMemoryUnique. The... |
These need to be called in this order since the latter depends on the memory requirements of the former
No, they do not. You do need to get the memory requirements appropriate to that buffer, but you do not need to use that specific VkBuffer object to do that.
It's best to compute the requirements once at the start o... |
64,632,076 | 64,632,256 | How to use c++ structure array like flexible? | What should I do if I want to use the structure array flexibly?
I made my code like below, and tried Triangle and Rectangular..
Triangle was success but when i tried Rectangular I got error messages.
struct C2D {
double x, y;
};
class Polygon {
int point;
std::vector<C2D> arr;
public:
Polygon(int point... | The problem is that you use the same name for
C2D c2d[3];
and
vector<C2D>c2d(point);
However, your code has several other issues such as using C-arrays in C++. Consider using std::vector, e.g., like this:
#include <iostream>
#include <vector>
struct C2D {
double x, y;
};
class Polygon {
std::vector<C2D> coordin... |
64,632,242 | 64,640,759 | MinGW-w64 generates 32-bit binaries | Why does my MinGW-w64 generates 32-bit binaries? They can't run if their stack size is more than ~2GB, compatibility mode is on Windows XP by default, and -m64 option doesn't works (64-bit mode is not compiled in.).
| Which exact file did you download? The installer, mingw-w64-install.exe? If so, it lets you choose if you want an x32 or x64 compiler. Consider using a different MinGW distribution (the one you used has an outdated GCC). The two good ones are msys2.org and winlibs.com – HolyBlackCat
|
64,632,424 | 64,632,780 | Interpreting static_cast "static_cast<void (Pet::*)(int)>" syntax? | I'm trying to understand the static cast as used in the Pybind11 docs here. Specifically, they use the syntax
static_cast<void (Pet::*)(int)>(&Pet::set)
Since I haven't seen this syntax before I'm strugling to interpret and apply to my own code so I was hoping somebody could explain what's going on here. Thanks
Edit -... | The meaning of:
static_cast<void (Pet::*)(int)>(&Pet::set)
static_cast<T_1>(T_2) means we're casting type 2 to type 1.
T_1:
(Pet::*) is a pointer to a class member of Pet (see https://stackoverflow.com/a/9939367/14344821 for a further discussion)
void (Pet::*)(int) is a pointer to a member function that takes an int... |
64,632,596 | 64,634,223 | Insert the last element in the middle of array in c++? | the code changes the place of other elements, I want output was without changing
if size = 6 elements 1 2 3 4 5 0 the output should be 1 2 3 0 5 6 but the code outputs 1 3 5 0 2 4
below my coding implementation in c++ I want to where exactly I am making mistake
the code changes the place of other elements, I want outp... | You can use std::rotate to move the end element to the middle.
For the problem you posed:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using std::advance;
using std::cout;
using std::ostream;
using std::rotate;
using std::vector;
static ostream& operator<<(ostream& out, vector<int> c... |
64,633,036 | 64,641,036 | Finding Bug in implementation of dynamic array class. Crashes after building list of strings | I have written a DynamicArray class in the past analogous to vector which worked.
I have also written as a demo, one where the performance is bad because it has only length and pointer, and has to grow every time. Adding n elements is therefore O(n^2).
The purpose of this code was just to demonstrate placement new. The... | The use of memcpy is valid only for trivially copyable types.
The compiler may even warn you on that, with something like:
warning: memcpy(data, old, size * sizeof(T));
writing to an object of non-trivially copyable type 'class string'
use copy-assignment or copy-initialization instead [-Wclass-memacc... |
64,633,154 | 64,633,337 | providing a default argument to a function, but that argument is a struct | struct mat4x4
{
float m[4][4] = {0};
};
Basically, I have function to multiply a 4x4 matrix.
mat4x4 matrix_matrix(mat4x4 m1, mat4x4 m2)
{
mat4x4 product.m[someValue][someValue] = do_calculations_and_get_product();
return product;
}
So what I was thinking is to take a third mat4x4 as argument by reference... | With a compiler supporting C++17 this becomes a simple matter of using std::optional with std::reference_wrapper. Implicit conversions do all the hard work for you.
#include <optional>
#include <utility>
#include <functional>
struct mat4x4
{
float m[4][4] = {0};
};
mat4x4 matrix_matrix(mat4x4 m1, mat4x4 m2,
... |
64,633,530 | 64,635,402 | How to use structure array like flexible with c++ | What should I do if I want to use the structure array flexibly? I made my code like below, and tried Triangle and Rectangular.. Triangle was success but when i tried Rectangular I got error messages.
So I tried to change my structure array more flexibly but I don't know how PLZ help !
polygon.h
#pragma once
#include <i... | I found two errors.
include cmath. It is better to use std::abs(sum) in function area_result() in accordance with cmath.
Major error is from the third line of main():
C2D c2d[3];
It fixed the array length of c2d to 3, which causes the segment fault for 4-point polygon.
To fix this error, you may use new allo... |
64,633,541 | 64,634,480 | "Extended" depth-first search in C++ | I know how to implement depth-first search algorithm in C++, but I need an "extended version". So, I have a map
map<int, map<int,int> > tree;
that for any vertex it returns a map with adjacent vertices as keys and (important for my program) edge indexes as values. The root of the tree is first (1) vertex. So, here is ... | "graph with no cycles" is also known as a tree.
You want to have a list with all the sequences of edge labels that represent a path from root to some vertex?
Pseudocode for a traversal (I guess this would qualify as a preorder traversal):
void collect(node, //current node
labels, //labels of edges leading to node
... |
64,633,563 | 64,633,590 | c++ Exception thrown at 0x7A45FF80 (ucrtbased.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0x00000000 | i have an error when i run this code and I don't know what it is, I get an error in string in visual studio app
the error
" Exception thrown at 0x7A45FF80 (ucrtbased.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation reading location 0x00000000."
#include <iostream>
using namespace std;
#include <string>
i... | string option = 0; is the culprit and string option; is the fix.
The latter relies on the std::string default constructor.
The former will cause the constructor to a const char* to be called, with undefined results.
|
64,633,811 | 64,634,147 | Using DirectShow with Direct2D | I have a windows only Direct2D application and would like to implement a video playback system for cutscenes. These files are mp4 but the format can be changed, if need be.
It seems like DirectShow is the advised way to render video/audio on windows.
Now how do I let DirectShow render the video frames to my Direct2D re... | There is no Direct2D/DirectShow interoperability layer in Windows. To fit these two technologies you would have to copy data between the APIs in a rather inefficient way (and this will still take some time to develop the fitting).
With H.264/HEVC MP4 video files you would be better off using Media Foundation to read an... |
64,633,899 | 64,634,030 | No inheritance found with operator= and initializer_list | Here the code that I a lot simplify for this question.
template<class T>
class A
{
public:
A<T>& operator=(A<T> const& other)
{
std::cout << "A<T>& operator=(A<T> const& other)\n";
return this->operator=(other.m_container);
}
template<class U>
A<T>& operator=(std::vector<U> const& ... | Your problem is when you try something as
BB bb1;
bb1 = { -1.0f, -1.0f, 0.0f };
not when you try to initialize your BB object with an initializer list. The error is coming from operator=().
To solve your problem, I suggest that you add a using, in your BB class, as follows
class BB: public AA
{
public:
usin... |
64,634,110 | 64,634,435 | C++ base class constructor taking derived class as argument (?) | Use case:
Vector class (implementing some math) and a derived Vector2D class
Both classes should ideally allow "copy construction" from each other
Vector
namespace mu {
template<std::size_t N, typename T>
class Vector {
public:
// ...
template <typename... TArgs>
Vector(TArgs... args) : data({args...}) {}
... | Your Vector class has two constructor: a template one (intended for values) and the default copy constructor.
Problem: the copy constructor is preferred but only if there is an exact match.
So, initializing b with a
mu::Vector<2, int> a{1, 2};
mu::Vector<2, int> b{a};
the copy constructor is preferred because a is an ... |
64,634,590 | 64,634,676 | can't tokenize a string and pass it to struct in c++ | i have to write a program in which i have to take time(hh:mm:ss) as string input and tokenize it using : as a delimiter and pass hours, minutes and seconds to a struct time and then display the total number of seconds. I have written the code but it's giving me error that i can't understand. This is the code:
#include<... | time happens to be the name of a function in the standard C library (and incorporated into the C++ library), and by naming your struct the same, you're creating ambiguity, and according to the grammar rules of C++, the compiler must consider time to the function name, here, resulting in a compilation error.
The simples... |
64,634,658 | 64,636,154 | Does C++ accept inline virtual function while performing polymorphism? | //header.h
#include<iostream>
using namespace std;
struct Base {
virtual void vf();
};
struct Derived :Base {
virtual void vf();
};
inline void Base::vf() {
cout << "Base::vf()" << endl;
}
inline void Derived::vf() {
cout << "Derived::vf()" << endl;
}
//source.cpp
#include"header.h"
int main() {
Ba... | As the code is currently written, the member functions are defined in header.h and marked inline. That's okay from the perspective of the language definition: inline means "it's okay to have multiple [identical] definitions of this function". From a maintenance perspective it can make things harder. In particular, when... |
64,635,598 | 64,635,721 | Calculate the sum between two iterators in STL containers | I am working on a problem in STL containers:
Create a Sum() function that calculates the sum between two iterators. The function then uses the template argument for the iterator type and accepts two iterators, the start and the end
I am trying to write the following code but I am not understanding the problem can anyon... | There are a number of issues with your code. In this function:
template <typename type , typename start , typename end>
double sum(type& t, start& s , end& e)
you are taking s and e by reference. But this can't bind to l.begin() or l.end(), since they return r-values.
Iterators are generally passed around by copy an... |
64,635,655 | 64,640,642 | How to change cv :: Mat value according to tolerance | I am new in C++, until now I was programming in Python.
I have a cv :: Mat and I want to pass all pixels greater than 100 to 255, if they are less than 100 I pass them to 0.
In python it would be:
imgDst(imgDst > 100) = 255.
imgDst(imgDst <= 100) = 0.
Can anyone tell me what this operation would look like in C ++? Obv... | Another option is to use a member method of cv::Mat:
imgDst.setTo(255, imgDst > 100);
and similary
imgDst.setTo(0, imgDst <= 100)
|
64,635,907 | 64,636,112 | Derived class hiding base class same name method | I was reading this article and it states
This calls Derived::f( complex ). Why? Well, remember that
Derived doesn't declare "using Base:f;", and so clearly Base::f( int )
and Base::f( double ) can't be called.
I decided to try this out and used this code
class Base {
public:
virtual void f( int ) {
cout <... | Simple. You should write the 'using' declaration under public section of class as below. If you put the declaration in private section, Base functions are available to Derived class but they will become private members of Derived class. That is why your compiler is throwing 'inaccessible' error.
#include <iostream>
#in... |
64,636,025 | 64,651,978 | Creating Command objects at run-time | I'm trying to write a console for a game engine which will allow me to type in commands to perform tasks, such as change the map, spawn an enemy etc.
I've been trying to do this with the Command pattern (following the example from gameprogrammingpatterns.com). See below for the outline of my current code structure.
pa... | By relying on a dictionary (e.g, std::unordered_map or std::map) that maps a command identifier (i.e., a std::string object) to a Command object, you can design a factory with dynamic registry for your Command objects.
First, extend Command by including another virtual member function, clone(), that allows us to imple... |
64,636,326 | 64,636,642 | Why does the address of the assigned object not change in C++? | In this C++ example, a class C has a default constructor, a copy constructor and an assignment operator:
struct C {
C();
C(const C& c);
C& operator=(const C& c);
};
The implementation is as follows with some output for tracking the objects. I added some example addresses in comments on the lines as referen... | Objects in C++ never change addresses.
An assignment operator is no different from any other method, normally it just goes over all member variables and assigns new values to them, copied from the corresponding members of the other object.
|
64,636,417 | 64,649,751 | SFML trying to get a sprite to track mouse | the below code doesn't seem to work I get a very strange sprite that sometimes tracks the mouse but almost gets bored and gives up. If this is the wrong place and need to go to maths exchange.
It seems to do something the sprite wiggles but doesn't follow the mouse and seems based on angle. The /2 is because the sprite... | If was writing your code, I did it like this:
float dX = mousePosition.x - sprite.x;//vector, collinear straight line whicn crosses sprite an cursor on X axis;
float dY = mousePosition.y - sprite.y;//same, but to Y axis;
float angle = (atan2(dY, dX)*180)/3.14159;//CALCULATING ANGLE
sprite.setRotation(angle + 90);
|
64,636,783 | 64,638,207 | RSA exponent d is negative | Im trying to encrypt and decrypt various messages with RSA and while it is working flawlessly while d is positive, it obviously breaks when d is negative as d is supposed to be a natural number.
I am using the EXTENDED_EUCLID algorithm to find it and the code is as follows.
void EXTENDED_EUCLID(cpp_int a, cpp_int b, cp... | The solution was to move the 2 lines of code that are above the EXTENDED_EUCLID(b, n_a, n_d, n_x, n_y); recursive call to the function MODULAR_LINEAR_EQUATION_SOLVER, below the initial EXTENDED_EUCLID call. Many thanks to President James K. Polk.
|
64,636,865 | 64,636,905 | Why do we have nullptr but not nullchar? | My understanding - and I'm sure I'm about to learn - is that nullptr was added to C++ to formalise the convention that a zero value for a pointer means the pointer does not point to a valid object. Is there a case for (or against) adding a corresponding nullchar to formalise the convention that a zero value for a char ... | No, because there's not as much reason to, really. nullptr was added to remove the need of the NULL macro, which in C is defined as something like (void*)0. In C, void* is implicitly convertible to any pointer type, so this would work. However, this is not true in C++, which removed this implicit convertibility (but no... |
64,637,192 | 64,637,221 | Is emplace_back ever better than push_back when adding temporary objects? | Suppose we want to insert an object of type T into a container holding type T objects. Would emplace be better in any case? For example:
class MyClass {
MyClass(int x) { ... }
}
MyClass CreateClass() {
int x = ... // do long computation to get the value of x
MyClass myClass(x);
return myClass;
}
int m... |
suppose we want to insert an object of type T into a container holding type T objects. Would emplace be better in any case?
No; there would be no practical difference in that case.
|
64,637,295 | 64,639,978 | Conanfile.py that sets a cmake flag? | I have a third party library that I am now attempting to add a conan recipe so I can start to manage this library via conan...
this third party library has a CMakeLists.txt that I need to manually add a compiler option... is there a way I can do this in the recipe ?
CMakeLists.txt
cmake_minimum_required( VERSION 3.0 )
... | If you want to create a recipe for a third party library and you want to modify any file from that library, including CMakeLists.txt, you can do that with tools.replace_in_file in your source method. The module tools is in the conans package.
I often use something like
tools.replace_in_file("sources/CMakeLists.txt", "p... |
64,637,340 | 64,637,409 | C++ - Searching in array from both sides | Is there any difference in speed between first loop and a second one when it comes to speed of executing it? Im talking also about larger arrays than this sample one.
int main()
{
int n = 17;
int posz = 7;
int array[] = {0, 1, 9, 2, 8, 3, 8, 5, 4, 7, 6, 10, 23, 43, 123, 54, 76, 34};
for (int i = 0; i < ... | In terms of Big-O time, no, since both methods are O(n).
In the first loop, you iterate less times but do more calculations per iteration. In the second loop, you do less calculations per iteration but do more iterations overall. I wouldn't expect there to be any huge performance difference between the two, and the com... |
64,638,183 | 64,638,234 | custom type declaration taking function C++ | I want to make something like below
void func1(int x)
{
...
}
int main()
{
auto acceptorFunc = bind(func1, 1);
keyword acceptorFunc;
return 0;
}
keyword is a struct which takes any function call as argument and execute its operator().
struct keyword
{
...
void operator()
{
// do some thing
a... | Something along these lines, perhaps:
struct TimeoutExecutor {
template <typename F>
void operator=(F f) {
// Do something before
f();
// Do something after
}
};
#define TIMEOUT TimeoutExecutor{} =
Demo . Actually, any binary operator would work, doesn't need to be an assignment.
|
64,638,343 | 64,638,930 | How do I get each child process to output a string? | For my assignment, I'm expected to "have the children generate a, b, c, & time it and then have them generate multiples of each letter to see concurrency in action. Use nested loops to go up to, say 500 of each letter."
Currently, my letter_generator.exe program just randomly chooses a letter and prints said letter. M... | Below is a basic example of starting a child process and passing it an argument via the command line.
I'll leave the remainder of your homework for you to figure out.
Also note I'm using some C++17 features here, so if you can't compile either set the language standard in Visual Studio to C++17 or change the code to co... |
64,638,417 | 64,638,445 | Do variables defined with const use up memory? | I've been researching whether I should use macros or constants in C++. This question isn't about that, but one thing that I realized is that macros don't take up memory (because they just do a text replace during preprocessing). But do constants take up memory? I wasn't able to find a good answer to this.
|
Do variables defined with const use up memory?
As far as abstract machine is concerned, yes they do.
As for actual memory: Potentially, yes. Not necessarily. Same goes for non-const variables. If you can replace a constant with a macro, then such constant should be possible without using memory.
I've been researchin... |
64,639,084 | 64,733,376 | How do you use stl iterator and a queue to implement a breadth first traversal of a graph? | while I understand the BFS conceptually I haven't grasped how to use an iterator and a queue to implement the BFS. I'd really appreciate it if somebody could give me some insight how to properly use the iterator in my code. Thank you.
I'm not even sure if an iterator is a good idea here, I tried to learn the auto type ... | I made slight changes to my code to fix it. I didn't use the iterator (an int variable in the for loop was fine), and I didn't need to dereference like this
n->adj[*i].v->name
Here's what ended up working
void getConnectedComponents(string buildingName, vertex *& node){
//pointer to sourceVertex
vertex *vStart... |
64,639,137 | 64,641,968 | boost geometry angle between two points | I'm playing with boost geometry (1.74) and there are a lot of examples using the distance algorithm which is great. How ever I'm struggling to find an example for calculating the angle (bearing) between two points.
It looks like the atan2 function is used inside details/azimuth.hpp but is not exposed on the API as at ... | You are quite right about the atan2 function in details/azimuth.hpp.
The angle (bearing) between two points is often called the azimuth.
It is defined in the file: <boost/geometry/algorithms/detail/azimuth.hpp> that you refer to, but unfortunately it is not listed in the documentation for boost algorithms.
You should b... |
64,639,184 | 64,651,398 | Repeating Command in LLDB | How can I repeatedly run a command in LLDB for debugging C++ code?
For example, when I set a breakpoint inside a loop and want to continue for 10 iterations before stopping, I am currently typing continue ten times manually to do this. Is there a better way?
As an example, let's say I have this code block:
int i = 0;
w... | lldb tends to use options where gdb would use a command argument. That makes it easier to have a bunch of different ways to condition a particular command without having to come up with ad hoc mini-syntaxes for each command.
Anyway, so in lldb you would do:
(lldb) c -i 10
You can see this in help:
(lldb) help continu... |
64,639,603 | 64,639,647 | Windows executable got executed on my linux | I wrote a simple code and compiled using g++ in linux in .exe format, suprisingly it got executed in my linux terminal. Can u say the reason for this ? Can linux terminal execute machine code in any format ? Can I run the same in windows ?
Code :
#include<iostream>
using namespace std;
int main(){
cout<<"Hello Worl... | Q: I wrote a simple code and compiled using g++ in linux in .exe format, suprisingly it got executed in my linux terminal
A: There's nothing "surprising". I assume you compiled it under Linux? So why shouldn't you be able to run it under Unix?
Q: Will an .exe I build on Windows run on Linux (if I copied the binary)? ... |
64,639,837 | 64,639,985 | Can I "hide" anything defined in a header file in C++ | Let's say I Have a header file test.h.
#pragma once
extern uint64_t a;
void foo( uint64_t );
In my case, uint64_t is used to represent a Bitboard as a part of my chess engine test.h Naturally I will be using uint64_t everywhere. I wanted to create a type alias for uint64_t, as Bitboard.
So I did
using uint64_t = B... | Best you can do is use an ugly C #define
#pragma once
#define Bitboard uint64_t
extern Bitboard a;
void foo(Bitboard);
...
#undef Bitboard
|
64,640,115 | 64,640,217 | Returning value of type defined in a class template | I'm new to C++ and trying to return a value from the size() member of my X class; the return type must be of X::size_type.
template <class T> class X {
public:
typedef size_t size_type;
size_type size() const;
// ...
}
template <class T> X<T>::size_type X<T>::size() const {
// ...
}
The above code res... | Due to the complex and sometimes ambiguous syntax of C++, sometimes hints are needed for the parser/compiler.
In general when referring to types defined inside a class, typename is needed to hint the compiler that you're talking about a type and not a value (since X<T>::size_type can be either).
|
64,640,253 | 64,640,311 | Taking string input without displaying its actual content (for PASSWORDS) | How to create a input function that doesnt displays what you have entered instead it displays another character?
ex- suppose you have entered "hello" it shows nothing or it shows "*****". With a proper backspace functionality.
THANKS IN ADVANCE
| EDIT: It looks like you already know the answer to your own question? I'll just leave this here in case anyone else finds it useful...
¯\_(ツ)_/¯
I'm going to assume you're wanting to do this in a console application, and you're probably on Windows. If so, I found this solution online from https://www.cplusplus.com/art... |
64,640,270 | 64,641,445 | Move Assignment of a Vector Element not working, Copy Assignment is called instead | I have a class that is not default-constructable, copy-constructable or copy-assignable. It is move-constructable and move-assignable.
struct SG_MotionState {
frameId_t frameId;
btTransform transform;
vector<sgCustomFieldData_t> mCustomFields;
sgCustomFieldLayout_t & mLayout;
SG_MotionState (sg... | Your problem lies in the absence of a move assignment operator.
Looking at your class, you have defaulted this operation.
Unfortunately, = default means that you get the default behavior, not that this method is created. This is really confusing.
To make this easier to spot I've recently enabled the following clang war... |
64,640,365 | 64,640,587 | Searching a map<pair<int, int>, ...> with lower and upper bound | I would like to know if looking up a map that takes a pair of ints (coordinates) as a key with lower_bound and upper_bound has any usable meaning?
using Point = std::pair<int, int>;
std::map<Point, Vertex> vertex_map = {};
const auto p = std::make_pair(0, 0);
const auto q = std::make_pair(10, 10);
auto foo = vertex_m... | No, I don't think it's possible. You need a comparator such that p < x && x < p iff x is bound by Rectangle (p, q) and this comparator must define a strict weak ordering
As far as I can tell this is not possible.
The way this problem is tackled in an efficient manner is to hold two lists: one with the points ordered by... |
64,640,479 | 64,640,607 | Hexadecimal to decimal converter not working (c++) | So, as part of an assignment, I wrote a program to convert hexadecimal to decimal. But I was not able to get the desired result. Can someone please pin point the error in this code?
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
int hexaToDecimal(string n){
int ans = 0;
int power =1;
int s =... | You may add - '0' like - 'A'.
There is the code:
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
int hexaToDecimal(string n){
int ans = 0;
int power =1;
int s = n.size();
for(int i=s-1; i>=0; i--){
if(n[i] >= '0' && n[i] <= '9'){
ans = ans + power*(n[i] - '0'); //THERE... |
64,640,725 | 64,660,241 | Uninitialised value was created by a stack allocation Valgrind c++ | So, I get this error when running the command: --track-origins=yes on Valgrind
==57680== Conditional jump or move depends on uninitialised value(s)
==57680== at 0x100584A6B: __dtoa (in /usr/lib/system/libsystem_c.dylib)
==57680== by 0x1005AB2DD: __vfprintf (in /usr/lib/system/libsystem_c.dylib)
==57680== by 0x... | This isn't a leak. You are reading uninitialized memory. As @PaulMcKenzie says in the comments, time is not standard C++, rather it is a GCC extension that comes from C99.
You could use memset to ensure that time is initialized. Alternatively, you could use std::vector, for instance
std::vector<double> time(iter_max + ... |
64,641,782 | 64,656,477 | Best way to add gtest to Visual Studio solution without NuGet | I have a GIT repository which contains a Visual Studio solution.
I need to add some tests for the code, and wanted to use Gtest for it.
Now, when I add a gtest project to the solution, a NuGet package of gtest is added to the solution directory. That's a lot of files that I don't want to keep inside the repository...
C... | You cannot create a GTest C++ project without using the nuget package. This is the system default project template that recommends to use Microsoft.googletest.v140.windesktop.msvcstl.static.rt-dyn nuget package.
It is designed by Microsoft and we cannot change the project without using the nuget package. And there is n... |
64,641,927 | 64,645,787 | ISO C++ forbids comparison between pointer and integer [-fpermissive][c++] | I am fairly new to c++ and prcticing some ds algo problem. From last 24 hours, I have been stuck with this.
/*Find shortest distance of every cell from landmine in a maze*/
#include <iostream>
#include <algorithm>
#include <queue>
#include <climits>
struct cell{
int x, y;
};
const int M = 6, N = 5;
int row[4] ... | 'X' vs "X"
C++ doesn't treat these two the same way.
'X' is treated as a char in C++.
But the second you use "", the meaning changes. Now it is treated as a string literal. Or, a sequence of characters. Or, a char[].
char c = 'X';
char c = "X"; // how dare you
How pointers?
Back to our example, to make it clear, whe... |
64,641,933 | 64,642,074 | Struct variable in class in heap and usage of smart pointer | How can I use smart pointer here?
#include <iostream>
using namespace std;
struct node
{
char data;
node *next;
};
class linked_list
{
private:
node *head,*tail,*tmp;
public:
linked_list()
{
head = nullptr;
tail = nullptr;
}
void add_node()
{
tmp = new node();
... | std::unique_ptr is probably the most appropriate here:
#include <iostream>
#include <memory>
struct node
{
char data;
std::unique_ptr<node> next;
};
class linked_list
{
private:
std::unique_ptr<node> head;
node* tail;
public:
linked_list()
: tail( nullptr )
{
}
void add_node()
... |
64,641,954 | 64,642,039 | what's the difference about fib function with template? | here is my code:
template<int x>
struct factorial
{
enum :unsigned long long{ value = x * factorial<x - 1>::value };
};
template<>
struct factorial<1>
{
enum :unsigned long long{ value = 1 };
};
what's the difference between
struct factorial<1>
{
enum :unsigned long long{ value = 1 };
};
and
struct facto... | If you don't provide specialization for factorial<0>, it would take definition of primary template, so to instantiate factorial<0>; you have to compute:
0 * factorial<0 - 1>::value;
which will also have to compute factorial<-1>::value, so factorial<-2>::value and so on...
Once in happen at factorial<-1024>, limit of y... |
64,642,024 | 64,642,156 | Static polymorphism with constant template | I'd like to have a static polymorphism with the parent class having a template std::array size. This code works fine:
#include <iostream>
#include <array>
using namespace std;
template <size_t size>
class Message
{
public:
size_t GetSize() { return size; }
private:
std::array<uint8_t, size> data_{};
};
c... | If you're fine with one extra layer of indirection, then you can use a "traits class" kind of solution:
#include <array>
#include <cstdint>
template <class T> struct MessageSize;
template <std::size_t size>
class Message {
public:
std::size_t GetSize() { return size; }
private:
std::array<std::uint8_t, s... |
64,642,216 | 64,643,626 | Best practice for initializing Winsock in a networking library | I'm writing a small library that internally does some networking using the OS socket API.
On Windows it is required to initialize the Winsock by calling WSAStartup at the beginning and WSACleanup at the end. However documentation says it is allowed to initialize Winsock multiple times and then cleanup same number of ti... |
Is it a good practice for a library to do this secretly?
I may be missing the point here, but to me the point of any library is to abstract the details away from the end-user, making using it hassle-free. Of course, abstraction may somewhat limit flexibility, but I don't feel like this is the case here. Note, that I'... |
64,642,525 | 64,642,724 | Is it legal for a pointer to point to a C++ register? | Let's say a C++ compiler compiled code for an architecture where CPU registers are not memory-mapped. And also let's say that same compiler reserved some pointer values for CPU registers.
For example, if the compiler, for whatever reason (optimization reasons for example), uses register allocation for a variable (not t... |
Is it legal for a pointer to point to C++ register?
Yes.
Would that compiler be considered standard-compliant?
Sure.
C++ is not aware of "registers", whatever that is. Pointers point to objects (and functions), not to "memory locations". The standard describes the behavior of the program and not how to implement it... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.