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,445,812 | 67,446,110 | How do arrays store strings in memory for C++? | To access any random index in array, we access the following memory location :
a[i] = base address + (size of data_type) * i
This is the reason why arrays have only same type of data.
Now this works perfectly fine when we're working with primitive data types like int, char etc.
However, let's say I have an array of str... | I'd say string memory layout is implementation dependent but you should generally have something like 15 bytes (for short string implementation) plus a pointer (for larger strings). So an array of std::string would be a fixed-size, contiguous array of strings (each 15 bytes plus the size of the pointer in my example, u... |
67,445,887 | 67,445,986 | C++ after delete pointer | After deleting ptr, does cout << ptr print the address of int(6)?
If so, why is it garbled? I remember that delete only releases the data in the specified space, isn't it?
And I would like to ask when the delete releases space data here, is it only to release 6 or even the int type?
int* ptr = new int(6);
cout << "Addr... | int* ptr = new int(6); reserves some memory where ptr will be pointing to, that memory will be good to store one int, 6 or any other, it cannot be used to do anything else, you can reliably store the data there and access it later.
After you delete it you tell the system that the memory is available and the program can... |
67,445,955 | 67,447,835 | Boost can not find nested nodes in INI file | I have an ini file like this;
[Sensor]
address=69
mode=1
[Sensor.Offsets]
x=65.0
y=-66.3
I am trying to load the values in an struct:
#include <iostream>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <spdlog/spdlog.h>
void myFunc() {
using namesp... | You need to "escape" the dot. Dots are special, so your key is interpreted as [Sensor][Offsets][x], not [Sensor.Offsets][x].
You can force it:
auto& so = pt.get_child({"Sensor.Offsets", '#'});
x = so.get<double>("x");
Which is shorthand for
auto& so = pt.get_child(
boost::property_tree::ptree::path_type{"Sensor.Of... |
67,446,328 | 67,446,486 | How to get the data type of a std::any variable? | std::any var = 1;
How can you get the type of var?
For example:
std::cout << GetTypeOf(var) << std::endl;
Output:
int
| std::cout << var.type().name() << std::endl;
Godbolt example
Note that the exact output of name() is implementation-defined, so you may get i instead of int for example.
|
67,446,697 | 67,473,366 | How can I calculate the direction vector to steer away from nearby agents | So I am trying to make a boids simulation. I am trying to implement the first rule which is that each boid must steer away from nearby boids. I have all boids in a std::vector called boids. Each boids has a std::vector called withinSensoryRange which holds all boids which are within the boids sensory range. The way I w... | After a few days of struggle I finally got it working. I got the idea from this paper. Particularly this sentence:
Each boid considers its distance to other flock mates in
its neighborhood and applies a repulsive force in the
opposite direction, scaled by the inverse of the distance.
The code bellow does exactly what t... |
67,447,172 | 67,447,557 | why the c++ map changes the content position? | I am trying to understand why the map changes the first element position to the fourth. When I print the map, the first added position goes to the fourth one.
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <iostream>
typedef std::map<double, unsigned int> A;
double fRand(double fMin, double fMax)
{
... | std::map does manage the ordering of the elements according to the keys <, or a custom comparator. Thats actually the main feature of a std::map. If you don't want that then don't use a std::map. If you want to keep the elements in order of insertion you could use a std::vector< std::pair< double, unsigned int>> instea... |
67,447,571 | 67,493,954 | Is there posibility to insert binary file as resource to VS project with cmake? | I try to build exe which will be show static bmp image compiled into exe. But I can't to do this because preprocessor doesn't find definition of the file in follow winapi code:
case WM_PAINT :
hDC = BeginPaint(hWnd, &PaintStruct);
hBitmap = LoadImage(NULL, MAKEINTRESOURCE(IDI_SPLASH), IMAGE_BITMAP, 0, 0... | According to IInspectable answer I've added resource.h with:
#define IDI_SPLASH 101 //or other number id.
This header I've included in source file (.cpp) and resource.rc. Include command in the resource file is same as in the source file:
#include "resource.h"
IDI_SPLASH BITMAP "sample.bmp"
It works :)
|
67,447,724 | 67,448,481 | Building CUDA extension fails even after issue in code (deprecated AT_CHECK) is fixed | I'm trying to install neural_renderer. Unfortunately, the original implementation only supports Python 2.7+ and PyTorch 0.4.0, so I'm using a fork that includes some fixes for compatibility with torch 1.7 (here). The main issue was using AT_CHECK(), which was not compatible with newer versions of PyTorch, and was repla... | If you want to install the fork, you cannot use pip install neural_renderer_pytorch. This command installs the original one.
To install the fork, you have to clone it to your local machine and install it:
git clone https://github.com/ZhengZerong/neural_renderer
cd neural_renderer
pip install .
You can do it in just on... |
67,447,959 | 67,448,002 | c++ void function as parameter for other function | I do not understand why this code that uses int functions and parameters works correctly, but this other code with void functions and without parameters does not:
First:
#include <iostream>
int Add(int x, int y)
{
return x+y;
}
int operation(int x, int y, int (*function)(int, int))
{
return function(x, y);
}
in... | In your first example, you should not need to take the address of Add(). Passing a function by name, without parameters, will automatically take the address.
std::cout << operation(1, 4, Add) << std::endl;
In your second example, you have forgotten the brackets in the function pointer:
void b(void (*function)(/* these... |
67,449,074 | 67,449,823 | Can I include a headerfile in a namespace? | I am using the <conio.h> header file, and somewhere else in my source code I define a function with the name getch and it has to have that name. Since there already is a getch in <conio.h>, and this header file declares all of its functions in the global namespace, I get a name collision.
I found that using the followi... | System header files like <conio.h> which are intended to be used in both C and C++ will enclose their declarations in an extern C scope, forcing C linkage for all that is contained in them, regardless of whatever additional C++ namespaces you add. That’s why your code compiles in this case.
See also this, which is almo... |
67,449,299 | 67,462,205 | Exclusive access to dynamic shared data | I'm looking for the best way to ensure exclusive access to dynamic shared data, where:
"dynamic" means that data (instances of some class) will be dynamically created and deleted throughout the application lifetime. It must be possible to do so safely without causing undefined behaviour or accessing invalid memory.
"e... | Simply:
have a mutex associated with each object,
keep each object in a smart pointer,
keep smart pointers in some concurrent map (e.g. Intel's TBB one).
Usage:
someone gets the pointer from the map (safe),
while holding a smart pointer reference to the object tries to lock the mutex (safe),
uses the object and subs... |
67,449,789 | 67,449,992 | How to make span of spans | C++20 std::span is a very nice interface to program against. But there doesn't seem to be an easy way to have a span of spans. Here's what I am trying to do:
#include <iostream>
#include <span>
#include <string>
#include <vector>
void print(std::span<std::span<wchar_t>> matrix) {
for (auto const& str : matrix) {
... | Why not use a concept instead?
#include <iostream>
#include <string>
#include <vector>
#include <ranges>
template <class R, class T>
concept Matrix =
std::convertible_to<
std::ranges::range_reference_t<std::ranges::range_reference_t<R>>,
T>;
void print(Matrix<wchar_t> auto const& matrix) {
fo... |
67,449,930 | 67,450,677 | C++ doing comparison from curl | I'm really new to C++ I'm trying to do a comparison from a curl request but my problem is that my program always print the body and doesn't enter in the if statement I already searched but since I'm new to C++ I don't know what I must search exactly
#define CURL_STATICLIB
#include <iostream>
#include "curl/curl.h"
#inc... | To help you, here is an example of a working curl program (it requests a random number page from https://www.random.org/):
#include <stdio.h>
#include <curl/curl.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
size_t write_data(void* ptr, size_t size, size_t nmemb, std::string* data)... |
67,450,057 | 67,450,245 | Veryfing that concrete types of polymorphic vector elements are the same | I have got a abstract base class Type which has multiple concrete child classes like Type_bool, Type_int, Type_double etc. Furthermore I construct two vectors of type std::vector<Type*> holding objects of the concrete child classes.
I have implemented the following method to check whether these vectors are the same. In... | Consider the code...
Type_int *a, *b;
Type_bool* c;
std::vector<Type*> arguments = {a, b};
std::vector<Type*> arguments2 = {a, c};
The pointers a, b, and c are uninitialized. So when you dereference them in Env::areArgsTheSame you invoke undefined behaviour which (in this case at least) results in a seg fault.
Your ... |
67,450,597 | 67,450,963 | Recursive variants and destruction on incomplete types | I'm trying to build an AST based on std::variant (I know there are other ways to do this, but I'm specifically interested in an approach around union types). I have two expression concepts
LeafExpression
RecursiveExpression
which I need in order to be able to use std::variant (because it doesn't allow recursive types... | Add a ~ and copy/move ctor and assign. Then default them after everything is defined.
You may also want to make Expr be a thin wrapper around variant, so you can forward declare it.
|
67,450,612 | 67,450,726 | "this" pointer in parameterized constructor points to another address than from outside | I have the following code:
#include <iostream>
class Entity {
public:
int x;
int y;
Entity() {
std::cout << "Default contructor: " << this << std::endl;
}
Entity(int x, int y) {
this->x = x;
this->y = y;
std::cout << "Constructor with parameter: " << this << std:... |
Why is the address in the main fuction the same as the address in the default constructor?
Because e is the same object, always. You cannot move it in memory or anything like that. It will occupy the same memory spot until it dies.
What you are using in e = Entity(10, 20); is called move assignment operator. Note tha... |
67,450,761 | 67,450,802 | STL container find_or_create() | Is there some sort of STL facility for doing a find_or_create() on STL containers?
E.g. in the case of unordered_map, I frequently find myself needing to retrieve some value and create it if no value exists. There are plenty of functions for conditionally inserting into a map, but all of them result in creating a new v... | try_emplace is what you want. Your problem is that you are deliberately constructing an A, instead of passing the arguments to the constructor, which it may or may not use to construct the A.
What you want is this:
auto &val4 = *m.try_emplace(0, "try_emplace").first;
Your find-or-create function would be useful if you... |
67,451,142 | 67,451,906 | How Do I Box Disparate "Resource" Pointers for SDL2? | I want to implement a resource loader, and conceptually, it feels like all the resources in SDL2 are the same; you need to free the resource when finished, SDL_Texture* with SDL_DestroyTexture, Mix_Music* with Mix_FreeMusic, Mix_Chunk* with Mix_FreeChunk, TTF_Font* with TTF_CloseFont. All that changes is the name of th... | dynamic_cast only makes sense when you're casting to a polymorphic type (or void*), from a polymorphic type. A polymorphic type is a class (or a struct, which is formally also a class) that has (possibly inherits) at least one virtual function.
None of the types you listed are polymorphic (because they come from C libr... |
67,451,266 | 67,451,708 | Why is D3DXQuaternionToAxisAngle being called in the following code? | I am attempting to convert some code over to glm/opengl that was originally using direct3d, and have run into a block that does not make sense according to what I found in the documentation on microsoft's website. The block in question is detailed in comments below:
Gx::Quaternion Gx::Quaternion::rotationBetween(const ... | As you note, the code in the the first if case is broken. They may have meant to use D3DXQuaternionRotationAxis which has the same signature.
As a reminder, these are 'D3DXMath' functions which were in the now deprecated D3DX9/D3DX10 utility libraries. The modern solution is DirectXMath. There's a list of D3DXMath equ... |
67,451,271 | 67,451,310 | How do I get the command line option for my Win32 C/C++ program? | I have a C/C++ winapi program that I'd like to extend a command line functionality to (which I've seen done in C#, but never C++). If the executable is opened with no arguments, it opens the window as normal, but when called from a command line with arguments such as an input or output file, the window does not open an... | There is LPSTR lpCmdLine parameter in WinMain. You can use CommandLineToArgvW function to parse lpCmdLine. When necessary parameters exist, you will not create or show program window and do the job.
|
67,451,295 | 67,452,848 | How to convert Text to Binary (and Reverse) in C++? | Okay, this will be a very beginner question, Though I can´t seem to find a good resource on this topic.
What I want is simple. take a string (or char*) and convert it to a binary file that I can store somewhere on my system.
Then, at a later date, I want to be able to read that binary file and convert it back to a str... |
How to convert Text to Binary (and Reverse)
There's nothing to do. Text is already data, and the in-memory presentation of all data in any modern computer is always binary.
You need to know what you mean. If you just mean "write it to a file" (in any representation), then just do that:
std::string my_text;
std::ofstr... |
67,451,490 | 67,452,294 | Cannot compile variant visitor access on MSVC 19.28 | I try to compile a personal project on Visual Studio 2019 (using MSVC 19.28 compiler) and I came accross a compilation error in the std::visit which I don't understand:
<source>(131): error C2653: '`global namespace'': is not a class or namespace name
C:/data/msvc/14.28.29914/include\type_traits(1493): note: see refer... | It seems MSVC is having difficulty synthesizing a lambda with a pointer-to-member argument in a template context.
I tried to simplify it to a MCVE, hopefully it captures the essence of the issue:
template<class T>
bool test(int T::* t) {
return [](int T::* x) {
return true;
}(t);
}
struct A {
int a... |
67,451,924 | 67,451,938 | Why does using string instead of auto fix this error? | When I run the code below, it gives this error:
error: request for member 'length' in 'st', which is of non-class type 'const char*'
cout << st.length ();
However if I used string instead of auto It runs without errors
#include <iostream>
using namespace std;
int main()
{
auto st="hello" ;
cout << st.l... | "hello", being a string literal, is of type const char*, not std::string.
When you do this:
auto st = "hello";
The type of st is deduced as const char*, not std::string.
When you do this instead:
string st = "hello";
It invokes std::string's constructor that takes in a const char* pointer, which will copy the chars f... |
67,451,951 | 67,452,031 | How to use pointers to figure out if a c-string ends with another c-string? | So for my assignment, I have to complete the function endsWith which returns true if s1 ends with s2 (both cstrings)
Example: "sailboat", "boat" -> true
Example: "mississipii", "pie" -> false
I already successfully did the program startsWith, which returns true if s1 starts with s2
bool startsWith(const char* s1, const... | You tagged your question as C++, but your code technically suggests "C", which is fine with me.
A "C" solution
// returns true if "s2" ends with "s1"
// examples s1="World" and s2="Hello World" => returns true
// examples s1="Hello" and s2="Hello World" => returns false
bool endsWith(const char* s1, const char* s2)
{
... |
67,451,963 | 67,452,480 | What is the difference between vector<vector<int> > v and vector <int>* v in memory allocation? | I use these two types of two-dimensional vector to load a graph.
In the first case I use vector<vector<int> > v to load the graph adjacency matrix, and in the second case I use vector <int>* vto do so, when I initialize it with vector <int>* v = new vector <int>[n].(n is the number of vetices).
It appeared on the offi... | vector<vector<int> > v(n) is a single vector internally holding a pointer to an array of n vector<int> elements.
vector <int>* v = new vector <int>[n] is a pointer to an array of n vector<int> elements.
In that regard, they are virtually identical, just that the 1st one manages the array for you and will free it automa... |
67,451,992 | 67,452,240 | Aligned allocation of elements in vector | I need to have elements in a std::vector aligned to some given step in memory. For example, in the program as follows:
#include <vector>
#include <iostream>
struct __attribute__((aligned(256))) A
{
};
int main()
{
std::vector<A> as(10);
std::cout << &as[0] << std::endl;
std::cout << &as[1] << std::endl;
}... |
In practice, I see that it is true in Visual Studio 2019, and in gcc 8+. But can I be absolutely sure, or is it just a coincidence and some custom allocator in std::vector (like boost::alignment::aligned_allocator) is necessary?
There is no reason to expect that, provided the absence of bugs in the implementation of ... |
67,452,122 | 67,452,244 | What are the use cases of C++20 Concepts? | I found about Concepts while reviewing C++20 features. I found that they add validation to templates arguments but apart from that I don't understand what are the real world use cases of C++20 concepts.
C++ already has things like std::is_integral and they can perform validation very well.
I'm sure I am missing someth... | SFINAE (see here & here) was an accidentally Turing complete sublanguage that executes at overload resolution and template specialization selection time.
Turns out it is used a lot in template code.
Concepts and requires clauses are an attempt to take that accidentally useful language feature and make it suck less.
The... |
67,452,787 | 68,261,249 | My program will not open text file. Ofstream CPP | I'm currently new to C++ and I've been watching a tutorial series https://www.youtube.com/watch?v=_bYFu9mBnr4, but I'm having a big issue. My C++ code will not open a file no matter what I do, I've looked online and tried renaming it, the full path, everything I can think of. Here's my code,
#include <iostream>
#includ... | Sorry about this question, it may have been a dumb issue. Turns out IT WAS my antivirus. Avast kept blocking it, it was just looking out for me. I decided to change my antivirus afterwards and it now works fine!
|
67,453,176 | 67,458,586 | Char sequence from string at compile time WITHOUT recursion | Yes, this topic may look as asked already a hundred times, but what I am asking is very different.
Please, don't let me be misunderstood: template recursion can be great and the only way for some idioms when used in C++03, but the problem may arise when using in MSVS 2017/2019 compiler and getting the dreadful fatal e... |
I wonder if there is some way to replicate the behaviour of BOOST_HANA_STRING macro (basically it takes a string and converts it into a char sequence, or wchar depending of input string) but getting rid of recursion.
Well, that's going to be difficult as BOOST_HANA_STRING doesn't use recursion:
namespace string_d... |
67,453,253 | 67,453,332 | Unable to use Precompiled headers in visual studio | I've seen several questions discussing this topic but none of their solutions seems to apply here. I have several libraries that I don't wont to be compiled every time I build the project so I've created "b5pch.h" and b5pch.cpp" files.
//b5pch.h
#pragma once
#include <iostream>
#include <memory>
#include <utility>
#in... | Okay I've fixed the problem. when I was including b5pch.h in my cpp files I was doing it like this:
#include ../b5pch.h since they were in different directories.
When I moved pch files in same directory and I just wrote #include b5pch.h there were no more errors. I didn't wanted them to be in same folder so I've moved ... |
67,453,324 | 67,453,339 | simple c++ code not working in visual studio | #include<iostream>
#include<windows.h>
using namespace std;
int main()
{
HWND hwnd = FindWindowA(NULL, "Terraria Part 3: The Return of the Guide");
if (hwnd == NULL)
(
cout << "cannot find window." << endl;
Sleep(3000);
exit(-1);
)
return 0;
}
I wrote
this exactly li... | Your if statement has bad syntax. Change the if statement from..
if (hwnd == NULL)
(
cout << "cannot find window." << endl;
Sleep(3000);
exit(-1);
)
to...
if (hwnd == NULL)
{ // <-- specifically these
cout << "cannot find window." << endl;
Sleep(3000);
exit(-... |
67,453,334 | 67,453,406 | How to overload "delete" operator in C++ to print the line and name of the file where it is used? | I'm trying to overload "delete" operator to print in console the line number and name of the file where it is used. I tried the following:
#include <iostream>
void operator delete(void* adress, char* file, int line) {
printf("%s: line %d -> ", file, line);
delete(adress);
}
#define delete delete(__FILE__, __L... | This is a very dirty solution, but maybe can help for your specific case:
#define delete cout << __FILE__ << " " << __LINE__ << endl, delete
However, there is a very strong limitation: It will not work if a function is declared as = delete
class SomeClass
{
...
void fn() = delete; // This will not compile
...
}... |
67,453,621 | 67,453,853 | "Error: Permission denied" while trying to edit txt file C++ | I'm fairly new to C++ and currently I"m getting a really weird error, telling me that permission is denied I've tried changing the permissions of it in the properties. I've tried disabling my antivirus, and I've even restarted my PC. Nothing I've done seems to be working to fix it. Here's the code.
#include <iostream>
... | From this source, they claim to have a similar problem also using window 10. All replies here point to a security feature not letting .exe programs to write to files. This is obviously a malware protection thing. The sure solution is to find a way to disable this. But your case seems to be a little different than this ... |
67,453,677 | 67,453,690 | Compilation Error in overloading operator | Not able to understand why getting error
error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream’} and ‘MyStruct’)
cout << st;
in the below code
#include <iostream>
using namespace std;
struct MyStruct
{
int a;
string b;
double c;
MyStruct(int a, string b, doubl... | The correct signature for the operator is:
friend ostream& operator<<(ostream& os, const MyStruct& dt);
Right now your output stream operator is only overloaded in a way that allows st << cout.
|
67,453,732 | 67,454,758 | How to check in compile time that the function has default parameter value? | All try to do is to make this piece of code
int main() {
if constexpr( ??? ) {
std::cout << "Yes\n";
std::cout << f() << '\n';
std::cout << f(42) << '\n';
}
else {
std::cout << "No\n";
}
return 0;
}
compile if the function f is defined as in any of these examp... | if constexpr can’t protect ill-formed code outside of any template (e.g., in main). The obvious thing to do is to write a template that accepts f itself as a template argument, but to do that you have to reify your overload set. The usual way to do that is as a SFINAE-friendly function object:
template<class F,class=... |
67,454,294 | 67,454,385 | LeetCode question. Two Sum linked list version C++ | I'm doing LeetCode problem 2 Add Two Numbers. The description is:
You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order, and each of their
nodes contains a single digit. Add the two numbers and return the sum
as a linked list.
You may assume the two num... | Your loop condition is not quite correct, it should be something like:
ListNode *r = nullptr;
ListNode **curr = &r;
bool carry = false;
while( l1 || l2 || carry ) {
int v = carry;
if( l1 ) {
v += l1->val;
l1 = l1->next;
}
if( l2 ) {
v += l2->val;
l2 = ;2->next;
}
... |
67,454,419 | 67,454,512 | cleanup (with delete) in a thread fails | Why using delete in a thread fails, but not if called synchronously ?
class dummyclass{};
main()
{
vector<dummyclass*> testlist{};
for(int i=0; i<5; i++)
{
auto value = new dummyclass();
testlist.push_back(value);
}
thread cleanuptest([&]() {for (auto x : testlist) delete x;}); // f... | The problem with your program is that your main() function exits before the cleanuptest() thread has a chance to run to completion, taking the testlist object with it. So when cleanuptest() runs, it will likely be trying to access a vector that has already been destroyed (or is in the process of being destroyed, depen... |
67,454,500 | 67,454,534 | Alternate letters in upper case | As the below code should convert the given String into alternative upper or lower case.A string S (only alphabets) is passed as input. The printed output should contain alphabets in odd positions in each word in uppercase and alphabets in even positions in each word in lowercase.
#include <stdio.h>
#include <string.h>... | scanf("%s, str) reads in a string until the first whitespace character. So when you type "tree gives us fruits" it reads in "tree" and then see's the whitespace and stops.
Try using fgets(str, 100, stdin) instead
https://www.cplusplus.com/reference/cstdio/fgets/
|
67,454,656 | 67,455,201 | Delete node at nth position from doubly linked list recursively? (C++) | I have been trying to practice a bit with some algorithms and in my code for a doubly linked list, I want to be able to delete a node at nth position recursively. I have tried doing this on my own but I cannot seem to find an effective way of doing so with recursion. If someone could possibly help me out in doing so th... | To delete nth node from a doubly linked list recursively :
Maintain a counter
If counter is less than position of node to be delete then
Increment the counter and recursive call the delete function and pass the next of current processing node in the list.
Assign the return value of delete function to next pointer of ... |
67,455,135 | 67,456,496 | [NDK_PROJECT_PATH=null]. Not able to resolve Android-NDK error from a sample project related to PARALLEL-SPACE | Error Logs
External native generate JSON release: executing ndkBuild Executable :
/Users/nidhinagvanshi/Library/Android/sdk/ndk/20.0.5594570/ndk-build
arguments : NDK_PROJECT_PATH=null
APP_BUILD_SCRIPT=/Users/nidhinagvanshi/Downloads/VirtualApp-master-2/VirtualApp/lib/src/main/jni/Android.mk
NDK_APPLICATION_MK=/Users... | I resolved this error by downgrading NDK. The following line was changed in local.properties:
ndk.dir=/Users/nidhinagvanshi/Library/Android/sdk/ndk/17.2.4988734
|
67,455,322 | 67,456,636 | random prime number generator over one million is only giving prime numbers half the time | I wish to find a random prime number over one million but my program only outputs one maybe half the time.
When it doesn't it will just output nothing.
unsigned long long int primeFinder(unsigned long long int base) {
int flag = 0;
unsigned long long int m = base / 2;
for (int i = 2; i <= m; i++) {
... | The main problem is that you do not ensure that your starting point is an odd number. Since you recursively call primeFinder() incrementing the "base" by two, this will result in endless recursion when the starting point is an even number, i.e. about half the time.
An easy way to fix this is to change the initial call ... |
67,455,350 | 67,456,257 | STL priority_queue push function adds an entire Linked List ( vector<ListNode*>& lists ), instead of one element | I am learning C++ out of my own interest.
I have come across a situation that i can not logically understand.
I am trying to solve this problem : https://leetcode.com/problems/merge-k-sorted-lists/ , with the help of Min Heap. I am using priority queue as a min heap.
Now my code looks something like this :
ListNode* m... | With that kind of Node data structure, the reference to your first node is also the reference to your linked list, because the first node has next pointing to the second, then next->next will be pointing to the third... etc. So it is behaving as expected.
Current behaviour
After the execution of the for loop, you will ... |
67,455,370 | 67,455,417 | matrix class template,the multiplication or addition of different types of matrices | I am writing a matrix class template. I want to implement the multiplication or addition of different types of matrices( for example, between real and imaginary matrices ), but I cannot access the data members of another type of matrix. How should I solve this problem?
template <class Type>
class Matrix
{
Type** p_... | You can use a friend declaration
template <typename T>
class Matrix
{
template <typename U>
friend class Matrix;
// ...
};
|
67,455,864 | 67,456,099 | Defining a bool in Qt pro file | Setting a boolean value for a variable in .pro file can be done the following way:
//ProjectFile.pro
DEFINES += "myBool=1"
This variable can be used in source code *.cpp for conditional compiling. Qt even highlights the conditional expression:
Now Iam looking for a way to use that myBool variable in .pro file
Acco... | Out of curiosity, I researched a bit…
First, I consulted qmake Manual > Advanced Usage but that didn't help much.
Then I tried to find something with google and found the following two Q/As (among others):
SO: qmake: using defines as conditionals
SO: SO: QMake appending to DEFINE without respecting conditional.
I com... |
67,455,915 | 68,935,145 | Always scroll a full line in QTextEdit | I have a QTextEdit with many lines and a vertical scrollbar. I want the vertical scrolling to always scroll full lines (as for example Windows Notepad does).
Right now, it has the default behavior of scrolling by pixels and not lines, so it's possible to scroll into the middle of a line for example, which I don't want ... | I'll answer my own question as I managed to solve it, at least for my usecase.
It turns out this is exactly what QPlainTextEdit was meant to do, so switching to it from QTextEdit was all that was needed.
|
67,456,235 | 67,456,345 | Why does the C++ standard not change std::set to use std::less<> as its default template argument? | #include <set>
#include <string>
#include <string_view>
using namespace std::literals;
int main()
{
auto v1 = std::set<std::string, std::less<>>{"abc"s};
v1.contains("abc"s); // ok
v1.contains("abc"sv); // ok
auto v2 = std::set{"abc"s};
v2.contains("abc"s); // ok
v2.contains("abc"sv); /... | My guess is because they thought it wasn't so great improvement to break backward compatibility.
Another reason is because std::set with std::less<Key> existed even before C++11 (starting from C++03 I guess) and std::less<> appeared only in C++14. So if they move to std::set with std::less<> then you have to force C++1... |
67,456,501 | 67,456,635 | How to define function with arbitrary precision (Eigen/MPRealSupport) | How to define Matrix<mpreal, Dynamic, Dynamic> with typedef?
We usually put the defined type in a header file, but it needs mpreal::set_default_prec(256); and that's the problem.
I am quite new to MPFR, so my apology if it seems easy.
So what is your idea?
#include <Eigen/LU>
#include <iostream>
#include <Eigen/Dense>
... | mpreal (attention, it is located inside a namespace mpfr) is a class and set_default_prec is a static method. This means that setting the precision has no effect on the template parameter and therefore also not on the typedef. Calling the static function will change the default precision only internally without having ... |
67,456,624 | 67,456,837 | Is this function casting safe? | This is standard Arduino library. On line 92 https://github.com/arduino/ArduinoCore-megaavr/blob/master/cores/arduino/WInterrupts.cpp the user supplied function void(*)(void) is cast into void(*)(void *) (voidFuncPtrParam is void(*)(void *))
How does this work? On line 138, the user supplied function is always called ... |
Is this function casting safe?
The cast itself is always safe. You can always cast function pointer to any function type.
The call at WInterrupts.cpp#L138) is indeed undefined behavior, as it calls void (void) function via void (void*) pointer.
How does this work?
The code was written specifically for megaavr to be... |
67,457,346 | 67,457,988 | Problem in allocating memory and set value to a refrence variable in c++ file body (Not in function) | I am new in c and c++. I want to allocate memory and set a value to a pointer in my c++ file body so it will execute only once.
Here is my code:
myFile.h:
struct SelectedRows_t {
uint32_t rowsLen;
SelectData_t* rows[];
};
extern SelectedRows_t* selectedRows;
myFile.cpp
SelectedRows_t* selectedRows = (SelectedRow... | I solved the problem by using a function to do all my works in it and return the pointer to the final SelectedRows_t:
SelectedRows_t* createSelectedRows() {
SelectedRows_t* selectedRowsTemp = (SelectedRows_t*)malloc(sizeof(selectedRows->rowsLen));
selectedRowsTemp->rowsLen=0;
return selectedRowsTemp;
}
SelectedR... |
67,457,410 | 67,457,665 | QLineEdit.text() function makes my program crash, but only when it's in a slot | quick Explanation, im still in HS and trying to put together a little project, basically its some kind of messenger app using our school's servers.
Of course, for that, you need a login window, with account management and stuff. The account management part is already done, leaving only the part where i put everything t... | It crash's cause of segmentation fault.
you didn't assign an address for this two QLineEdits.
what you actually did in constructor is defining another QLineEdit m_nickname and m_password and your class member variable did not locate in memmory
change your constructor where you define these QLineEdits like this:
instead... |
67,457,725 | 67,457,764 | Difference between int i(x); and int i = x; | I have been practicing C++ in HackerRank. There I was seeing different submissions and something new came in my sight.
someone used int i(0) in for loop like
for (int i(0), mark; i<q; ++i)
So my question is :
what is Difference between int i(x); and int i = x;? (where x is type of int defined in initialized before t... | The answer is essentially here.
int i(x); is direct initialization which
Initializes an object from explicit set of constructor arguments.
whereas int i = x; is copy initialization, which
Initializes an object from another object
(The following is probably irrelevant for int, so take it as comment about the differe... |
67,457,738 | 67,457,810 | What does "%.7le " in printf means? | What does
fprintf(fp, "%.7le ", data);
means?
I don't know what "%.7le " is mean.
Thanks!
| .7 is the precision and le means normal form.
double x = 0.012345678910;
printf("%.7lf\n", x); // 0.0123457
printf("%.7le\n", x); // 1.2345679e-02
printf("%.9le\n", x); // 1.234567891e-02
Edit
See Eric Postpischil's unswer below, it's way more comprehensive than this one.
|
67,457,753 | 67,457,881 | Why does my code for Ptice hit runtime error? | I am new to programming and I want to learn as much as I can.
I am working on problem Ptice on Kattis (Link to problem).
The problem in my programming journey now is that I create code I think works but when I pass it through Kattis it rejects my solutions halfway etc. Code below passes 3 out of 19 test cases. (on 4th ... | Your answer sequences for the three people are each 12 characters long.
If the input string is 12 characters or less, that's fine.
But if the input string is 13 or more characters long (it can be up to 100 characters, as stated in the competition text), the line
if (inputSequence.at(i) == Adrian.at(i))
compares the in... |
67,458,102 | 67,458,205 | User defined type trait gives an unexpected false type | Printing string that contains type info:
std::string demangle(const char* mangled_name) {
size_t len = 0;
int status = 0;
std::unique_ptr<char, decltype(&std::free)> pointer (
__cxxabiv1::__cxa_demangle(mangled_name, nullptr, &len, &status),
&std::free);
return ... | This did the trick for me:
int main()
{
std::cout << is_string_v<char const[sizeof "Hello"]> << '\n';
std::cout << is_string_v<std::remove_reference_t<decltype("Hello")>> << '\n';
}
Output:
1
1
Looks like decltype added an extra reference. Taken from this answer:
The type denoted by decltype(e) is defined as... |
67,458,450 | 67,458,574 | How can I convert my heap sort program to use C++ standard containers (for example std::vector)? | I know how to code with C, however, this is my first time I try to use C++. And the use of VLAs(Variable Length Arrays) is not allowed in C++. So how can I convert this program to use C++ standard containers( for example std::vector) for the same instead of going the C route?
Instead of int arr[n]; in main(), use std::... |
And the use of VLAs(Variable Length Arrays) is not allowed in C++
I've just compiled your code in C++ and it works perfectly fine. Feel free to rephrase if you think I misunderstood you.
If you want to stick to arrays instead of std::vector you can use std::array. Otherwise in your case it would be mostly swapping in... |
67,458,615 | 67,458,658 | ‘structure was padded due to alignment specifier’ VS warning | If in Visual Studio I specify alignment for a class or structure, e.g.
struct __declspec(align(256)) A
{
};
I get level 4 warning as follows ‘warning C4324: 'A': structure was padded due to alignment specifier’.
Do I specify alignment somehow incorrectly or this warning is just safe to ignore?
|
Do I specify alignment somehow incorrectly
No, although you are using a language extension. That may be unnecessary as there is a standard syntax that would be preferable:
struct alignas(256) A
{
};
This warning is just safe to ignore?
Yes, it is safe to ignore this warning, unless you have areason to consider the... |
67,458,732 | 67,945,432 | Correct usage of modulo operator's in C++ | I am trying to teach myself c++.
On Sololearn I have a task, which is
You are making a program for a bus service.
A bus can transport 50 passengers at once.
Given the number of passengers waiting in the bus station as input, you need to calculate and output how many empty seats the last bus will have.
Sample Input: 12... | First you have to get the number of passengers
int passengers; cin >> passengers;
then you have to find how many passengers are left
int remainPass = passengers % 50;
then you have to find how many seats are left
int remainSeats = 50 - remainPass;
|
67,458,745 | 67,473,698 | OpenACC nvlink undefined reference to class | I am new to OpenACC and I am writing a new program from scratch (I have a fairly good idea what loops will be computationally costly from working in a similar problem before). I am getting an "Undefined reference" from nvlink. From my research, I found this is because no device code is being generated for the class I c... | The problem here is that you're trying to call a device routine, "Vec1::operator*", that's contained in a shared object from a kernel in the main program. nvc++'s OpenACC implementation uses CUDA to target NVIDIA devices. Since CUDA doesn't have a dynamic linker for device code, at least not yet, this isn't supported... |
67,458,829 | 67,460,465 | fitting a gamma variate curve to a set of data points in c++ | I have an array of values (concentration values), with each value taken at a different time point. I need to fit a gamma-variate curve (formula is in the picture below) to these values (i.e. find alpha and beta such that the curve best fits those points - all other variables are known.)
an example of the values i migh... | This is a problem which is not best suitable to solving by ITK. While you could use ITK's Optimizer infrastructure, there are better/simpler choices.
Maybe try NLOpt? Here is an example of how to use it. Also, you could look at this code which fits a polynomial to points in 3D space.
|
67,458,849 | 67,461,334 | Finding an index of element in vector and removing it | I have a loop. If a certain condition is true, I need to add an item to a vector. If it's false instead, I need to remove an item from the vector.
Here is my best attempt at reproducing what I am trying to do:
#include <iterator>
#include <vector>
#include <algorithm>
#include <memory>
struct Arrow
{
std::vector<A... | I second the choice of vector, but since adding and removing items in a loop can be tricky and not so efficient I'd skip the adding and removing thing by starting from an empty container and then just adding, so this doesn't address directly your question but shows how I'd approach your problem. (code not compiled, may... |
67,458,993 | 67,467,105 | Removing extra files generated while creating a dll project in visual studio | While creating a dll project in VS17, I see multiple files were created on initialization.
But whichever project on C++ I work on, I don't see any such files in their environment. How can I get rid of these files in my environment. Is there any workaround to remove them entirely or reduce these 4 files to one file to... | When you create a new project in Visual Studio, a precompiled header file named pch.h is added to the project. (In Visual Studio 2017 and earlier, the file was called stdafx.h.)
For more details about pch.h and stdafx.h, I suggest you could refer to the Doc:
Precompiled Header Files
If you couldn't want to use precompi... |
67,459,020 | 67,459,189 | Error using GCC Intel Assembly: invalid operands (.text and UND sections) for + | I am writing inline assembly and I came across a error that I don't know how to fix.
This part of the code raises an error. It is supposed to add "i" to "source" and "array" addresses, and copy the contents of the byte at "source" to "array".
int main()
{
char* _source = new char [1];
_source[0] = 1;
char* ... | Your use of named operands is wrong in a few ways. Instead of "r" "source" (_source), you should specify the operand as: [source] "r" (_source), where [source] specifies its name, _source is the C variable, and "r" is the constaint to use. And you should access the operand with %[source], not $[source].
|
67,459,837 | 67,460,095 | How to fix this error :pointer being freed was not allocated | I am new here and learning about topics of dynamic memory and linked list. And here is the problem that I have encountered.
void deletenode(Node*& head){
Node* temp = new Node;
temp = head; // I would like to create a new pointer to store the value of head node.
head=head->next; // and here I want to change the head no... | Node* temp = new Node;
This creates a new object in dynamic scope, and sets temp to point to it.
At this point, you can go ahead and delete this object if you wish, and everything will work out at the end. But instead you do this:
temp = head;
This then immediately replaces the temp pointer, and it now points to some... |
67,459,950 | 67,460,064 | Why is a friend function not treated as a member of a namespace of a class it was declared in without additional declaration? | Suppose we have a class foo from a namespace space which declares a friend function named bar, which is later on defined, like so:
namespace space {
struct foo {
friend void bar(foo);
};
}
namespace space {
void bar(foo f) { std::cout << "friend from a namespace\n"; }
}
To my understanding, friend... | There's a slight subtlety that the friend declaration, while it doesn't require a previous declaration of the function or class your class is befriending, does not make the function visible for lookup except via ADL.
cppreference:
A name first declared in a friend declaration within a class or class template X becomes... |
67,460,835 | 67,470,223 | Rich edit control sends EN_CHANGE when spellcheck underline appears | Let's say you've just set some text in a spellcheck-enabled rich edit control, and the text has some spelling errors. A split second will go by, spellcheck will kick in, and then the misspelled text will get underlined. But guess what: the rich edit control will actually send an EN_CHANGE notification just for the und... | because documentation about CHANGENOTIFY ( must contains information that is associated with an EN_CHANGE notification code, but not..) is wrong - only research exist.
in my test i view that EN_CHANGE related to Spellcheck received only when rich edit handle WM_TIMER message. so solution is next - subclass richedit and... |
67,461,198 | 67,461,629 | Getting the number of bytes in a Unicode string | I have a Unicode string and I need to know the number of bytes it uses.
In general, I know that wcslen(s) * 2 will work. But my understanding is that this is not reliable when working with Unicode.
Is there a reliable and performant way to get the number of bytes used by a Unicode string?
| wcslen counts the number of wchar_t entities, until it finds a NUL character. It doesn't interpret the data in any way.
(wcslen(s) + 1) * sizeof(wchar_t) will always, reliably calculate the number of bytes required to store the string s.
|
67,461,291 | 67,468,195 | Making a Bazel genrule that modifies an executable generated by cc_binary | Assuming I have a cc_binary() rule like this:
cc_binary(
name = "App",
srcs = [
"app.cpp",
],
)
This will produce App.exe somewhere in bazel-bin. I need to write a genrule that can read App.exe and produce another version of it. How can I do that?
Edit: this is my current attempt for a genrule, but... | cc_binary(
name = "hello_main",
srcs = ["hello_main.cc"],
deps = [
":hello",
],
)
genrule(
name = "foo",
outs = ["out.txt"],
cmd = "du -sh $(location :hello_main)` > $@",
tools = [":hello_main"],
visibility = ["//visibility:public"],
)
will create a out.txt file with an ou... |
67,461,415 | 67,463,966 | Clang linker does not recognise Linux libraries | I am close to being able to cross compile binaries for Linux on Windows. I have got a command that will compile my code to a .o file, but I am unable to get it to link to produce the binary. Right now it is saying that it can't link to several copies of Linux libraries even though I have a copy of them on my system and... | I believe clang is searching for the gcc C runtime for the environment you are compiling for. You should be able to set the search path for this with the --gcc-toolchain flag.
For example, running the following command works on my machine (in Powershell):
clang --gcc-toolchain=$TOOLCHAIN --sysroot=$TOOLCHAIN\x86_64-lin... |
67,461,724 | 67,461,918 | How can I properly redirect C and C++ I/O to a winapi console handle? | I have a winapi program that I wish to not open any windows if executed with command line arguments. I can attach to the parent console perfectly and WriteConsoleA() works, but when I try to redirect C I/O, std::cout, and std::cin to the console (following the methodology of several StackOverflow posts about this subje... | This should work, but I didn't test it:
void RedirectIOConsole()
{
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONERR$", "w", stderr);
}
|
67,461,770 | 67,461,898 | How to resolve free(): invalid pointer error while assigning multiple variables in a doubly linked list? | C++ newbie here.
I have 2 data variables in my doubly linked list; instr_num and opcode. When I copy a value into instr_num, it works, but throws an error when I do it for opcode.
struct Node {
int instr_num;
std::string opcode;
struct Node* next;
struct Node* prev;
};
void initialize_DLL(Node** tail, ... | In C++, you would use new to initialize the allocated memory:
#include <string>
#include <utility>
struct Node {
int instr_num;
std::string opcode;
Node* next;
Node* prev;
};
void initialize_DLL(Node** tail, Node** head, int s_instr_num,
std::string s_opcode) {
*tail = *head =
new ... |
67,461,892 | 67,461,956 | How I can get values for function? | I'm stuck with c++. I'm new at this, and I'm confused. totalGrade gives the sum of 5 grades received by the student. But I couldn't calculate this total grade. I can't access the values in the array in the function. How to access values in an array
#include<iostream>
using namespace std;
class Student {
public:
... | Your array is local to takeNotes(), so totalGrade() can't access it. You need to make the array be a data member of the Student class instead, eg:
#include<iostream>
using namespace std;
class Student {
private:
int nA1[5];
public:
void takeNotes(){
for (int i = 0; i < 5; i++){
cin >> nA1[... |
67,461,917 | 67,468,409 | Decide which template to instantiate based on which concept is satisfied | Let's say I have 2 concepts:
struct Vector3 {float x; float y; float z;};
template<typename T> concept ImplementsMeshGetters = requires(T a, uint index)
{
{ a.Position(index) }->std::convertible_to<Vector3>;
};
template<typename T> concept HasMeshMemberArrays = requires(T a, uint index)
{
{ a.positions[index]... | In C++20 you can define constrained member functions:
template <typename MeshType>
class Mesh {
public:
Vector3 GetPosition(uint i) requires ImplementsMeshGetters<MeshType> {
return mesh.Position(i);
}
Vector3 GetPosition(uint i) requires HasMeshMemberArrays<MeshType> {
return mesh.positions[i];
}
priva... |
67,462,117 | 67,462,252 | parameter packs parameter type | I have modified the sample from https://en.cppreference.com/w/cpp/language/parameter_pack to save the string in a variable. My code
#include <string>
void tprintf(std::string& str, const std::string& format)
{
str += format;
}
template <typename T, typename... Targs>
void tprintf(std::string& str, const std::st... |
tprintf(std::string&, const std::string&, std::string, int) <- arg is
std::string
Correct, therefore, here:
str += std::to_string(arg);
arg is a std::string, and there is no such std::to_string overload.
No matter what type T is, the resulting template must be valid C++ code. Even if the corresponding formatting ch... |
67,462,137 | 67,462,696 | Why does this HTTP response stream yield a parsing error? | I sent an HTTP response to the socket in segments, but when testing with Postman, Postman fails to parse the response. Postman outputs:
Parse Error: Expected HTTP/
First segment:
HTTP/1.1 200 OK\r\n
Accept-Ranges: bytes\r\n
Content-Type: text/html; charset=UTF-8\r\n
Content-Length: 648\r\n\r\n
Second segment:
<!doctyp... | I figured out what causing this. It's the content-length. The content-length actually invalid because the response shows gzipped content length instead of actual content-length so I have to re-calculate content length before sending response.
Since content-length is wrong, the parsing fails to digest the response as va... |
67,462,396 | 67,462,452 | Compiler "Optimizes" Out Object Initialization Function | I have an object that I need to populate before using called pipelineInfo. To populate the object I use a function called createPipelineInfo. This works perfectly well when I use visual studios to compile a debug build but when I try to compile a release build the compiler "optimizes" out the entire createPipelineInfo ... | wild guess: this parameter is passed by copy
const std::array<VkPipelineShaderStageCreateInfo, 2> shaderStages
so when taking the address of its contents here with data method call:
pipelineInfo.pStages = shaderStages.data();
you invoke undefined behaviour. The compiler isn't smart enough to 1) warn you about taking ... |
67,462,811 | 67,462,903 | Exception thrown at 0x7BC9E829 (ucrtbased.dll) in Project1CSCI115.exe: 0xC0000005: Access violation reading location 0x80A801E4 | I was writing some code that converts a adjacency matrix into an adjacency list, and ran into a problem. I traced it down to a memory error, but when I step through with my debugger, it passes right over the error, and does not throw an exception. When the program runs without breakpoints, it throws the exception. I ha... | The constructor should be
matrix::matrix() {
numVertices = 0;
}
matrix::matrix(int m, int n) {
numVertices = m * n;
aMatrix = new NodeAM * [n*m]; //n is columns
curr = new NodeAM * [n];
currVert = new int[n];
for (int i = 0; i < n; ++i) {
aMatrix[i] = nullptr;
curr[i] = nullptr;... |
67,463,566 | 67,463,629 | How do I check is two conditions are true without writing the same condition twice | This is a rather simple question I believe, I simply want to know how to write this more efficiently;
I have a pHandle to a process that works fine. However, when I was writing out my error check I realized that if I write
if (pHandle == NULL || INVALID_HANDLE_VALUE)
It will always be true even if the pHandle is valid... | The only approach here is to write that out twice. If you want someone to blame, blame C where this restriction is inherited from.
This is largely a product of how C is just "fancy assembler", and in assembly terms your code looks like:
LOAD a, pHandle ;; Load handle into register A
LOAD b, NULL ;; Load NULL into b
CMP... |
67,463,804 | 67,463,867 | How to include Microsoft detours library in visual studio | I am trying to use the detours library in a visual studio empty windows project. I cloned the repository (https://github.com/microsoft/Detours), I added the include directory into Project Properties / C/C++ / Additional Include Directories, and I added the lib.X86 directory into Project Properties / Linker / Additional... | You need to add the specific .lib file, which I'm guessing is "detours.lib" (or similar) to the "Additional Dependencies" line.
Properties->Linker->Input->Additional Dependencies.
|
67,463,810 | 67,595,142 | c++ variable initialization in ranged loops with mutidimentional arrays | I am learning c++ for the first time(I am transitioning from python)
I see some weird behavior when I try to work with and compile ranged loops using multidimensional arrays. Consider the following case:
#include <iostream>
#include <typeinfo>
int array[2][3]
for (dataType row : array) { std::cout << typeid(row).name(... | Credit to M.M:
for (const auto row : array) { std::cout << typeid(row).name(); }
auto here becomes a pointer, then const is applied to it. It is a pointer, the address stored in the pointer cannot change but the value it points to can be changed.
It is the same as writing:
int* const row
conversely const auto* simply... |
67,464,201 | 69,146,503 | How do I convert a std::string to System.String in C++ with Il2CppInspector? | I am using Il2CppInspector to generate scaffolding for a Unity game. I am able to convert System.String (app::String in Il2CppInspector) to std::string using the functions provided below.
How would I reverse this process; how do I convert a std::string to System.String?
helpers.cpp
// Helper function to convert Il... | The accepted answer is actually wrong, there is no size parameter and copying stops at the first null byte (0x00) according to the MSDN documentation.
The following code fixes these problems and works correctly:
app::String* string_to_il2cppi(const std::string& string)
{
const auto encoding = (*app::Encoding__TypeI... |
67,464,365 | 67,464,472 | how can I allocate an array on the stack if the size is not known at compile time? | I'm writing a c++ program with visual studio and I have written this code
DWORD GetProcIDByName(const char* procName) {
HANDLE hSnap;
BOOL done;
PROCESSENTRY32 procEntry;
ZeroMemory(&procEntry, sizeof(PROCESSENTRY32));
procEntry.dwSize = sizeof(PROCESSENTRY32);
hSnap = CreateToolhelp32Snapshot... | The szExeFile field is not dynamic length. It is a fixed-length array of MAX_PATH characters, holding a null-terminated string.
Note that:
sizeof() reports a size in bytes
szExeFile is an array of wchar_t characters, in your case
wchar_t is 2 bytes in size on Windows.
So, when you declare your char[] array as char fi... |
67,464,433 | 67,464,682 | nested macro with __VA_ARGS__ does not expand | To get number of __VA__ARGS__, I read this answer and it works. But I feel that PP_NARG_ is redundant, and I see no reason why PP_RSEQ_N is a macro function. So I modify the code as below
#include <assert.h>
#define PP_RSEQ_N \
63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
... | The essential nature of macro calls is that macro arguments are not expanded in the macro call. The precise procedure is specified in the standard at §6.10.3.1.
After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place.
So the arguments to the macro are ... |
67,464,503 | 67,465,805 | How to print an index of an integer array for the index number times. For example: if the index = 3 then print 3 for three time | I'm trying to write a code that takes the size of the array and the elements of the array from the user,
input:
3
5
8
3
and then print,
output:
5 5 5 5 5
8 8 8 8 8 8 8 8
3 3 3
this is my code so far:
#include <iostream>
using namespace std;
int main()
{
int T;
cin >> T;
int arr [ 10000 ];
int i;
... | The code below will help you if I have understood your question correctly.
#include <iostream>
int main()
{
int size = 0;
std::cout << "Please enter array size: ";
std::cin >> size;
for (size_t i = 0; i < size; ++i)
{
std::cout << size << " ";
}
}
Output :
Please enter array size: 8
8 ... |
67,464,688 | 67,523,614 | Mysterious nullptr added to std::unordered_map | I have an unordered map like this:
std::unordered_map<std::type_index, WidgetMetaData*> m_metaData;
The WidgetMetaData type is not important, the only important thing is that it is a pointer.
Now for some reason, very rarely, a nullptr slips in there. I have no idea where it comes from. I have added assertions in every... | So as it turns out, in a completely different part of the code, a lambda was being called that looked like this:
auto cleanup = [this]() { this->m_variable = nullptr; }
And the this in question had been deleted. So it was setting some random part of the memory to a bunch of zeroes.
So to answer my own question, settin... |
67,464,690 | 67,464,759 | Does std::ofstream guarantee the old open file will be closed if opening new one? | #include <fstream>
int main()
{
auto fout = std::ofstream("/tmp/a.txt");
fout.open("/tmp/b.txt"); // Will "/tmp/a.txt" be closed?
fout.open("/tmp/c.txt"); // Will "/tmp/b.txt" be closed?
}
Does std::ofstream guarantee the old open file will be closed if opening new one?
| The second and subsequent calls will fail.
[filebuf.members]
basic_filebuf* open(const char* s, ios_base::openmode mode);
2 Effects: If is_open() != false, returns a null pointer. Otherwise...
[ofstream.members]
void open(const char* s, ios_base::openmode mode = ios_base::out);
3 Effects: Calls rdbuf()->open(s, mode... |
67,465,375 | 67,465,711 | Sphere-Sphere Intersection, choosing right theta | I am working on a C++ problem where I'm trying to make a utility function that takes as input two line segments starting points in 3d space [(x,y,z) and radius r]. If the segments can be oriented such that they end at the same point, the function should return true and print out that point. If there are multiple orient... | As Spektre correctly pointed out I missed the 3D portion of your question, so the 4 options are the following:
no intersection (or one sphere completely lies within the other)
a single point (spheres touch from inside or outside)
a normal intersection forming a circle
both spheres overlap completely, i.e. they have th... |
67,465,423 | 67,465,587 | Are there any downsides to compiling with -g flag? | GDB documentation tells me that in order to compile for debugging, I need to ask my compiler to generate debugging symbols. This is done by specifying a '-g' flag.
Furthermore, GDB doc recommends I'd always compile with a '-g' flag. This sounds good, and I'd like to do that.
But first, I'd like to find out about downsi... | If you use -g (which on recent GCC or Clang can be used with optimization flags like -O2):
compilation time is slower (and linking will use a lot more memory)
the executable is a bigger file (see elf(5) and use readelf(1)...)
the executable carries a lot of information about your source code.
you can use GDB easily
so... |
67,465,671 | 67,474,245 | Is llvm's dyn_cast still used as an alternative to dynamic_cast? | I'm trying to optimize some code like this:
// RequestType inherits MessageType
void receive_message (MessageType* M)
{
auto msg = dynamic_cast<RequestType>(M);
if (msg != nullptr)
{
// do something
}
}
The program doesn't know until runtime what specific type MessageType will be.
In the code, dy... | While LLVM's dyn_cast templates are "an alternative dynamic_cast", it also requires the user to implement LLVM's RTTI which is described in detail in this document: https://llvm.org/docs/ProgrammersManual.html#the-isa-cast-and-dyn-cast-templates
To answer your question; yes, dyn_cast and friends are still used by LLVM ... |
67,465,726 | 67,465,769 | When to create header file only classes | I'm learning c++ (not my choice) and faced some classes with no .cpp file. I was told that classes should be implemented in 2 files : header file (.h) and source file (.cpp) but it seems it's not always like this.
My question is :
When and why it is preferred to implement class methods in header file (.h) and when it's... | Implementations of templated classes practically have to go into headers (though see alternatives described in the link below).
Non-templated classes are indeed recommended to be split as you describe.
See Why can templates only be implemented in the header file?
Some libraries (header-only libs) consist only of header... |
67,466,197 | 67,466,432 | can't call functions from arduino library | When i try to call any function from my library, it gives the following error:
In function 'void setup()':
error: expected unqualified-id before '.' token
netti.SetupWifi();
^
Yesterday it worked fine and i'm pretty sure that i haven't changed anything so i have no idea what's wrong with it. The library is for making ... | The error is the following. You have defined a class called netti but you have not created an instance of the class. Therefore you cannot call instance methods on this class. For example if you have
class netti{
public:
//constructor
netti(bool displayMsg=false);
//methods
void SetupWifi();
void... |
67,466,490 | 67,466,803 | Want to minimize my code so it consumes time less than 1 sec. It uses concept of modular exponentiation .Correct output but exceeding time limit | The below code is to calculate 2^n where n is equal to 1 <= n <= 10^5. So to calculate such large numbers I have used concept of modular exponentian. The code is giving correct output but due to large number of test cases it is exceeding the time limit. I am not getting a way to minimize the solution so it consumes les... | You can make use of binary shifts to find powers of two
#include <iostream>
using namespace std;
int main()
{
unsigned long long u = 1, w = 2, n = 10, p = 1000000007, r;
//n -> power of two
while (n != 0)
{
if ((n & 0x1) != 0)
u = (u * w) % p;
if ((n >>= 1) != 0)
... |
67,466,714 | 67,470,993 | Under what circumstances is ref_view{E} ill-formed and subrange{E} not? | C++20 introduces views::all which is a range adaptor that returns a view that includes all elements of its range argument.
The expression views::all(E) is expression-equivalent (has the same effect) to:
decay-copy(E) if the decayed type of E models view.
Otherwise, ref_view{E} if that expression is well-formed
Otherwi... |
But regarding the third case, I can't think of under what circumstances subrange{E} is well-formed and ref_view{E} is ill-formed.
ref_view{E} is only well-formed for lvalue ranges.
subrange{E} is only well-formed for borrowed ranges. You can find its deduction guide in [range.subrange.general]:
template<borrowed_ran... |
67,466,950 | 67,467,261 | std::regex_search reverse search | https://stackoverflow.com/a/33307828/9250490
You can find the first 5-sequential-number 12345 via regex_search(s.cbegin(), s.cend()...
string s = "abcde, eee12345 11111ddd 55555 hello";
std::smatch m;
bool b = std::regex_search(s.cbegin(), s.cend(), m, std::regex("[0-9]{5}"));
cout << m[0] << endl;
But if I want to fi... | It's because the iterator types do not match, if you look at the source of std::smatch in Visual Studio you'll find this.
using smatch = match_results<string::const_iterator>;
And you're trying to pass std::string::const_reverse_iterator in your std::regex_search call.
Use std::match_results<std::string::const_revers... |
67,467,242 | 67,604,315 | KeyBoard events in Ubuntu aren't working? | I am creating a cross-platform application in Qt5.15 monitoring user activity. My code works fine in Windows,Mac, and Raspberry Pi-Desktop-version(Debian), but when it comes to ubuntu keyboard events and mouse click events are not working. Note that my application is running in the background while the user is working.... | Your check
if(ie.code==EV_KEY)
should be
if(ie.type==EV_KEY)
The type will tell you the type of event like key-press or mouse movement.
The code will tell you which key was pressed.
|
67,467,910 | 67,468,107 | Store data of one class in another class | I have a class fp which represents a fixed point number. The underlying type is fixed at compile time, the position of the decimal point is determined at runtime.
Thus I need to store the position p of the decimal point somewhere.
Secondly, I want to use my fixed point number in structs which have variables of the fixe... | It looks like fp is tied really closely to container. I'd make that really explicit, and make fp a nested type of container. In C++, nesting a type does not create a special relation between instances. That relation between container and fp instances remains the member fp container::s.
But you can now write container a... |
67,468,320 | 67,532,078 | Debugging C++ variables in Android Studio | I have an Android app that involves both Java and C++ code. I'm currently debugging it from Android Studio on Device. I have a function parameter of const char* type. Whenever I try to view the value of the variable, it shows me the first value in the string.
Is it possible to view the entire null-terminated string, or... | The best I could find is printing variables with lldb.
Open lldb window while in debug
write p/s [variable_name], and it should print out the contents of the string.
If someone knows a better way, please let me know.
|
67,468,540 | 67,468,660 | Initialize member function arguments as data members in c++ | When trying to implement a class like this
class sample{
int a;
public:
sample(int a = 0){
this->a =a ;
}
void fun(int base = /*the value of a*/){
// some function code
}
};
I want to initialize the argument base of the function fun with the value of a (the data member of the class)... | Sentinel values
This can be achieved via a "sentinel" value. If a particular integer is unused (such as -1), try:
void fun(int base = -1) {
if (base == -1) {
base = this->a;
}
// ...
}
std::optional
Another way is to wrap the input up with an std::optional:
void fun(std::optional<int> base = std:... |
67,468,797 | 67,487,706 | Unable to enable / disable Mosaic using NVAPI | I'm working on some code to enable and disable Mosaic via NVAPI on a Quadro P4000.
I've set Mosaic to be active via the Nvidia utilities on the machine and it works. However, when I try to disable the Mosaic settings via code I receive the NVAPI_NO_IMPLEMENTATION status error.
This is the code I'm using:
void disableMo... | After more investigation, it turns out the error message is right, but there is a work around.
The NvAPI_EnableCurrentMosaicTopology() method is for Windows XP (most of the example code I've found in this area has been quite old, hence this mistake). To get this functionality working on Windows 7 - 10 there is a differ... |
67,469,364 | 67,469,451 | Accepting any Qt container as input parameter | I have a method that takes a collection of values as input parameter:
void doSomething(QVector<int> const &values) {
for(auto v : values) {
// Do something.
}
}
Sometimes, the values that I want to pass to the method are in a QSet instead of a QVector. Since doSomething just iterates over the collectio... | Since you want something that can accept multiple types not related by inheritance, just make it a template.
template <typename Container>
void doSomething(Container const& c)
{
for (auto v : c) {
// do something
}
}
will work fine for any type Container that has suitable begin() and end() methods (or ... |
67,469,383 | 67,469,544 | Convert (for example) 12345:12-34 into three ints: (12345, 12, 34) C++ string? | What is the fastest way to seperate these into 3 ints? I feel like this should be possible in one line but the closest I can find is this:
#include <ostream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
std::vector<int> extract_ints(std::string const& input_str)
{
std::vector<... |
how to expand to ':'s
You read a char from input and check if it's a :. For example:
#include <iostream>
#include <exception>
#include <vector>
#include <sstream>
#include <exception>
std::vector<int> extract_ints(std::string const& input_str)
{
std::vector<int> r(3);
std::istringstream iss(input_str);
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.