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 |
|---|---|---|---|---|
66,733,819 | 66,734,306 | Specific right-angled Triangles are not being recognized as right-angled in Cpp | I have to take the coordinates of the vertices of a triangle from the user and tell if it is a right-angled triangle or not. I'm using Pythagoras Theorem to Find out i.e. h * h = b * b + p * p
But surprisingly this doesn't work for some specific right-angled triangles.
Here is one such Triangle:
Vertex A: (x, y) = (1, ... | The line
double dist = sqrt((x-p.x)*(x-p.x) + (y-p.y)*(y-p.y));
in the Vertex::distance method gives you an approximation of a square root which is rarely going to coincide with an exact answer. This is because most real numbers can't be represented in floating point arithmetic.
But in given code sample you can make d... |
66,734,142 | 66,739,981 | play button sound without stopping music running in the background | I use PlaySound(TEXT("background.wav"), NULL, SND_FILENAME | SND_LOOP | SND_ASYNC); to play music in the background. I have some buttons in my game that play a short sound when the user clicks the button and it will stop the music. How can I keep the music playing in the whole game? I use PlaySound(TEXT("button.wav"), ... |
I have some buttons in my game that play a short sound when the user
clicks the button and it will stop the music.
You can use PlaySound to play background music in a loop. Then use mciSendString to play a short sound.
Like this:
//play music in the background
PlaySound(TEXT("background.wav"), NULL, SND_FILENAME | SN... |
66,734,535 | 66,734,663 | error in printing inverted half hollow pyramid in C++ using for loop | I am trying to print the pattern of Inverted half hollow triangle and it should look like the below pattern.
* * * * * *
* *
* *
* *
* *
*
I tried the below code but am not getting the required output. I don't want to include more variables leading to complexity .
#include<iostream>
using namespace std;
... | You have a problem on your 2 Strings because one takes 2 "spaces" and the other just one
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
for(int i=n;i>=1;i--){
for(int j=1;j<=i;j++){
if(j==i || j==1 || i==n){ /*you can simplify your condition*/
cout<<"*... |
66,734,767 | 66,734,783 | File Handling c++ in linux | Hi I am trying file handling in ubunto linux. I have a code that runs fine in virtual studio in windows but gives problems in Linux. Following attached is the code and screenshot of error. The code is to read a file check if there is an integer in the file and if any increase it by 1.
code:
#include<iostream>
#include<... | gcc is for compiling C program. You should use g++ instead to compile C++ program.
|
66,734,816 | 66,735,247 | Do vector also initialise primitive types in c++? | I know that when working with vectors and when knowing the size of a vector beforehand (tho it might get extended), one should use myVector.reserve(# objects) instead of vector<object> myVector(# objects) since the latter does a lot of unnecessary copies as it actually initialises the objects.
Does the same hold for pr... | Refer this:
Which has the description:
Constructs the container with count default-inserted instances of
T. No copies are made.
So yes, if you write vector<int> vec(10), it will default construct 10 integers with value 0.
|
66,734,911 | 66,737,826 | Monte carlo integration for area under curve | I have managed to code a program that uses the monte-carlo method to estimate pi. Now i am trying to instead estimate the area of plane curves, specifically a quadrifolium.See image for reference
I have been unable to do this so far. Surely this only involves a tweak to my current code? Any help or advice would be appr... | First, I must precise that Monte Carlo is by far not the best method to solve this problem. This solution exploit the fact that for both x and y superior to 0, ((x^2+y^2)^3 < 4x^2y^2) => (x,y) belongs to the surface.
#include <math.h>
#include <ctime>
#include <iostream>
double pow(double x, int n){
double r=1.0;
... |
66,735,024 | 66,735,058 | In C++ how do you define ***.h for class? | I have 3 files: ***.cpp *2 and ***.h *1
once i put into terminal: g++ mymain.cpp landowner.cpp -o mymain
it says
error: ‘landowner’ was not declared in this scope
8 | landowner Alex;
| ^~~~~~~~~
//landowner.h
#ifndef LANDOWNER
#define LANDOWNER
using namespace std;
void ShowScore();
#endif
//landowner.cpp
#... | The class decparation should be placed inside the header.
//landowner.h
#ifndef LANDOWNER
#define LANDOWNER
#include <iostream>
#include <string>
using namespace std;
void ShowScore();
class landowner
{
private:
string name;
long score;
int cards[20];
public:
landowner(){}
~landowner(){}
void ShowScor... |
66,736,417 | 66,736,468 | C++ assigning to a object | Why the last variable c do not print anything. I know that is caused by destructors but i can't really find out why. I thought that destructors only works when is called or is the end of function, program.
.....//
class Int{
private:
int a;
public:
Int(): a{0}{}
Int(int s):a{s}{}
Int(const Int& va) : a{va.a} ... | Your job in the destructor is to clean up any resources you've allocated or inherited ownership of as per the RAII rules of C++. It is not to delete yourself. That is not your job.
Since you have no allocated resources, your job is pretty simple:
~Int(){}
Nothing to it, literally. In fact you can skip having a destruc... |
66,736,886 | 66,834,841 | Windows vs code wxWidgets's #include <wx/wx.h> not found | I use window10 and vs code to compile some source code.
I can compile the code but when I run the .exe file. Nothing shows up.
I got this error.
My cmakefile is as follows:
cmake_minimum_required(VERSION 3.11.3)
set(CMAKE_CXX_STANDARD 17)
project(membot)
set(wxWidgets_ROOT_DIR "C:/wxWidgets-3... | I found my solution.
In the cmakefile.txt, I use find_package(wxWidgets REQUIRED gl core base OPTIONAL_COMPONENTS net) instead of find_package(wxWidgets REQUIRED COMPONENTS core base)
My final cmakefile.txt is like this
cmake_minimum_required(VERSION 3.11.3)
set(CMAKE_CXX_STANDARD 17)
project(membot)
set(wxWidget... |
66,737,128 | 66,737,185 | SFML Window not responding to inputs | I recently started working on SFML. I just created a window then later started to separating my main code. First i wrote a window class.
Nothing special, just draws my window and prints mouse coordinates.
#include "Window.hpp"
#include <iostream>
Window::Window()
{
SetWindow(800,600, "JUST SFML");
}
void Window::... | In order to receive events (such as the mouse moving), you need to call pollEvents on the window.
In your commented code, you were doing this through your Window::EventControl() method. Your new GameManager class isn't calling this, however, so you aren't receiving any events.
|
66,737,532 | 66,751,436 | C++ Send image client to server (sockets), image corrupt | after hours I write this :
Client side : Here I have image.png ( original image )
FILE* fichier = fopen("image.png", "r");
if(fichier != NULL)
{
response += "Analyse... ";
fseek(fichier, 0, SEEK_END);
long taille = ftell(fichier);
fseek(fichier, 0, S... | There are so many problems with this code, it just needs to be re-written from scratch. Reading and sending the file data in chunks is fine, but you don't need to convert those chunks to strings (especially since you are doing it incorrectly), and you certainly don't need to send each chunk's size. All you really nee... |
66,737,721 | 66,737,882 | SFINAE does not work for copy constructors | I have a template class and I would like to have two copy ctors. One for trivial types, and another for non trivial types.
The following code works (with one copy ctor):
template <typename T>
struct MyStruct
{
MyStruct()
{}
MyStruct(const MyStruct& o)
{
std::cout << "copy ";
foo(o)... | Unfortunately, a template constructor can't be a default, copy or move constructor.
The signature of a copy constructor for MyStruct is as follows
MyStruct (MyStruct const &);
This function, in your second example, is implicitly deleted because you've written an explicit move constructor.
Your template constructor, wi... |
66,737,866 | 66,748,748 | How to access the values of a map<string, vector<int>> in C++? | I am working on my version of a genetic algorithm to solve the knapsack problem in C++. I have a map of string to vector like
map<string, vector<int>> objects
{
{"Object 1", {7, 20, 15}},
{"Object 2", {3, 50, 10}},
{"Object 3", {5, 80, 12}},
{"Object 4", {4, 80, 8}},
{"Object 5", {2, 40, 11}}
};
an... | I think that with some little linear algebra your problem has an easy solution: indeed, if you store the numerical data related to your objects into a matrix A, then for each population vector p your desired result is simply p^T A (or equivalently, A^T p) where ^T denotes the transpose of a matrix or of a vector.
If yo... |
66,737,878 | 66,738,042 | c++ segfault and pointers confusion (I have the feeling I'm missing something terribly obvious) | I'm a python programmer new to C++. Currently getting a segfault when trying to play around with pointers. Can someone explain this behavior? I suspect there's something significant about cout that I'm not understanding.
#include<iostream>
using namespace std;
int main() {
int var; // declaration
cout << "v... | You declared a pointer to an integer, but not initialized or assigned it with any pointer (i.e. to memory address of an integer variable).
int* ptr; // declaration
The line above says, ptr is a pointer (that would point to memory address of an integer variable). In your case it just says it is a pointer, what it does ... |
66,738,376 | 66,738,401 | How to iterate over an unordered map's specific key's values? | I have an unordered map with a string and a vector of strings. I want to go to a specific key and iterate over all it's values.
Ex. Go to key 400 and iterate over 1, 2, and 3.
{
400 -> [1,2,3],
200 -> [],
13 -> [10,30]
}
std::unordered_map<std::string, std::vector<std::string>> mymap;
myKey = 400;
for(aut... | You don't need 2 loops to do this. Specifically, the outer loop that looks for the key is unnecessary. If you know that the key exists, you could simply do:
for (auto const & item : mymap["400"])
// ...
If you're not sure whether the key exists, you can write:
if (auto it = mymap.find("400");
it != mymap.end())
... |
66,738,528 | 66,738,626 | Spawning threads inside a class | I'm getting an compilation error, related to std::invoke, and also another that can not specialize the template for invoke.
This is the code:
#pragma once
#include <thread>
#include <iostream>
#include <vector>
#include <string>
#include <chrono>
class ThreadLoader {
private:
unsigned int id;
void _loadFile(co... | You have your parameters the wrong way round, it should be:
std::thread t(&ThreadLoader::_loadFile, this, std::ref(filepath));
|
66,738,870 | 66,738,972 | Separate compilation with abstract classes C++ | I have a question in regards to building a project in C++ with abstract classes.
Suppose you have an abstract class A in a header file and then you have class B in a cpp file to create an object from class A. So far we have:
Class_A.h, Class_B.cpp
Within the Class_B.cpp file, I have included the header Class_A.h.
I wan... | Just need to organize your code. There's no hard and fast rules about how that needs to be done, but generally you define classes in header files (.h or .hpp) and implement the class in source files (.cpp). In this situation I would:
Class_A.h
class Class_A
{
public:
virtual void myFunc() = 0; // Class_A is abstra... |
66,738,914 | 66,739,201 | STL Priority queue with custom comparator not working as expected | I'm trying to implement Priority queue with custom operator. The algorithm tries to find the minimum increments to be done so that no two adjacent elements in array have absolute difference > 1.
For this, I get the maximum element "x" in the array and modify its neighbours to x-1, then repeat the same for other elemen... | You are modifying the item after it was put into the queue and still is part of that queue. This is not supported by the priority queue and yields unspecified results. C++ STL does not offer updatable priority queue.
But, seeing your use case I suspect this is competitive algorithmic programming. There are decent alter... |
66,740,038 | 66,740,230 | c++ - Multiple conditions in for loop getting incorrect result | Given an array A = [10,9,2,5,3,7,101,18] I am populating another array B of same length such that B[i] is longest increasing sub sequence containing A[i] of subarray A[0,i] (Please refer Longest Increasing Subsequence : https://leetcode.com/problems/longest-increasing-subsequence/ )
For this I am using following loop
f... | Ok, first example will work for each j value and find the maximum value. Second will stop the first time you hit A[j] < A[i]. So what if you have situation like A[i] = 5 and A[j] = 5, but down the road A[j+1] = 6, A[j+2] = 7 ... A[j+100]=1000. Your second loop will say I found maximum its 5, go on and increment i. No A... |
66,740,137 | 66,741,441 | Is there an even faster approach than swap-and-pop for erasing from std::vector? | I am asking this as the other relevant questions on SO seem to be either for older versions of the C++ standard, do not mention any form of parallelization, or are focused on keeping the ordering/indexing the same as elements are removed.
I have a vector of potentially hundreds of thousands or millions of elements (whi... | Take a look at std::remove_if algorithm. You could use it like this:
auto firstToErase = std::remove_if(myVec.begin(), myVec.end(),
[](const & T x){
// Do calculations to determine if element must be removed
// ...... |
66,740,276 | 66,740,631 | To read FILE and store data in map<string, vector<string>> c++98 | I have file bird.lst, I need to read file contents and store data in map<string, vector>, here the idea is bird name is store in string and those having some attribute values that needs to be stored in vector. please help
eventually map<string, vector> looks like below,
ex:
parrot.sh ----> eat yes
... | You need a nested loop.
The outside one reads the name of the bird (the key of the map)
The inside one reads the attributes of the bird (the values of the vector)
Here is what I came up with:
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <vector>
typedef std::vector<std::string> a... |
66,740,526 | 66,740,916 | Vector of pointers throws error on push_back | Spiral/Zigzag level order traversal of binary tree. Initailize vector of pointers to traverse and pop from the front but don't know why its not working
Here is my code sample
Code:
void spiralPrint(Node *root)
{
if(root!=NULL)
{
vector<Node *> v;
v.push_b... | Here's the fix
for(int i=0; i<count; i++)
{
auto it = *v.begin();
if(it->left != NULL)
{
v.push_back(it->left);
}
if(it->right != NULL)
{
v.push_back(it->right);
}
v.erase(v.begin());
}
Also with front
for(int i=0; i<count; i++)
{
if(v... |
66,740,897 | 66,757,211 | Why does Clang prefer the primary template over the specialization from C++17? | The following program is reduced from the code in this question:
template <typename T, void (*)(T), typename = void>
struct S;
template <typename T, void (*f)(T)>
struct S<T, f, void> {};
S<int const, nullptr> s;
In all versions of GCC, in all language revisions, the specialization of S is chosen when s is instant... | This is because C++17 allowed a template type argument to be deduced from the type of a non-type argument. [temp.deduct.type]/13:
When the value of the argument corresponding to a non-type template
parameter P that is declared with a dependent type is deduced from
an expression, the template parameters in the type of ... |
66,740,909 | 66,753,672 | How do bitwise operations work on expressions within variable assignments in C/C++? | I'm learning reverse engineering, and I have the following snippet which I am trying to make sense of:
var = strcmp("C:\\Windows\\System32\\svchost.exe", pe.szExeFile);
if (var)
var = -(var < 0) | 1;
if (var)
{
// additional code here
}
I think I understand most of what is going on here, but I'm confused about the... | strcmp() returns one of three possible results:
< 0
0
> 0
Assumed common two's complement, after the first if the variable var will be
-1 for the former "< 0"
0 for the former "= 0"
+1 for the former "> 0"
However, the second if will be taken only if var is non-zero.
The "mysterious" first if has no effect, as far ... |
66,741,155 | 66,741,231 | My code is failing the time limit even though it seems to produce the correct output. How do I decrease the time taken for my code to work? | Question - For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)^n*n
Your task is to calculate f(n) for a given integer n.
Input -
The single line contains the positive integer n (1 ≤ n ≤ 10^15).
Output -
Print f(n) in a single line.
Link to question - https://codeforces.com/problemset/p... | Your algorithm has O(N) complexity, hence it fails. We can come up with an O(1) solution here.
Look at values of f(n), to make it easier.
f(1) = -1
f(2) = 1
f(3) = -2
f(4) = 2
f(5) = -3
f(6) = 3
2 simple observations here:
f(n) is positive if n%2==0
abs(f(n)) = ceil(n/2)
Using these facts, the algorithm gets reduc... |
66,741,996 | 66,742,050 | How can I access the class variables inside the print() function here? | Book.h
class Book{
private:
std::string title;
std::string author;
int callNo;
public:
Book(std::string title,std::string author,int callNo);
void print();
};
Book.cpp
Book::Book(string title,string author,int callNo){
this->title=title;
this->author=author;
this->callNo=callNo;
}
voi... | Since it's a member function of Book, it should be
void Book::print(){
std::cout << "Title: " << title << std::endl;
std::cout << "Author: " << author << std::endl;
std::cout << "Call Number: " << callNo << std::endl;
}
|
66,742,457 | 66,757,288 | building a .so that is also an executable with C++ | Based on building a .so that is also an executable I'm trying o reproduce with C++ and I'm getting a segmentation fault on main program execution.
/* pie.cpp */
#include <cstdio>
int foo()
{
printf("in %s %s:%d\n", __func__, __FILE__, __LINE__);
return 42;
}
int main()
{
printf("in %s %s:%d\n", __func__, __FIL... | I just tried code from my old answer; it no longer works using a recent GLIBC (I have 2.31-9+build1):
$ gcc -fPIC -pie -o pie.so pie.c -Wl,-E
$ gcc main.c ./pie.so
$ ./pie.so
in main pie.c:10
in foo pie.c:5
$ ./a.out
./a.out: error while loading shared libraries: ./pie.so: cannot dynamically load position-independent... |
66,742,797 | 66,742,841 | C++ Template TypeName as Friend | Need to make the specialization a friend... but getting error...
template<typename foo>
class bar
{
friend class foo;
};
error C2649: 'typename': is not a 'class'
| Remember that class names are also type names, and that you don't need to specify class when using it as a type name.
Because foo already is a type name, the same applies here and you don't need the class keyword:
friend foo;
|
66,743,851 | 66,747,562 | Three-way comparison of CRTP-ed std::vectors | In this article I've stumbled upon this obscure code (which is presented casually, like this is a totally normal C++ code):
struct Tree : std::vector<Tree> {};
Two trees are then created and compared (see the demo):
Tree tree(size_t h)
{
Tree s;
if (h > 0)
s.insert(s.end(), 2, tree(h - 1));
return s;
}
int ... | The issue here is constraint recursion.
In C++17, vector<T>'s operator< had a precondition that < was defined for T, but libstdc++ didn't check this. Their implementation was basically:
template <typename T>
inline bool operator<(vector<T> const& a, vector<T> const& b) {
return lexicographical_compare(a.begin(), a.... |
66,743,929 | 66,745,978 | Google Kickstart 2013 Round B Problem Sudoku Checker gives a wrong answer, yet it is working | https://codingcompetitions.withgoogle.com/kickstart/round/0000000000434ad7/00000000004347b3
Sudoku is a popular single player game. The objective is to fill a 9x9 matrix with digits so that each column, each row, and all 9 non-overlapping 3x3 sub-matrices contain all of the digits from 1 through 9. Each 9x9 matrix is ... | As mentioned by @jabaa you forgot to check the sub-matrices.
Moreover, checking the sums is not enough, as for example 1 + 3 = 2 + 2.
An efficient solution consists in checking, in each line, column or sub-matrix, that no number arrives twice.
This is efficient, at the condition to first check that all numbers are in t... |
66,743,983 | 66,744,375 | How to print x times "Hello world" by asking with an external function call, which is written in another c++ file (2 files in total) | How to solve it with two cpp files?
how to print x times "Hello world" by asking with an external function call, which is written in another c++ file?
function.cpp
#include <stdio.h>
int intf(void) {
int l;
printf("How many lines to print?");
scanf("%d", &l);
printf("%d lines to print.\n", l);
int i = 0;
while (i<... | This is called separate compilation and is commonly used in medium to large programs.
Here main.cpp could be as simple as:
int intf(void)
int main() {
intf();
return 0;
}
If you are using an IDE, just declare both source files in the same project, if you use a CLI compiler, just compile both into one executab... |
66,744,016 | 66,744,259 | Call python Multivariate linear regression code from C++ Application | I am doing my research in networking and I want to implement linear regression on my own data set(numeric). I used python for multivariate linear regression using sklearn library and now I want to embed/call that python implementation from my c++ code.
AS if I say that c++ is my application and python code is a servic... | When you want different languages to collaborate, you have 2 possible ways.
the easy way: external program and communication through pipes/files:
you prepare the input data in your C++ program and save it to a file
you launch a python interpretor to execute your python script with fork/exec (on Linux), spawn (on Wind... |
66,744,046 | 66,751,274 | (boost C++ library) bootstrap.bat: ''Web' is not recognized as an internal or external command' | I am currently trying to build boost for visual studio 2019 (64 bit), however, when I run bootstrap.bat from both the visual studio terminal and the windows command prompt, I get the error as mentioned in the title.
Here are some screenshots:
visual studio terminal
windows command prompt
Please note this is my first po... | For some reason boost does not like your current path. Either because of the & symbol or spaces. Try moving it to a more canonical path C:\boost_1_75_0
|
66,744,271 | 66,744,671 | Implicit conversion insists on using private function | I have a class that has a conversion operator to int& that I want to hide. I created a derived class that only offers a conversion to int and made the conversion to int& private. But I still cannot make the int conversion to be used, either the compiler tells me that the conversion is ambiguous, or insists to use the i... | I could not find a way through inheritance. But if containment is an option (Derived has a Base instead of is a), it is much simpler:
struct Base {
int value;
operator int&() { return value; }
};
struct Derived{
Base b;
operator int() { return b.operator int&(); }
};
int main() {
int p = Derived(... |
66,744,636 | 66,745,267 | How to pass char* by value C++? | I have defined an attribute of type char* content that accepts a string that contains even \0 like characters, in this way I could not use the string type.
The problem here when I tried to define the setter for content is this :
void MyClass::setContent(char* content)
{
if(this->contentLength!=0){
if(this->... |
I have defined an attribute of type char* content that accepts a string that contains even \0 like characters,
There's your problem right there. If you're passing a char * around - and even worse, using it to manage dynamically allocated memory returned by malloc(), there are many things that can go wrong.
Simply p... |
66,744,750 | 66,746,063 | C++: Runtime error in while loop condition | nums is a vector, and I have one code line that
while(i < nums.size()-2 && nums[i] == nums[i+1]) i++;
It would give me a Runtime error, If I run the code when the nums.size() is 1.
But if I change this line to:
while(i-2 < nums.size() && nums[i] == nums[i+1]) i++;
The build succeeds.
I have no idea, what is the diffe... | std::vector<>.size() returns an unsigned long which, when combined with nums.size() - 2 gives an underflow and the result is some really big number which doesn't fit your code logic. Since the expression i < nums.size() - 2 will always evaluate to true because of the underflow, you will keep iterating through the vecto... |
66,744,762 | 66,744,972 | Why should I use (void*) in second parameter of WriteProcessMemory() func? | I am trying to create a game trainer for a game. I have found the needed memory addresses and now I want to write my values into that address.
For example: address of ammo is: 0x0E9AFD07
The WriteProcessMemory() function in the Windows API can do this.
My source:
int main(){
DWORD pid;
int address = 0x0E9AFD07;... | Note that your two code snippets are not equivalent; rather, they are asking the WriteProcessMemory function to write data to different locations.
In the second snippet, you pass 0x0E9AFD07 (as a void*), which tells the function to write the data to memory starting at the given address (the hex value passed).
However, ... |
66,744,814 | 66,745,152 | GCC strange std::integral_constant<bool, value> instantiation and compile-time evaluation | Question context :
While toying with godbolt about ways to recover compile-time contexts using runtime-value,
(yeah, sounds like a bad idea), I found out a context where GCC evaluates std::integral_constant<bool, value_arg>::value strangely :
See the complete example on godbolt here : https://godbolt.org/z/KzrK5xz3c
Di... | From the requirements of std::visit:
[first parameter] - a Callable that accepts every possible alternative from every variant
In your case the lambda you pass must accept both std::integral_constant<bool, false> and std::integral_constant<bool, true>, which is not true because the static_assert's cause the instantia... |
66,745,533 | 66,745,703 | I cannot use the static variable | I'm trying to print the employee count after each created object but I'm getting an error like this: undefined reference to `Employee::numberofEmployees'. How can I solve this little problem? Any ideas? Btw I'm using a local class.
the purpose of the numberofEmployees variable is to store the information on the number ... | If you have a static variable within a class, you are supposed to initialise it outside of the class, ie in a .cpp file. From C++17, however, you are allowed to initialise it in-class, in-line, using the inline keyword.
Code:
#include <string>
#include <iostream>
using namespace std;
class Employee
{
public:
str... |
66,745,561 | 66,746,814 | How to read such a nested json array in Qt? | Im trying to read json file with qt c++. After reading i will do some operations. I've read my json like it, but i want to print spesific datas, which include "float".
After finding them, i will assign a value each of these.
Thanks for any help
{
"A":[
{
"GPS":[
{
"GPS ID":[... | Actually, you seem to already know what you need to do to handle Json data, you just have to continue to unpack your nested structures until the leaf data.
I'm not sure what was your issue, you just had to continue what you were doing but anyway, I have written an example that prints in the console the inner GPS data o... |
66,745,646 | 66,745,767 | What is the role of BOOL in the given code? | Here's a c++ code to sort the data of various types using template function. Can someone elaborate what does BOOL do here?
I've read about bool data type. It basically assumes only two values TRUE and FAlSE. But I've no idea, what is the role of BOOL here ?
using namespace std;
#include <iostream>
tem... | The bool in the example is there to check wether any exchanges happened in that iteration of the for-loop. If no exchanges happened == the array is sorted, the sorting algorithm is done.
Giving this function a already sorted array will show the purpose of the boolean. In the first iteration through the whole array, no ... |
66,746,115 | 66,746,778 | Clang failed to compile with unused template | There is some code in our codebase that failed to compile with clang10. The code looks like this:
class A {
private:
A& operator=(const A&); // don't allow assignment operator
A(const A&); // don't allow default copy constructor
};
template<class T>
class pool_allocator {
void setAllocator(A* a) { all... | See temp#res.general-6.1
The program is ill-formed, no diagnostic required, if:
(6.1)
no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the template is not instantiated, or
void setAllocator(A* a) { allocator = *a; }
is wrong for any T, so pr... |
66,746,309 | 66,746,426 | Redefinition of same variable in body after defining in for loop | Here i is within the scope of first for loop, so when redefined in a nested loop, why doesn't it give a compilation error?
#include <iostream>
using namespace std;
int main() {
for(int i=0; i<2; i++){
cout<<"out: "<<i<<endl;
for(float i=0; i<1; i++) {
cout<<"in: "<<i<<endl;
}
... | It's just variable shadowing. Perfectly allowed, but can be confusing.
There are cases where you want to shadow, and there's others where you've done it inadvertently. In this case there's no reason confusion, excepting the part of using a float as an indexed array iterator, which is usually a bad plan.
|
66,747,158 | 66,747,245 | Sorting by different data members of a class C++ | So, I basically learnt class and also Template functions in C++. Suppose I have a record of students in a class with their roll number, name and total marks.
I am using index sorting to sort the records. Now the sorting can be done on the basis of name, roll or total marks. How to incorporate all three using template f... | You can pass a functor as comparator to the function:
template <typename Comparator>
void my_sort(int a[], record r[],int n, Comparator comp)
{
/*...*/
if (comp(r[a[j], r[a[j+1]]) // instead of if(r[a[j]].name>r[a[j+1]].name)
/*...*/
}
Then you can call it with custom predicates, eg to compare name mem... |
66,747,208 | 66,747,608 | how last->next = temp works? | This is the code for displaying a linked list from a udemy tutorial here we will take an array and store those values in a linked list. I didn't understand how the code works. in the below code where we are storing the address of the next node how last->next=temp; works where I didn't create a last node like last=new n... | The best way to figure out pointers is to draw boxes and arrows with pen(cil) and paper.
Here is a (sad) ASCII rendition of what happens:
head->data = A[0];
head->next = nullptr;
last = head;
head points to a newly created node, and last points to the same place as head:
head
|
v
+------+------+
| data ... |
66,747,577 | 66,747,934 | How to move a value out of a std:optional without calling the destructor? | I am trying to write a function, make_foo, that will "unwrap" a std::optional< foo >, returning the contained value.
The function assumes that the optional is engaged so does not perform any runtime checks on the optional.
My implementation of this is below, along with the compiled assembly for reference.
I have a coup... |
How to move a value out of a std:optional without calling the destructor?
Like you did in the example. The destructor is not called by the move. The destructor of foo is called by the destructor of the std::optional which is called by the destruction of the temporary std::optional object that you created.
You can onl... |
66,747,651 | 66,757,714 | _Pragma("omp parallel for") causes internal error in Visual compiler | I currently wonder why I get an compiler error in Visual.
I tested my code with Clang and GCC and it works without issues.
However, on Windows I seem to get an error or compiler crash.
Using #pragma seems to compile, but both expressions should be equal.
#define paral_prog_decl \
_Pragma("omp parallel for")
para... | I suggest that you could refer to the following code:
#include<stdio.h>
#include<omp.h>
#define paral_prog_decl \
_Pragma("\"omp parallel for\"")
int main() {
paral_prog_decl(x)
for (int i = 0; i < 20; i++) {
printf("this is No.%d Thread ,i=%d\n", omp_get_thread_num(), i);
}
... |
66,747,731 | 66,751,617 | Creating a basic PyTupleObject using Python's C API | I'm having difficulty with creating a PyTupleObject using the Python C api.
#include "Python.h"
int main() {
int err;
Py_ssize_t size = 2;
PyObject *the_tuple = PyTuple_New(size); // this line crashes the program
if (!the_tuple)
std::cerr << "the tuple is null" << std::endl;
err = PyTuple_S... | The commenter @asynts is correct in that you need to initialize the interpreter via Py_Initialize if you want to interact with Python objects (you are, in fact, embedding Python). There are a subset of functions from the API that can safely be called without initializing the interpreter, but creating Python objects do ... |
66,748,083 | 66,748,611 | Simple Boost UDP receiver gest heap-use-after-free when using std::vector | I am struggeling to understand why my quite simple UDP receiver is getting heap-free-after-use error (diagnosed by ASAN). The idea is listen to a configurable number of local ports for incoming packets.
I am here posting a simplified version of the class
UdpReceiver.hpp
class UdpReceiver
{
public:
UdpReceiver(std... | The documentation for async_receive_from says: "Ownership of the sender_endpoint object is retained by the caller, which must guarantee that it is valid until the handler is called."
Your push_backs may reallocate the underlying storage, leaving async_receive_from with a dangling reference.
To avoid reallocation, reser... |
66,748,114 | 66,748,210 | Determine return type of C++ std algorithm function like count_if | How can I determine the type of std:: function like std::count_if?
Ideally, I'd like something like the following
using ret = std::invoke_result_t<std::count_if, const char*, const char*,
std::function<bool(const char)>>;
But this does not work for multiple reasons.
I could get closer ... | Simplest way is just using decltype like this:
using type = decltype(
std::count_if(
std::declval<const char*>(),
std::declval<const char*>(),
std::function<bool(const char)>{}
)
);
|
66,748,198 | 66,748,692 | How to map string literals to types in C++ | I'm writing a small 2D game and I'm currently adding scripting capabilities to it (using Lua or Python), and I stumbled on this problem (which I think will lead me to implement some kind of reflection system for my game):
I'm using the Entity Component System pattern, and the definition for an entity is provided by a s... | I can think of a few approaches to your problem.
Different types of components are not different C++ types.
In this case, your components are just bundles of properties. Code looks at which bundles you have and behaves differently.
You have a fixed set of component types in C++.
Here, the scripts name kinds of com... |
66,748,590 | 66,748,771 | Enable function only for some template specification if template is of integer type | I have a Vector class which has a template of <unsigned int Dim>, eg. I can do Vector<2> for a vector in 2-dimensional space, Vector<4> for 4-dimensional, etc. I want to add some methods to the class if Dim == specific value, for instance CrossProduct for Vector<3>, or x,y,z,w getters for a vector of sufficient dimensi... |
pre-C++20, static_assert might be the simplest:
template <std::size_t Dims>
struct Vector
{
// ...
double getZ() const { static_assert(Dims >= 3); return data[2]; }
};
SFINAE is possible, but complex and verbose:
template <std::size_t Dims>
struct Vector
{
// ...
template <std::size_t D = Dims, std:... |
66,748,719 | 66,748,824 | move class instance holding a unique_ptr | I have a vector of class instances. Each of those instances has a unique_ptr to another class.
Since I never try to copy the class instance or even share the pointer, I felt like unique_ptr are more appropriate than shared_ptrs since the pointer is not shared, but only accessible through the class instance.
Is it bad p... | This answer focuses on compilation error you seem to be having. Bad or good practice is left for others to chime in.
Your code have several errors there, but the main one seems to be that your custom B( ) constructor inhibits default move constructor. If you add it, your code becomes well-formed.
Here is a full working... |
66,748,912 | 66,752,147 | Split vector of class into vector of class member | I found a problem in C++ that I cannot solve by myself and so I would like to ask you,
if there is a possibility to split vector of class into vector of class member.
class CPerson
{
public:
string m_Name;
string m_Surname;
}
class CPersonList
{
public:
CPersonList ( const vector<CPerson> & ref )
... | A vector owns its content so if you want to return a std::vector<CPerson> you would have to copy the data, for example
std::vector<CPerson> people;
people.reserve(m_Alldata.size());
std::transform(m_Alldata.begin(), m_Alldata.end(), std::back_inserter(people),
[](CData const & data) { return data.m_pers... |
66,749,023 | 66,749,632 | How to use Q_PROPERTY with static class members | I'm new to Qt and came upon the Q_PROPERTY class, and was trying to set a static member using it. This is what I have so far:
class test{
Q_OBJECT
Q_PROPERTY(bool enabled READ enabled WRITE setEnabled)
public:
bool enabled() const{
return m_enabled;
}
void setEnabled(bool enable){
... | There's nothing special about using static members with Q_PROPERTY. There are two problems with the code that you provided:
Your test class does not derive from QObject. Change it to this:
class test: public QObject
In your .cpp file, you need to define the instance of the static variable. This is true of any stati... |
66,749,246 | 66,753,008 | Premake5: GLFW project does not compile under project kind "ConsoleApp" | I have this strange problem where my GLFW project does not compile (I am using Mingw64 as my compiler) when I set the project kind to "ConsoleApp" in my Premake file. It works perfectly when the project kind is set to "WindowedApp", but I want to have debugging capabilities. Here is my Premake file:
workspace "EatOrDie... | Trivial mistake. I have to link the project with gdi32 to display the window.
|
66,749,690 | 66,750,226 | About the using vertices as index in graphs c++ why we wasting space | I have a question about the vertices of graphs in c++. Like, let's suppose I want to have a graph with vertices as 100,200,300,400 and they are connected in some manner not important but if we are creating an adjacency list graph what we do is.
adj[u].push_back(v);
adj[v].push_back(u);
and let 400 is connected with 20... | An adjacency list stores a list of the connected vertices for each vertex in the graph. For example, given this graph:
1---2
|\ |
| \ |
| \|
3---4
You would store:
1: 2, 3, 4
2: 1, 4
3: 1, 4
4: 1, 2, 3
This can be done with a std::vector<std::vector<int>>. Note that you do not need to use the values of the graph as... |
66,749,737 | 66,819,901 | Python Extension Dll Installation | I have a large program written in C++ that I wish to make usable via Python. I've written a python extension to expose an interface through which python code can call the C++ functions. The issue I'm having with this is that installing seems to be nontrivial.
All documentation I can find seems to indicate that I should... | Let me try and divide your post into two separate questions:
How to package a C++ library with a non-trivial compilation process using setuptools
Is it possible to distribute a python package with a precompiled library
1. How to package a C++ library with a non-trivial compilation process using setuptools
It is possi... |
66,749,974 | 66,752,376 | Issues with calculating CRC16/MCRF4XX | I would like some help as I seem to be unable to calculate the CRC for a single byte, let alone an array of bytes.
Below is the test code that I have been trying to get work. Please note that I used the code from this post, and the example with the array of chars works, but I need to be able to adapt this to work for a... | If you do this:
uint8_t test[] = "123456789";
uint16_t remainder = crc(test, sizeof(test)-1);
then you get the expected result, 28561.
You need to subtract 1 from sizeof(test) to exclude the terminating 0.
|
66,750,140 | 66,750,185 | Singly Linked List, insert at end | Due to reasons beyond my control, the function declaration must not change. I'm not very good with pointers, so the NODE** declaration really throws me off.
I know the basic gist is more or less correct. I just keep getting errors due to the pointers and don't know how to solve it.
There is currently an error in this l... | NODE** data is a pointer to NODE*, so you should dereference the pointer like *data to get the value of NODE*.
void add_node_tail(NODE** data, string firstname,string lastname, string email) {
NODE* temp = new NODE;
temp->firstname = firstname;
temp->lastname = lastname;
temp->email = email;
temp->n... |
66,750,262 | 66,750,363 | C++: Copying pointer to const object into non-const object pointer | In my custom class, I'm getting an error when declaring the input variable pointer as constant and copying it into a non-constant member variable pointer.
The error I get is:
Cannot initialize a member subobject of type 'Position *' with an
lvalue of type 'const Position *'
Why does this happen? And why is this not c... | The first parameter does not refer to anything outside of the constructor scope as it is just a copy. The const in that case is only saying that your constructor itself is not allowed to change the value of attack.
The second parameter is a pointer to a const Position. If you could assign that to a non-const Position*,... |
66,750,452 | 66,751,794 | how to generate UML class diagram from C++ | I have these 2 structs and 1 class and I want to convert them into UML class:
struct cat
{
std::string name;
int id;
};
struct dog
{
std::string name;
std::string owner;
int age;
};
class Pet
{
std::vector<cat> cats;
std::vector<dog> dogs;
//some methods
};
i made this:
thank you in advance
| Some remarks :
cat and dog are C++ struct => their members are public, not private
you missed to indicate the types of name, id, owner and age
you used associations navigable in the two directions, but a cat and a dog do not know the corresponding Pet
the association end must be named (cats / dogs), and it is useless ... |
66,750,668 | 66,750,960 | Partial specialization on a property of a template argument | Suppose that I have several types which have a bool property isComplex:
struct SimpleBar1 {
static constexpr bool isComplex = false;
// ...
};
struct ComplexBaz2 {
static constexpr bool isComplex = true;
// ...
};
I'd like to have a template, which is partially specialized on the complex-ness of the ty... | C++20 introduces the requires-clause specifically for providing template specialization without adding SFINAE-style additional template arguments.
template <typename T>
class Foo;
template <typename T>
requires T::isComplex
class Foo<T> {
public:
static constexpr auto test = "complex";
};
template <typename T... |
66,750,822 | 66,753,548 | Pass container to a variadic template function | In modern C++17, how can we pass a container such as std::vector to a variadic template function in below code?
template <typename... Args>
void foo(const Args&... args) {
for (const auto& arg : { args... })
std::cout << arg << ' ';
}
int main() {
foo(1, 2, 3);
std::vector vec{ 1, 2, 3 };
foo(v... | Taking your comment into consideration, this is how you can adapt your code to print the elements of the vector
#include <iostream>
#include <vector>
template <typename... Args>
void foo(const Args&... args) {
for (const auto& arg : {args...}) {
std::cout << arg << ' ';
};
}
template <typename T>
std::ostream... |
66,751,234 | 66,751,285 | c++ function call without struct reference | I'm new to C++ but I have a good programming background and I have been looking for function calls that don't need a reference object to a struct or class. The best referral to what I'm looking for is probably any of unity's classes where for instance Vector2.Distance can be used and it returns another Vector2 but Vect... | You can define static functions inside your classes.
#include <stdio.h>
#include <stdlib.h>
struct vector {
float x, y;
// only recently figured out you could do this
// instead of vector() {x = 0.0; y = 0.0} etc.
vector() : x(0.0), y(0.0) {}
vector(float _x, float _y) : x(_x), y(_y) {}
// ad... |
66,751,378 | 66,751,658 | Does't work fopen_s(&file, "filename", mode) in visual studio 2019 C_language | So this is my first question here. If you could help me, that would be much appreciated. This code is about my thesis. I'm trying to write to a file and it works but trying to read another file is not reading. I can't make it work. "file does not open" appears on the screen. Help me please, for read to file.
#include ... | The original code posted had 2 major issues:
"C:\SA\input.txt" should be "C:\\SA\\input.txt" or simply "C:/SA/input.txt". Microsoft's legacy systems use \ as a path separator which must be escaped in C strings as \\ (and in many other languages too). The traditional path separator on POSIX systems is / and it is also ... |
66,751,719 | 66,751,828 | How do you insert 3 items into a multimap | I am trying to enter three items into a multimap.
-Title
-Genre
-Rating
Is there a way to insert two strings and int value into a multimap. And how would I print out this multi map?
#include<iostream>
#include<string>
#include<map>
#include<iterator>
using namespace std;
int main() {
multimap<string, string, int... | std::map and std::multimap is a key -> value storage, which means there is a single key and single value. It does not mean you cannot keep multiple data types, but you have to wrap them into single value like structure. For example:
using mmap = std::multimap< std::string, std::pair<std::string,int> >;
Which means th... |
66,751,834 | 66,751,870 | Leetcode Minimum Path Sum | I am working on an question called minimum path sum. I have made my logic and find it to be true but I am getting Runtime Error in the code. I have searched properly but can't find any mistake. Here is the code:-
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int colsize=grid.size();
... | It seems you accidentally swapped colsize and rowsize in the latter half of your question:
for(int i=1;i<rowsize;i++)
{
for(int j=1;j<colsize;j++)
{
grid[i][j]+=min(grid[i-1][j],grid[i][j-1]);
}
}
return grid[rowsize-1][colsize-1];
It ... |
66,751,855 | 66,751,929 | What is the purpose of a `std::variant` with a single template parameter? | In the example on this page: https://en.cppreference.com/w/cpp/utility/variant there is an std::variant with a single template parameter:
std::variant<std::string> x("abc");
Since a variant allows to store an object which can belong to a set of different classes, what is the purpose of the previous line? Should not it... | Depends what you mean by "the same". Those two lines of code definitely don't have the same layout in memory, nor the same access pattern.
As to the reason for that to exist, well -- symmetry. If you're going to support a large number of template arguments, nothing's stopping you from also supporting one. In fact it ca... |
66,752,066 | 66,752,383 | How does Cpp work with large numbers in calculations? | I have a code that tries to solve an integral of a function in a given interval numerically, using the method of Trapezoidal Rule (see the formula in Trapezoid method ), now, for the function sin(x) in the interval [-pi/2.0,pi/2.0], the integral is waited to be zero.
In this case, I take the number of partitions 'n' eq... | OP is integrating y=sin(x) from -a to +a. The various tests use different values of a, all near pi/2.
The approach uses a linear summation of values near -1.0, down to 0 and then up to near 1.0.
This summation is sensitive to calculation error with the last terms as the final math sum is expected to be 0.0. Since th... |
66,752,237 | 66,752,475 | Why is it not possible to add two addresses together? | Let's say I've defined two variables x and y:
int x = 5;
int y = 6;
I can get the address where x is stored via:
cout << &x << endl; // 0x61fe18
Which is a hexadecimal number. Now, if I want to print this number after adding 5, it is fairly simple:
cout << &x + 5 << endl; // 0x61fe1d
But if I sum together the addres... | The ability to convert something to an integer does not mean it is an integer.
Computers use binary logic, and you can take any piece of information in binary and convert it to an integer. But for it to be an integer, it means that addition, subtraction, multiplication and division all have the expected meaning.
Point... |
66,752,310 | 66,763,476 | ERROR_WINHTTP_NAME_NOT_RESOLVED when using dbghelp as a service | I am trying to setup a symbol proxy server that targets both our own internal symbol stores (UNC) and http servers (microsofts being one). I want it to run as a service, or as IIS (which runs as a service of course).
I have tried Micrsoft SymProxy, and am now trying pySymProxy.
pySymProxy works just fine when I run it ... | A (not particularly nice) work around for this issue is to use an OLD version of dbghelp.dll and symsrv.dll, which still supports the DBGHELP_WININET flag.
This is also confirmed by the original dbg author as an unsolvable problem here. As MS symbol servers are automatically redirecting to https, there is no way using ... |
66,752,337 | 66,752,466 | How do I efficiently forward the formatting arguments when implementing a formatter for a custom type | I am trying to write a custom formatter to help me print vectors. I am attempting to maintain the format specifiers so that each item in the vector is formatted the same way.
I have taken most of my inspiration from this tutorial, and the docs
#include <fmt/core.h>
#include <fmt/format.h>
template<typename ValueType>
... | You can get rid of your parse implementation and use the inherited function, and use fmt::formatter<ValueType>::format(item, context) inside your format to output each item (godbolt demo):
#include <fmt/core.h>
#include <fmt/format.h>
template<typename ValueType>
struct fmt::formatter<std::vector<ValueType>> : fmt::fo... |
66,752,392 | 66,752,626 | Problems wrapping a const-member-function in a functor | We implement a system that passes callbacks to object-instance member-functions. This works nicely, see the code below. The problem is that the current state of the implementation handles only non-const member functions.
The code below compiles and demonstrates that the system is working. As soon as the /* const */ ... | If you want to specialize WrapP for a const member function, you need to specify that:
template <typename T, typename R, typename ... Args, R(T::* F)(Args...) const>
struct WrapP<F> { // ^___^
// ...
};
As far as I'm aware, there isn't a way to allow for either const... |
66,752,398 | 66,752,757 | Using array from private access specifier | Here I have an array within the private section of my class which is unable to retain the values set in different members of the clas; during the fight sequence both of the values in the array equate to 0.
#include <iostream>
#include <string>
#include<math.h>
#include<cstdlib>
using namespace std;
class champions {
p... | I think your problems are coming from not understanding how to structure your code in the presence of classes and multiple objects. I have restructured your code below in a cleaner and more common way (it is not the only way to do it, but it is more typical). Hopefully there are not typos.
#include <iostream>
#include ... |
66,753,278 | 66,753,318 | Can a recursive variadic template function be implemented inside a template class? | I have a std::any that contains a numeric type, and I'm trying to cast the value in the any to a specific type via a recursive variadic template helper class
#include <any>
#include <cstdint>
#include <iostream>
template <typename ResultType>
struct Cast_any_to
{
template<>
static ResultType from_one_of(std::any cons... | You cannot explicitly specialize a template unless you are in namespace scope. If you want to keep everything in the class definition, use function overloading instead:
template <typename... Ts>
struct TypeList {};
template <typename ResultType>
class Cast_any_to {
private:
static ResultType from_one_of_impl(TypeLi... |
66,753,723 | 66,753,750 | What a L"string" in front of square brackets mean? | I found this among a supposedly trivial Tetris console game code.
wchar_t *screen = new wchar_t[];
unsigned char *pField;
.
.
.
screen[someMathIndex] = L" ABCDEFG=#"[pField[someOtherMathIndex]];
What is an wchar string in front of square brackets even mean?
I can't even able to find a way to google it.
Can you redirec... | String literals in C++ are actually arrays. I this case L" ABCDEFG=#" is a const wchar_t[11]. When you do
L" ABCDEFG=#"[pField[someOtherMathIndex]]
You are going to the pField[someOtherMathIndex]'th index of that wchar_t array.
|
66,754,558 | 66,754,605 | incorrect output using STL remove_if | I am trying to remove elements from a vector of ints using std::remove_if, but am not getting the required output.
Initial vector members: {0, 1, 2, 1, 3, 1, 4, 5, 1, 6, 1, 7, 1, 8, 1, 9}
Required Output: {0, 2, 3, 4, 5, 6, 7, 8, 9}
Actual Output: {0, 2, 3, 4, 5, 6, 7, 8, 9, 6, 1, 7, 1, 8, 1, 9}
#include <iostream... | There are just as many elements in the vector before and after the call to
std::remove_if:
Removing is done by shifting (by means of move assignment) the elements in the range in such a way that the elements that are not to be removed appear in the beginning of the range.
... and std::remove_if returns an iterator to... |
66,754,871 | 66,759,056 | Random generation with TRNG | For the following code which generates random numbers for Monte Carlo simulation, I need to receive the exact sum for each run, but this will not happen, although I have fixed the seed. I would appreciate it if anyone could point out the problem with this code
#include <cmath>
#include <random>
#include <iostream>
#inc... | TL;DR The problem is two-fold:
Floating point addition is not associative;
You are generating different random number for each thread.
I need to receive the exact sum for each run, but this will not
happen, although I have fixed the seed. I would appreciate it if
anyone could point out the problem with this code
F... |
66,754,960 | 66,755,229 | Having trouble getting timer interrupts to enable on the STM32f4xx | I am working on a project that will require timer interrupts.
Using STM32cubeIDE, I generated code that should work with timer-interrupts. Here is a truncation of what my main.cpp looks like: (htim1 is a global handle)
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_TIM1_Init();
HAL_TIM_Base_Start_IT(&h... | I would never use HAL library to set up the timers. It makes no sense for me. In the example below I will omit clock (in my case 168MHz) & GPIO settings. As you did not state what model of STM32F4 you use, this code was tested using STM32F446RET uC. Other STM32F4 have identical timers.
Setting the timer:
__HAL_RCC_... |
66,755,486 | 66,755,504 | C++ Call child function from parent | I am trying to call an overriden function from the parent, and found out that it just crashes.
This is quite hard to describe, so here the minimal reproducible code:
#include <iostream>
class A
{
public:
A()
{
init1();
}
void init1()
{
printf("1");
init2();
prin... | You can't call a derived class's overriden methods from within a base class constructor (or destructor). The derived class portion of the object doesn't exist yet.
So, to answer your questions:
yes A::A() is trying to call A::init2(), not B::init2(), and thus crashes from calling a pure virtual method.
There are way... |
66,755,714 | 66,755,794 | In C++, finding repeated peak values in array and calculating pulse | First of all I apologise in advance, I'm very new to programming and any help at all is greatly appreciated. I am using mbed to program a microcontroller:
my goal is to check an array for peak values:
void peakvals(int array[],const int count);{ //count = size array = 10, meant to find peak vals in array
int pe... | As I suggest in the comments, a simple function could looks like this:
int count_peaks(const int array[], const int arrsize)
{
int peakcount=0;
// NOTE: C++ index start at 0, so (arrsize-1) is the last element you can access in the array.
for (int i= 1; i < arrsize - 2; ++i... |
66,755,725 | 66,755,805 | C++ call class constructor from another class | I currently have a problem when I want to declare a class in another class. The following is my code. When I call the class Shape in the main function, there is no error. It turns out to be problematic if I want to define a Shape (myshape1) in Rectangle, it pops up the error:
class_constructor_derived.C:22:18: error: ‘... | The problem is that this code:
Shape myshape1(a,b); //something wrong here
...looks to the compiler like a function declaration. Except that when it looks up the meaning of a and b, it find that neither one is a type, which is what it would need to be for the function declaration to be valid.
The easy fix (assuming a ... |
66,755,743 | 66,773,139 | Gtk::StatusIcon system tray alignment issues | I'm creating a Gtk::StatusIcon object from a PNG file but the system tray icon displays in the center of the system tray.
How can I get this system tray icon alignment over to the right side by default. I've looked at the GTK::StatusIcon API but did not see anything.
Glib::RefPtr<Gtk::StatusIcon> m_status_icon;
m_statu... | From the official documentation, this does not seem possible in Gtkmm, or GTK+ (nothing in the API gives you such control). Also, note that Gtk::StatusIcon is deprecated in favor of plateform specific APIs.
|
66,755,775 | 66,756,006 | static_assert usage in C++ vs C | This is a part of a huge project, so I post an excerpt from a cc file (only one static_assert is needed in the real code, I just experimented with it):
namespace large
{
static_assert(sizeof(void *) == 4, "64-bit code generation is not supported."); // A
namespace fake_n
{
static_assert(sizeof(void *) == 4, "64-bi... |
Something in one of your headers appears to be doing #define static_assert _Static_assert, which fails in C++ because _Static_assert is a (reserved) identifier with no special meaning; in particular it doesn't perform a static assertion. I get the same errors in an example by manually adding #define static_assert _St... |
66,756,090 | 66,756,369 | Is an array of an object stored in stack or heap? | In the following code:
#include <iostream>
using namespace std ;
class TypeA {
public:
int a[10] ;
TypeA () {
int i ;
for ( i = 0; i != 9; i++) {
a[i] = double(i) ;
}
}
void printVal() {
int i ;
for ( i = 0; i != 9; i++) {
cout << a[i] << endl ;
}
}
~TypeA() {
//de... | Try this code:
#include <iostream>
#include <type_traits>
#include <cassert>
struct A{
A() {
std::cout<<"Called A() for "<<std::hex<<this<<'\n';
}
};
struct B {
A arr[10];
B() {
std::cout<<"Called B() for "<<std::hex<<this<<'\n';
}
};
int main() {
B* ptr = new B;
static_ass... |
66,756,148 | 66,756,278 | Implementing custom iterator in struct for custom linked list type | I have a linked list using std::list, that is of custom type "node" (std::list<node>) which is implemented through
struct node {
std::string pname;
int time;
};
I am wondering how I can create an iterator so that I can loop through my linked list to be able to print out the contents of 'pname' and 'time', or i... | It's pretty straightforward. Something a bit like this:
#include <iostream>
#include <list>
struct node {
std::string pname;
int time;
};
int main()
{
std::list<node> nodes {
{"test 1", 1},
{"test 2", 2},
};
for(auto& n: nodes) // range-based for
std::cout << n.pname << ":... |
66,756,295 | 66,771,227 | cannot find -lgsl, cannot find -lgslcblas | I am trying to install a R package on windows 10 using "R CMD INSTALL Rpkg" and I am getting the following error:
C:/rtools40/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lgsl
C:/rtools40/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.3.0/../../../../x86_64-w64-mi... | I figured out the solution for the issue. First of all, I do not need to install a separate gsl library to use with R. So, I removed the gsl library I installed earlier into C:\R_soft\R\local323. Then I opened the msys2 shell in rtools and ran pacman -S mingw-w64-x86_64-gsl. This installs gsl library to mingw64 folder... |
66,756,541 | 66,756,576 | Switch statement only executes last case? | I'm trying to execute a switch statement, but it will only execute the last case, excluding the default. So when I use this code:
switch (int)
{
case 1:
<code>
case 2:
<code>
case 3:
<code>
case default:
<code>
}
it executes case 3, no matter what I enter as int. But if I remove case 3, it executes cas... | You need to break properly.
switch (n) {
case 1:
/* code here */
break;
case 2:
/* code here */
break;
case 3:
/* code here */
break;
default:
/* code here */
break;
}
If you forget a break statement, it will fall through to the next case.
|
66,756,601 | 66,756,707 | What is the run time of this code in Theta notation? | I am struggling a bit with run time analysis and wanted to see if got those right.
I would greatly appreciate if someone could point out if I made any mistakes.
void f1(int* arr, int n){
for (int i = n; i > 0; i--) ---> time complexity = n
reverseArray(arr, i);
}
void reverseArray(int* arr, int n){
int l... | Time complexity of f1 is correct.
But in f2,
for (i = 0; i < n; i++) ---> time complexity = n
for (j = 1; j <= arr[i]; j++) ---> time complexity = n
c++;
the second for loop runs exactly for a[i] number of times for each i, but you have initialised arr[i] = 7; in previous for loop.
for (i = 0; i < ... |
66,756,802 | 66,756,891 | c++ change an object value in another class | I'd like to change the object brain in class Robot, not in main function. But the brain.brainData = 11; gives me an error:
class_constructor_another.C:11:3: error: ‘brain’ does not name a type
brain.brainData = 11; //something wrong
Here is the full code:
#include <iostream>
class RobotBrain{
public:
int brainD... | You cannot do inline member initialization in a procedural way like you're attempting. You must either define a constructor for RobotBrain that initializes the value, or a constructor for Robot that performs the non-encapsulated approach you're doing.
Option A:
class RobotBrain {
public:
int brainData = 10;
Robo... |
66,757,643 | 66,775,881 | Using vector in c++ and debugging it lead to Exception |
As mentioned in the title, on debugging C++ code an Exception occurred(as seen in the picture). How can I overcome it?
It's my code that induces Exception.
#include <iostream>
#include <vector>
int main()
{
int t;
std::cin >> t;
std::vector<int> v(t);
for(int i = 0; i < t; i++)
{
std::cin... | Thank you all guys.
I finally solve this problem. It occurred when debug mode has been changed x86 to x64 in VS.
but I still dont know why these exceptions occurred when debug mode is x64, I just guess that's maybe occurred when last debugging is proceeded on x86 mode at the same project.
|
66,757,672 | 66,757,952 | why floating point numbers does not give desired answer? | hey I am making small C++ program to calculate the value of sin(x) till 7 decimal points but when I calculate sin(PI/2) using this program it gives me 0.9999997 rather than 1.0000000 how can I solve this error?
I know of little bit why I'm getting this value as output, question is what should be my approach to solve th... |
sin(PI/2) ... it gives me 0.9999997 rather than 1.0000000
For values outside [-pi/4...+pi/4] the Taylor's sin/cos series converges slowly and suffers from cancelations of terms and overflow of int factorial(int n)**. Stay in the sweet range.
Consider using trig properties sin(x + pi/2) = cos(x), sin(x + pi) = -sin(x... |
66,757,693 | 66,757,744 | C++ no instance of overloaded function error in vector with unique_ptr | #include <iostream>
#include <memory>
#include <vector>
using namespace std;
typedef struct _cor {
int x;
int y;
} COR;
int main() {
int n;
cin >> n;
vector<unique_ptr<COR>> v;
v.reserve(n);
for (int i = 0, tmp1, tmp2; i < n; i++) {
cin >> tmp1, tmp2;
COR *temp = new CO... | You need to transfer (move) a unique_ptr into the vector slot instead of pushing a raw pointer.
Instead of this:
COR *temp = new COR{tmp1, tmp2};
v.push_back(temp);
This:
std::unique_ptr<COR> uptr = unique_ptr<COR>(new COR{ tmp1, tmp2 });
v.push_back(std::move(uptr));
Or better yet, take advantage of ... |
66,757,768 | 66,759,018 | Calling class function without objects | The following code:
#include <iostream>
#include <string>
using namespace std;
class ABC
{
public:
void display ()
{
cout<<"ehhh";
}
};
int main ()
{
using xyz = ABC;
xyz::display();
}
Throws an error:
main.cpp:19:16: error: cannot call member function ‘void ABC::display()’ without... | Calling a non-static function of a class requires creation of an object.
You can call the function using the code by creating an object or by declaring the function as static.
// Calling display function by creating an object.
#include <iostream>
#include <string>
using namespace std;
class ABC
{
public:
void ... |
66,757,846 | 66,758,857 | Why does it give me no match for operator the operand types are std:: basic stream and void in line 45 | Hey I am c++ newbie I am trying to display a vector, reverse it and rotate it in the same program I have passed the vector as Reference to avoid copying but it keeps giving me error I really don't know what's wrong.
Here below is my code:
#include<iostream>
#include<stdio.h>
#include<string>
#include<algorithm>
#includ... | The mistake you are making is that you are trying to print the output of the function call but the function do not return anything. You have several other problems in your code which I have also fixed. You can instead write your codes as follows:
#include<iostream>
#include<stdio.h>
#include<string>
#include<algorithm>... |
66,757,982 | 66,758,808 | Is there any way to force openmp to get desired number of threads? | I'm trying various ways to set my number of threads by either using clause or setting in the environment, but none of them has worked. Is there any way to force OpenMP to get a custom number of threads?
#include <cmath>
#include <random>
#include <iostream>
#include <chrono>
#include <cfloat>
#include <iomanip>
#includ... |
#pragma omp num_threads(6) reduction(+ : sum) //default(none)
{
//OMP_NUM_THREADS=6;
omp_set_num_threads(6);
This is wrong, you need to set the number of threads before the parallel region. Furthermore, you are missing the parallel clause there. So you can either do:
omp_set_num_threads(6)
#pragma omp parallel r... |
66,758,070 | 66,758,404 | The size of closure (lambda function) not same as std::function or pointer | #include <iostream>
#include <functional>
std::function<int(int)> makeLambda1(int x) {
return [x] (int y) { return x * y; };
}
auto makeLambda2(int x) {
return [x] (int y) { return x * y; };
}
auto makeLambda3() {
return [] (int y) { return 10 * y; };
}
int main() {
auto lambda1 = makeLambda1(10);
auto la... | Lambdas are just syntactic sugar for objects with an overloaded operator(). That means that
return [x] (int y) { return x * y; };
is equivalent to
class unique_unnamed_type
{
private:
const int x;
public:
unique_unnamed_type(int x) : x{x} {}
auto operator()(int y) { return x * y; } const
};
return unique_... |
66,758,621 | 66,758,661 | Is it good practice to initialize a member variable of a class in the header file? | Let's say I have a pointer and I want it to be initialized to nullptr. Which option would be better, to create a constructor that sets that member variable to nullptr or just initialize it in the declaration on the header file to nullptr.
Is there any differences at all? Is the latter considered bad practice?
Thanks in... | Initializing a member in the class body is completely equivalent to doing it in the member initializer list in the construcor. (But if you provide initializers in both places, member-init-list overrides initializers in class body.)
Initializing in the class body whenever possible is a good practice, because it's less e... |
66,758,823 | 66,759,384 | No Matching function to call. C++ STL | I'm new to C++ STL. I'm writing a function to check whether one vector is an subset of another(Duplicate elements also count) and print 'Yes' or 'No'. I have come up with the following code :
void checkMagazine(vector<string> magazine, vector<string> note) {
vector<string>::iterator a;
for(int i=0;i<note.size()... | erase takes an iterator. You have that iterator, it's called a. But you then convert the iterator a into an offset relative to begin(). erase does not have an overload which takes an offset.
The Standard Library has alternatives if the vectors would be sorted, but we don't see the calling code so we can't assume that.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.