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 |
|---|---|---|---|---|
61,811,211 | 61,811,344 | Why declare global variables in file doesn't include? (c++) | An unexpected result occurred when testing both Windows-VS-environment and Linux-Cmake-environment.
A global variable was declared, even though it is not in included file.
Here is Example codes.
CmakeLists.txt
ADD_EXECUTABLE( app.out main.cpp test.cpp )
main.cpp
int main()
{
return 0;
}
test.h
#pragma once
#in... | The short answer here is, simply, because this is how C++ works.
static Test g_test;
This instantiates an object of type Test in the test.cpp translation unit. Whether or not it is declared in some header file is immaterial. It is instantiated. So it exists. You are alive because you, yourself exist and not because yo... |
61,811,384 | 63,102,752 | Compiler to C++20 on Windows | I need a compiler that supports c++20, like GCC 10.1 (used on linux), but to use it in my Windows 10.
I saw posts that recommend Mingw-w64, but does it supports c++20?
| In the meantime GCC 10 has been released and MinGW builds are available.
You can download a standalone build of MinGW-w64 with GCC 10 for Windows 32-bit and 64-bit from http://winlibs.com/
|
61,811,459 | 61,868,392 | Unreal Engine 4.24.3: No instance of constructor Error when declaring TArray<FString> in a header file | I've been trying to create a header file that will declare a TArray of FStrings but keep getting the following compiler error:
"C++ no instance of constructor matches the argument list argument types are: (const wchar_t [6], const wchar_t [6], const wchar_t [6], const wchar_t [6], const wchar_t [6])"
I have... | It seems ok, and it compiles in my VStudio, I am not sure about that error, but to be exact the error says that you created a TArray of "FString" items and you are adding TEXT("abcd") which is of type "wchar_t*".
Try this one:
#include "CoreMinimal.h"
const TArray<wchar_t*> WordList = {
TEXT("chart"),
TEXT("quest"),
T... |
61,811,646 | 61,811,755 | Implementing a Generic Double linked list in c++ | I have implemented a fairly simple idea of a double linked list. I don't know what am I doing wrong!
I have tried making the member variables of the node as public but doesn't help. Friend class doesn't help either. What is the nonclass type here?
d_list.h
#include "node.h"
#ifndef NODE_H
#define NODE_H
template<c... | The thing is that head and tail shouldn't be T, but rather node<T>:
Node<T>* head;
Node<T>* tail;
Remember, T is the type of object you want to hold in your list. It has no link associated with it. So if you do a d_list<int> currently as written, the templated code will look something like this:
int* head;
int* tail;
... |
61,812,104 | 61,812,123 | Hashtag symbol in C++ macro expression | In the macro definition below, what does '#' symbol do? What is this syntax (#x) here?
#define print(x) cout<<(#x)<<" : "<<x<<endl;
| # is the stringify operator. It turns the macro argument x into a string literal.
I can see no reason for the extra parens, #define print(x) cout << #x <<" : " << x << endl; would work just as well. Even better would be #define print(x) cout << #x <<" : " << (x) << endl; because the second use of x might require parens... |
61,812,811 | 61,812,875 | C++ Standard Template Library simple code giving error in vs code in macos mojave | I am working in STL in c++ in the vs code editor and i have declared an array as given in the code below...
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<int> arr={11,2,13};
for(int i=0;i<3;++i)
cout<<arr[i]<<" ";
return 0;
}
I am getting the error tha... | It seems the compiler does not support c++11.
you can use -std=c++11 and try again.
eg. g++ -std=c++11 -c example.cpp
And also can get more info form this why am I getting “non-aggregate cannot be initialized with initializer list
|
61,812,899 | 61,813,640 | Solving the SPOJ Problems | I'm trying out to solve this problem,
with this reference cpp codes.
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
long double integral(long double h,long double w,long double f,long double x)
{
return -(w-2*x)*sqrt((w*w*w*w+16*h*h*(w-2*x)*(w-2*x))/(w*w*w*w))/4
-(w*w*asinh(4*h*(w-2*x)/(... | A C++ pair is basically a struct of two elements in C.
You replace
pair<<long double,long double> res;
with (note that your code has a ; res; that has to be fixed)
typedef struct {
long double first;
long double second;
} pair;
pair res; // <====
For convenience you could add (in C, a function can return a s... |
61,813,116 | 61,814,080 | What is the most efficient algorithm to find the max element of a Symetric Matrix | I actually want to know how it's the best way to pick the maximum integer (the one with bigger value) of a matrix in c++ such data structure is a map<string, map<string,int>> both ordered in growing lexicographic order. Actually my function returns a pair of where the maximum element is indexed. Thank you for your ti... | Searching whole matrix (O(n²)) would be:
std::map<std::string, std::map<std::string,int>> matrix;
int m = matrix.begin()->second.begin()->second; // Assuming non empty
for (const auto& row : matrix) {
for (const auto& p : row.second) {
m = std::max(m, p.second);
}
}
map doesn't have random access, so ... |
61,813,235 | 61,813,521 | Find if the binary search tree has duplicated value | For binary search tree to see if the tree has duplicated value or not. I took this post order approach.
My goal was to keep the value of the current node and then use other function traverse the tree to see if there is any matching value to that current value, and if it finds any duplicate value it brings "true value"... | Your checking function should look like this:
bool checking(BSTNode* parent, int val) {
if(parent == nullptr) // point 1
return false;
if (val == parent->data){ // point 2
return true;
}
else{
bool left = checking(parent->left, val);
bool right = checking(parent->righ... |
61,813,983 | 61,820,468 | Big O and Theta for loop | for(int i = 2; i < n*n; i = i*i)
for(int j = 1; j < i; j++)
im really confused on how the n*n and i*i affect each other
my assumption is that it is O(n^2loglogn)
but i dont really know how to derive it
| I'm leaning a little bit out of my base knowledge, so take the following with a grain of salt.
For the raw topic:
Your iterator forms the series 2, 22, 222, 2222...
This is known as Tetration.
Tetration has two inverse functions, which are the super-root and the super-logarithm. The latter is relevant here, as we have ... |
61,814,578 | 61,815,036 | Why c++ program generating different output for the same input? | I am implementing matrix chain multiplication program in c++. I am using ONLINE_JUDGE flag to write output to the file. When i run the program it does not produce correct output in file, but it is producing correct output in console.
My Program:
#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONL... | Include it in your program std::ios::sync_with_stdio(true); on the top of every statement. It also happened with me. Including this, in your program, cout and printf will become thread-safe. Make sure the argument must be true.
|
61,814,745 | 61,814,913 | Generalised std::function (std::any for callable objects) | How can I create a variable of generalised std::function type that can take any callable objects? I can't use variadic templates because it'll create a family of different types, while I need a single type, so that I can take different [&] lambdas to a same array.
I did it with functors (example below) that produce std... | Just stuff lambdas into std::function<void()>.
using OperationFunctor = std::function<void()>;
using ChoiceArray = std::vector<OperationFunctor>;
int GetInt(int restriction);
class MenuFunctor {
private:
std::string output;
ChoiceArray arrayOfFunctions;
public:
MenuFunctor(std::string n_output, ChoiceArra... |
61,815,049 | 61,815,199 | The substring shouldnotexist in an operand causes std::string concatenation by + operator to return an empty string | Background - I was writing a benchmark to measure the cost of stat on a missing file and appended the string "shouldNotExist" to the end of a filepath to do so.
e.g. /foo should become /fooshouldNotExist
However, the code was just trying to stat an empty string "".
After digging a little deeper, I noticed that when con... | c_str gives you a pointer to the contents of a string instance to use in plain-C functions (like printf). However, when you apply it on a temporary string instance created by e.g. concatenation, it is invalidated immediately afterwards, as the temporary object goes out of scope:
A temporary string instance for the con... |
61,815,243 | 61,815,467 | How to do lower_bound on vector of objects | i was wondering if it is possible to do lower_bound on vector of objects, but without overloading operator< ? To be more precise i have vector of objects, which have one attribute (one of many). I'm pushing objects inside that vector as i order so i know it is sorted. Attribute which i mentioned is changing, to be more... | Something like this (untested code)
std::vector<int> nums { 1,2,3,4,5 };
auto res = std::lower_bound(nums.begin(), nums.end(), 3, [](const int& a, const int& b){ return a<b;});
|
61,816,012 | 61,816,597 | C++ - Decrypting a string from file | As you can see from the title I need to decrypt the strings in a text file. I have major problems with this so if you can help me I would really appreciate it.
First of all, here is the input file:
saoreecessinntfi
pmrrj ie2
borj
I want to decrypt these words like this:
sesnaestocifreni
primjer 2
broj
I have used the... | I think this should work just the fine for your case:
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
int matrixSize(std::string &str) {
auto x = sqrt(str.length());
return x - floor(x) == 0 ? x : 0;
}
int main() {
std::fstream file("test.txt");
std::string str;
while (st... |
61,816,306 | 61,822,162 | Windbg syntax - combining two commands (MASM and C++) into one | My apologies if I should know this, but I know that someone else will know straight away if it's possible (and I'd assume it is) and then I can know for the future. But is it possible to combine these two commands into one?
0:006> ? @@(this->m_pSession->m_SessionContext._Mypair._Myval2._Bx._Buf)
Evaluate expression: 16... | i don't know why use convouluted strategies
I hope you understand the implementation of std::string and sso (short string optimization)
I hope you understand any string that crosses a threshold cannot be printed with _Buf
but need to be printed via its _Ptr
why not use just c++ or use the convenience functions
... |
61,816,310 | 61,817,536 | Gmock: returning an invalid value | The strange behavior of the return value of the function when using the enum class, before that, int was used and the test passed successfully.
enum class rvalue
{
ok = 0,
bad = 1,
other = 2,
};
class Speeder
{
public slots:
rvalue Run(int speed)
{
if (speed < 0)
return rvalue::... | Unless specified otherwise, mock would return default value.
It doesn't call base class implementation.
|
61,816,478 | 61,818,762 | Edit Single YAML value without updating the formatting of rest of YAML (YAML CPP) | I already have a YAML file. I want to just change a single value inside that YAML file. I found yaml-cpp library being used widely for parsing/editing yaml files from c++ code. Is there a way I can update single value and leave the rest of the file untouched?
I have a YAML file like this already. And I just want to upd... | From the YAML documentation https://yaml.org/spec/1.2/spec.html#id2767100:
Comments are a presentation detail and must not have any effect on the
serialization tree or representation graph.
YAML will remove the comments by design.
A solution would be to edit the file manually: C++ overwriting data in a file at a pa... |
61,816,693 | 61,816,882 | simple calculator in c++ weird results | I am new to c++
I tried to create a simple calculator.
I am not sure why but when I run this code, it prints weird results, for example: 15 * 5 = 753
int a;
int b;
char param;
printf("Enter Two numbers:\n");
scanf_s("%d %d", &a, &b);
printf("%d %d\n", a, b);
prin... | There is no break between cases which explain that your example enter in case '*' print 75 (15 * 5) as there is no break continue to '/' and print 3 (15 / 5). And that's what you got 753.
switch (param)
{
case ('+'):
result = a + b;
printf("%d", result);
break;
case ('-'):
result = a - b;
printf("%d... |
61,816,720 | 61,817,020 | Issues with animation - translation, projection OpenGL/C++ | Recently I had this issue. Now that I've fixed that with given solution, I ran into some other issues. Here is a gif of the animation I have to achieve.
Issues I have now are: the ball in my animation doesn't look like it's moving forwards and backwards like it is at the beginning of the .gif. I do believe this has som... | If you want a perspective projection, where the size of the objects is relative to screen resolution and independent on the the size of the window, then you have to compute the filed of view angle in relation to the height of the window:
void reshape(int w, int h) {
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
gl... |
61,816,809 | 61,817,019 | How to correctly forward declare struct with "using XXX"? | There is a header file "api.h" that I have to use, and I can NOT modify it, but all names of the structs in it are too long and with less readability, also the naming style of them is not similar to my project.
e.g. in file "api.h":
#pragma once
struct AVERYVERYLONGLONGNAMEOFSTRUCT1 {
...
};
struct AVERYVERYLONGLON... | Put only the forward declarations in the header and include that header:
// common.h
// dont include api.h here !
struct AVERYVERYLONGLONGNAMEOFSTRUCT1;
using ContraDef_t = AVERYVERYLONGLONGNAMEOFSTRUCT1;
// my_class.h
#include "common.h"
struct my_class{
ContraDef_t* c;
};
// my_class.cpp
#include "my_class.h"
... |
61,817,015 | 61,817,173 | Print star pattern in c++ | I'm having trouble finding out how to start with a problem that asks to print for an integer, suppose 3,
*
**
*
***
*
**
*
And so far I only have
void print(int n)
{
if (n < 1) {
return;
}
if (n == 1) {
cout << "*" << endl;
return;
}
print_star(n - 1);
for (int i = 0; ... | You forgot to print again the case n-1after printing the nstars.
For example, for n = 2, adding this new print will replace
*
**
by
*
**
*
Same for higher values of n
#include <iostream>
void print_stars (int n) {
if (n < 1) return;
if (n == 1) {
std::cout << '*' << "\n";
} else {
prin... |
61,817,122 | 61,817,218 | c++ reference function parameter seems to contain a copy of the original object, not acts as a "real reference" | sorry for the newbie question. :)
the reference function parameter is connected to an object, but a modification on the reference has no effect to the original object.
Simplyfied code:
struct dummy{
int i;
};
dummy arr[4];
// fill array
for(int n=0;n<4;n++){
arr[n].i = n;
}
void foo(dummy& d){
d = arr[0];... | So I think your misunderstanding is over the line
d = arr[0];
You think that makes d refer to arr[0] but it doesn't. Instead it assigns arr[0] to whatever d is referring to.
In C++, once a reference has been bound it cannot be rebound. Any attempt to assign to a reference always assigns to what the reference is referi... |
61,817,328 | 61,817,664 | Why is "int" not working correctly with "j" but long long is working fine? | This is my code with int j:
void solve(){
unsigned long long n;
cin>>n;
unsigned long long sum = 0;
int j = 1;
for(int i=3;i<n+1;i+=2){
sum += ((4*i)-4)*(j);
j++;
}
cout<<sum<<"\n";
}
Input:
499993
Output:
6229295798864
but it is giving wrong output, and here is my cod... | Notice that the result of ((4*i)-4)*(j) is an int, since both i and j are int types. The right hand side is promoted to unsigned long long only when adding ((4*i)-4)*(j) to sum. But the expression ((4*i)-4)*(j) already overflows the size of the int type for a large enough n before being promoted.
However, if you change... |
61,817,363 | 61,817,504 | what does std::move(const shared_ptr reference) mean? | The following is toy code I am trying... I understand the first and second one. The first one give the ownership to _p. The second one copies p to _p.
but I don't understand the third one...
What does std::move of const shared_ptr & mean? Thank you.
class P { };
class A {
public:
// first one
A(std::shared_pt... | std::move is a function which converts the argument to an rvalue reference. The function call is an xvalue expression.
When the argument is a reference to const, then the result of the conversion is an rvalue to const. If you initialise from rvalue to const, copy constructor will be used because the rvalue reference pa... |
61,817,665 | 61,819,516 | I'm getting a "redefinition of" error for every method in the class | I'm getting a redefinition error for every method in the class. I tried to put the .cpp code in the header where the "include Algebra.cpp" is, but didn't change a thing.
// This is the .h file
#ifndef ALGEBRA_H
#define ALGEBRA_H
#include <iostream>
template <size_t rows, size_t cols>
class Matrix {
double** mat... | First, that template function definition belongs in the header file that gets pulled in wherever it's needed with #include "algebra.h".
The reason you're getting problems with this particular setup is that, as several comments have suggested, you're compiling the .cpp file that contains that template function definitio... |
61,818,580 | 61,818,637 | C++ Can't figure out why its giving false positive (newbie) | Hey so I recently started learning C++ and I can't figure out why this problem is giving a false positive all the time.
Maybe someone can help?
// [Included stuff]
using namespace std;
int main() {
int erg = 5;
int inp;
cout << "Answer: 3 + 2: ";
cin >> inp;
if (inp == erg) {
cout << "... | The condition in this if statement
if (inp <= erg || inp >= erg) {
cout << "False!";
}
means that inp can be equal to any number. That is the condition is always evaluates to true so the enclosed statement
cout << "False!";
is outputted.
It seems you mean either
if (inp != erg) {
cout << "False!";
}
or (... |
61,818,747 | 61,828,382 | What's clang-format's equivalent to rustfmt's indent_style=Block? | If clang-format was rustfmt, it would have this all-encompassing indent_style config option, which refers to this basic distinction in indentation style:
Visual (default in clang-format):
ReturnType<std::vector<int>> ClassName::functionName(int a,
bool b,
... |
What can be configured:
(covers functions, ctor init lists and enums, but not lists)
AlignAfterOpenBracket: AlwaysBreak
BreakConstructorInitializers: BeforeComma
BinPackArguments: 'false'
BinPackParameters: 'false'
The BinPack* options are not strictly there for the block indentation,
but to do like the question show... |
61,818,759 | 61,819,117 | Sorting products in a file by price | I have the products.txt file:
Chocolate 5 250
Car 5000 1
Chips 3 350
...
As you can see the data is arranged in order: name, price, quantity. I need to sort the products by price. I have already determined how many products are in the file and what is the total value of all products.
I have a structure:
struct produ... | You should first read the data, write it to a vector, sort it and then write the sorted data in the desired format to a *.txt file. The std::sort function allows you to define how to compare two objects. You can do something like this:
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
struct... |
61,818,776 | 61,819,182 | C++ atof - Segmentation fault (core dumped) | I'm working on a simple C++ application, but this is the first time I'm using command line arguments.
It actually worked fine, until i added the option for the program to calculate more numbers than one at a time.
I use the following code to convert the argv to a float. (Well the code that's relevant in this case)
if (... | Instead of argc = 3 write argc == 3. Always be careful with assignment and equality check in C-style languages :)
|
61,819,277 | 61,820,340 | How to zip vector of vector with range-v3 | (This is a follow-on to Sum vector with range-v3)
If I have two (or more) vectors, I can zip them together with range-v3 like this:
std::vector< int > v1{1,1,1};
std::vector< int > v2{2,2,2};
auto v = ranges::views::zip( v1, v2 )
| ranges::views::transform( ... );
This works well, but in practice, I don't have expl... | I suppose if you don't know the size of external vector in compile time the only reasonable solution that remains is work around it. Instead of trying to zip it I would suggest going with accumulate on top of that as it seems more versatile in this situation.
std::vector< std::vector< int > > V{{1,1,1},{2,2,2}};
auto ... |
61,819,856 | 61,821,728 | How to get message from other thread winapi | I need to run message loop in other thread using std::async, is it possible to get messages from main thread? Can you give some exampels?
And second question: i do not need to call wndproc, what i need is just getting messages and avoid "program not responding", do i need to call dispatchmessage()?
| Each thread manages its own message queue. If you want the main thread's messages, the main thread must get them and post them to you. But it sounds like that would defeat the purpose altogether.
Sounds like what you really want is to switch your threads' places. Have the main thread run your message pump and do your... |
61,819,866 | 61,820,045 | How to implement a blocking processing loop? | I'd like to implement a processing loop in a worker thread so that it processes data from a queue when there's something and blocks (the thread sleeps) otherwise...is this even possible? Should also work without any noticeable delays.
Something simple like this:
std::deque<Foo> queue;
void worker()
{
while (activ... | There is something that will suit your needs in C++11 standard. It is condition_variable. It allows you to wait until it is notified by other thread. So your worker could wait until producer notifies it like this. Note this is very dumbed down example and in most situations insufficent but gives you gist how to do it
s... |
61,820,171 | 61,820,493 | Explain syntax for returning array by reference from a function | The syntax of function in C++ is:
return_type function_name(parameter1, parameter2, ...)
{
// function body
}
I have some doubts regarding "returning reference of an array from a function":
Return type is specified first then function name but to return reference of an array it is written as:
// for array of siz... |
why?
Because Dennis Ritchie designed it to be so in C, and because C++ was designed to be compatible with C.
There weren't references in C of course, but references follow the same syntax rules as pointers do, which were inherited from C.
The main confusion however doesn't seem to be about where the reference puncu... |
61,820,401 | 62,391,278 | Boost build fails to generate visual studio manifest file | I'm attempting to build Boost from source and running into an odd issue. Some Windows machines can compile this just fine and others fail even though they're all running the same version of Visual Studio. This worked on all machines using Boost 1.62 but is failing with Boost 1.72.
Here's the Boost build command:
b2 -j... | For posterity, the team upgraded to Visual Studio 2019. This at least worked around the issue for most of us. A few folks still have issues.
|
61,821,195 | 61,821,655 | Overloading operator>> C++ | I have a problem with operator>> when I try to use it in my class String. I need to make a string from keyboard, but all my tries make fails. Help me, please.
When I try to turn in this code, I always have a crash.
#include<iostream>
#include<fstream>
using namespace std;
class myString
{
public:
friend std::ost... | You are trying to read to a pointer initialized with nullptr and you use sizeof() of that pointer when you have length data member. Since you already defined assignment operator for char array you can just use it:
istream& operator >> (istream& in, myString& other)
{
char buffer[256];
in.getline(buffer, sizeof(... |
61,821,265 | 61,975,968 | Warning: left shift count >= width of type when reading bytestream into double variable in C++ | I'm trying to read a bytestream into a double variable in C++.
So my code for this is the following:
double foo;
foo = bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24) | (bytes[44] << 32) | (bytes[5] << 40) | (bytes[6] << 48) | (bytes[7] << 56);
As you can see I'm trying to read in 64 bits. And even th... | I found out a solution for myself - but thanks to all the comments!
I tried memcpy() and that worked fine.
I solved it like this:
foo = bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24) | ((uint64_t)bytes[44] << 32) | ((uint64_t)bytes[5] << 40) | ((uint64_t)bytes[6] << 48) | ((uint64_t)bytes[7] << 56);
|
61,821,291 | 61,822,478 | How to generate the C and C++ header file for a C++ library/class? | I've developed a custom C++ linux library to control a device through my driver. The library controls the flow to correctly use the device and I'd like my users to be able to call the "lib/API" from C and C++ app.
Basically the library is just a class containing public and private/protected variables and methods.
The u... | I think this link answered my question about the C header:
Can I use shared library created in C++ in a C program?
For the C++ header hiding private/protected, I discovered the PIMPL idiom that seems perfect. Thanks Caleth.
|
61,821,353 | 61,821,621 | C++ compilation issue error - C2332: <class: missing tag name> | VS 2005 -> Compilation without any errors.
VS 2010 -> Compilation with any errors.
e.g. code snippet
template< bool f > struct static_assert;
template<> struct static_assert<true> { static_assert() {} };
Compiler Error:
error C2332: 'struct': missing tag name
e.g. code snippet
template< typename T >
class ab... | In your first code snippet, the problem is that static_assert became a reserved keyword in the C++11 Standard (VS-2010 seems to be using this), whereas it was an 'allowed' identifier in previous versions of the language (such as the VS-2005 compiler was using). To resolve this issue, change the name of your structure, ... |
61,821,448 | 61,822,017 | emplace_back modify the value in parameter | I'm writing some code and figured out a problem with emplace_back on vector.
void generateTube(std::vector<glm::vec3> &vertices, const glm::vec3 &pos) {
glm::vec3 N, B;
float cos, sin;
...
for (int i = 0 ; i < 2 ; i++) {
...
std::cout << pos << std::endl;
vertices.emplace_back(pos + cos ... |
Yes pos refer to an element of vertices...
That's the problem. During emplace_back, reallocation of vector elements may be triggered, which invalidates all iterators/refernces/pointers to vector elements, including pos. Dereferencing pos then causes undefined behavior.
A simple remedy might be to reserve enough vecto... |
61,821,721 | 61,823,797 | User interface compiler Qt | i have created a UI with the Qt Designer, i want to integrate it into my cpp program now.
I have to convert the main_window.ui to a header file?
Supposedly it should be a possibility via the Designer Form->View Code to give a cpp code to this class which I can copy directly into a header file?
Unfortunately I get th... | Most of the time you don't need to call uic manually: just add the .ui files to your .pro files as "FORMS", and qmake will take care of the rest. See for example: https://doc.qt.io/qt-5/qmake-variable-reference.html#forms and https://doc.qt.io/qt-5/designer-using-a-ui-file.html
|
61,821,925 | 61,825,364 | Variable length array error with constexpr | I have a class with a member function which declares an array whose size is based off a formula.
template <int SIZE>
class Example{
constexpr int lookup(const int n) const
{
return n * n + n;
}
inline void func()
{
double array[lookup(SIZE)];
}
};
This gives me the vla error. I think it ... | It's complicated...
First of all, some compilers (see MikeCAT answer and Bill Lynch linked example) can compile the following code (if you give a name to the class and correct lookup() naming n the argument)
inline void func()
{
double array[lookup(SIZE)];
}
because they support a C99 extension that accept the "va... |
61,821,969 | 61,822,164 | Level of exception handling / rethrowing an exception | I have a function that basically returns an element from a vector using at(size_type pos). at() throws an std::out_of_range exception in case of an invalid (out_of_range) position.
I basically want this exception to be propagated to the caller, so that it can be handled on that level. Would the rethrow that I've added... | The exception thrown by std::vector::at(), as any other exception (someone correct me if I'm wrong), will unwind the stack until it reaches a try-catch block where it is caught, or cause an unhandled exception error if it isn't caught at any level.
Therefore, if your only intent is to catch it at the caller level, wit... |
61,822,232 | 62,444,934 | C++/CLI converting managed MathNet Matrix to Eigen MatrixXi for use in native class | I'm trying to build a managed wrapper for a native C++ class that holds an Eigen::MatrixXi. Let's say the native class has one member matrix that it stores and gets through its constructor, and a method that uses that member at a later time:
#include <Eigen/Dense>
#include <Eigen/Core>
#include <iostream>
using Eigen:... | I found this to be the cleanest way to do it:
static Eigen::MatrixXf MathNetToEigen(MathNet::Numerics::LinearAlgebra::Matrix<float>^ data)
{
auto mat = Eigen::MatrixXf(data->RowCount, data->ColumnCount);
for (size_t i = 0; i < data->RowCount; i++)
for (size_t j = 0; j < data->ColumnCount; j++)
... |
61,822,625 | 61,822,994 | std::map emplace non-movable non-copyable non-default-constructible type | I want a map of a class that has no copy ctor, no move ctor, and no default ctor (I have no control over this class).
I've tried using std::map::emplace with the std::piecewise_construct and std::forward_as_tuple arguments, but it seems like the compiler is telling me that this is not possible because it tries default ... | There's no issue with the emplace operation, however, the issue is with std::map::operator[] since it requires the value_type to be default constructible. However, stone has a deleted default constructor.
Instead, you could use std::map::at which does not have that requirement:
std::cout << "map[5]: " << m.at(5).str <<... |
61,822,809 | 61,823,017 | Find pairs in an array such that a+b%10 = k | There is a ordered list like
A=[7, 9, 10, 11, 12, 13, 20]
and I have to find pairs a+b%10=k where 0<=k<=9
For example k = 0
Pairs: (7, 13), (9, 11), (10, 20)
How can i find the number of pairs in O(n) time?
I tried to find convert all the list with take mod(10)
for (auto i : A) {
if (i <= k) {
B.push_back(... | Let’s begin with a simple example. Assume that k = 0. That means that we want to find the number of pairs that sum up to a multiple of 10. What would those pairs look like? Well, they could be formed by
adding up a number whose last digit is 1 with a number whose last digit is 9,
adding up a number whose last digit is... |
61,822,881 | 61,838,923 | Add xml namespace to xml_document using pugixml | How can I add an xml namespace declaration to my xml_document using pugixml?
I tried this, which results in a invalid xml (invalid char ":", says my validator):
xml_document doc;
auto declarationNode = doc.append_child(node_declaration);
declarationNode.append_attribute("xmlns\:xsi") = "http://www.w3.org/2001/XMLSche... | I'm quoting zeux, the creator of pugixml, who was so kind to answer this question here on github
This code appends the xmlns attribute to the node; you should
append it to the document element instead:
doc.document_element().append_attribute("xmlns:xsi") = "http://www.w3.org/2001/XMLSchema-instance";
The code I ... |
61,823,137 | 61,823,236 | Why does a const reference to a reference lose its constness? | Given this code:
#include <iostream>
template<typename T>
void modify(const T &j){ j = 42; } // j has type int&
int main()
{
int i = 10;
modify<int&>(i); // T=int&
std::cout << i; // 42 is printed
}
Why does const T &j become int &j if T=int&? What happens to const?
| There is no such thing as reference to a reference i.e. there is no T & &.
Given a const T& where T is int&, the type collapses into int&.
What happens to const?
There is no such thing as a const reference either i.e. there is no T & const (not to be confused with reference to const, which does exist and which is qui... |
61,823,442 | 61,823,499 | How to print two coordinates from class? | I have been trying to print the points like The position of the point is (1,2) from using class, but I can't figure out a way to do it. I simply can't find a way to return two numbers like that, but the problem requires solution that way.
#include <iostream>
using namespace std;
class MyPoint{
public:
int ... | Your point_display could return a string composed of the 2 values:
std::string point_display()
{
return std::string{"("} + std::to_string(x)
+ "," + std::to_string(x) + ")";
}
Alternatively, as your question asks about returning 2 values, the function could return a pair:
std::pair<int,int> point_display ()... |
61,824,205 | 61,825,107 | Specialization of a template with enable_if in header file | So i want to make 2 functions: one for numbers(with template) and one for strings.
Here's my best try:
Header:
class myIO
{
public:
template<class Arithmetic,
class = enable_if_t< is_arithmetic_v <Arithmetic>>
>
static Arithmetic Input();
template<>
static string Input<string, void>();
};
... | Here is the answer:
.h:
class myIO
{
public:
template<class Arithmetic,
class = enable_if_t< is_arithmetic_v <Arithmetic>>
>
static Arithmetic Input();
template<class String,
class = enable_if_t< is_same_v<String, string> >
>
static string Input();
};
.cpp:
template<class Arit... |
61,824,398 | 61,824,665 | I encountered some thing weird code in Dynamic memory allocation for 2D arrays in C++? please explain me what is this? | code:- p = new int *[5]; where p is a pointer & declared as int **P; Please explain me that why there is a * in between new and [5].
| When allocating an array using new you need to specify the type. The general pattern is:
type* x = new type[n];
Where type is the base type, x is the variable, and n is the number of entries. You can make this a pointer type by adding * to both sides:
type** x = new type*[n];
You can continue this indefinitely:
type*... |
61,824,469 | 61,824,908 | Memory leak identified by valgrind involving use of malloc to return a string that was returned via a std::string | I've been hitting 'memory problems' in my python (ctypes) interface to a c++ library. So I ran my C++/C API tests through valgrind which is suggesting that the following function is a problem:
char *PhysicalEntity_str(PhysicalEntity *physical_entity_ptr, const char *format, const char *base_uri) {
std::st... |
char *cstr = (char *) malloc(str.size());
This function allocates memory. If the returned pointed is never deallocated with free, then it means that the memory was leaked.
suggest a workaround?
Deallocate everything that you allocate.
This is easier if you avoid the use of bare owning pointers. Use smart pointers ... |
61,825,369 | 61,825,411 | Structure binding doesn't work without type? | I try to do something like this
pair<int, int> f() {
return {1, 2};
}
int a, b;
[a, b] = f();
and get compilation error. All errors boil down to that fact, that the compiler think that it is a syntactically incorrect lambda. So if I use structured binding I always should write auto?
| Yes, that's just how structured bindings work. It introduces new identifiers, so they cannot be existing variables. So when using it, you must use auto, e.g.
auto [a, b] = f(); // can also be auto&, auto const, etc
If you want to use existing variables, you can use std::tie:
int a, b;
std::tie(a, b) = f();
Note tha... |
61,825,378 | 61,825,470 | How to write this do...while from C++ to Python? | How to write this do...while from C++ to Python??
I looked at a lot of topics, but I don’t understand how to write with such functionality
do
{ L = 0; x = a; h = h / 2;
while (x < b) {
y1 = fC(x);
y2 = fC(x+h);
L = L + sqrt(h * h + (y2-y1) * (y2-y1));
x ... | while True: # do --> while True:
L = 0
x = a
h = h / 2
while x < b:
y1 = fC(x)
y2 = fC(x+h)
L = L + sqrt(h * h + (y2-y1) * (y2-y1))
x = x + h
L = L * 2
if fabs(L0 - L) / L0 > 0.0001: break # do's while --> if ... : break
|
61,825,796 | 61,826,094 | XString breakpoint thrown when defining string | Hello i've had this break point being thrown by xstring for the last two days and I can't seem to get rid of it. First off the class i'm working with or at least the relevant bit.
class myProjects {
public:
std::wstring wstr;
const wchar_t* BrowserPtr = wstr.c_str();
std::string browser = "undeffined";
};
... | A possible problem can be found in class myProjects:
class myProjects {
public:
std::wstring wstr;
const wchar_t* BrowserPtr = wstr.c_str();
std::string browser;
};
When a variable of type myProjects is constructed, first wstr is constructed with an empty string, then BrowserPtr is initialized with a point... |
61,825,882 | 61,826,010 | error C2065: 'firstName': undeclared identifier | So I have my header and my CPP for that class. My understanding is that although StudentID is a private variable in StudentClass.h I assign it to
StudentID = FullStudentID; under my set statement so it should work. Hoewever, I get error C2065: 'firstName': undeclared identifier. Tried all solutions I found but none wo... | StudentPrint is not a member function of Student and can thus not access those variables. Either make it a member function of Student, or better yet, use the 'get' functions you've defined (after you've actually implemented them).
void StudentPrint(const Student& student) {
cout << "student ID: " << student.GetStud... |
61,826,282 | 61,826,316 | Initializing objects of my class with a string | I'm writing a polynomial class:
#pragma once
#include<iostream>
using namespace std;
class polynomial
{
private:
int coeff[300];
int expo[300];
int counter;
public:
polynomial();
polynomial(const polynomial&);
polynomial operator-()const;
polynomial& operator=(const polynomial);
polyno... | What you need is a converting constructor that takes a single argument of a std::string type.
The constructor definition would look something like:
polynomial(std::string const &s) {
// use s to construct
}
However, you still can't construct a polynomial object the way you want:
polynomial p1 = "+5x^2-3";
because... |
61,826,311 | 67,308,409 | In BAZEL, Is there a way to prevent dependency C/C++ headers from being propagated to dependent library? | For example:
lib_a is an internal library. It exposes interface header alpha.h.
lib_b is an API library. It includes alpha.h in beta.c and exposes interface header beta.h which does not include alpha.h.
exe_c is a test app that utilizes lib_b. Since it is "external" to API library lib_b, it should not have access to ... | Update 5/24/22: Bazel added an implementation_deps feature.
This is possible with a custom rule and macro.
Here's how you can write a macro my_cc_library so that you can do something like this
my_cc_library(
name = "b",
hdrs = [
"b.h",
],
srcs = [
"b.cc",
]
impl_deps = [
... |
61,826,482 | 61,827,187 | L-System tree won't branch correctly | I have tried to implement the L-System in c++ with SFML, but for some reason it doesn't work as expected.
I tried replicating this program:
https://www.youtube.com/watch?v=E1B4UoSQMFw?t=1256
And everything works fine except the branching. At the timestamp(20:56) you can see the tree branching off into two branches, and... | You implemented an L system with the following alphabet:
Alphabet: F+-[]
And the following rule:
Rule 1: F → FF+[+F-F-F]-[-F+F+F]
The meanings of the alphabet characters are very turtle-graphic-like and are as follows:
F Move forward 1 unit and draw a line as you go.
+ Turn Clockwise
- Turn Counter-Clockwise
[ P... |
61,826,715 | 61,826,904 | Reuse code in C++ functions that access different attributes of struct | I have a struct
struct doodle
{
int x;
int y;
};
and 2 methods that are identical, except they make use of different attributes of struct doodle:
void ProcessDoodlesHorizontally(std::vector<struct doodle>& v_doodles)
{
for (unsigned int i=0; i<v_doodles.size(); i++)
{
int x = v_doodles.at(i).x;
... | Since the only difference between the functions is which data member is used, you can pass in a pointer to the data member (this works here since both data members are of the same type):
void Process(std::vector<struct doodle>& v_doodles, int doodle::* field)
{
for (auto &doodle : v_doodles)
std::cout<< doodle.... |
61,826,728 | 61,827,257 | Unable to update the value of field inside class | This function removes the expired messages from the messages container
void Broker::removeExpiredMessages(){
while(true){
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
messageMut.lock();
std::cout<<Broker::getMessages().size()<<std::endl;
for(auto& i : Broker::getMess... | You need this to return a reference
Header &getHeader() const{
return this->header;
}
It is returning by value and not by reference right now. That is why the expire time is not decrementing!
|
61,826,948 | 61,827,262 | C++ thread safe class, not working as expected | I am trying to implement a thread-safe class. I put lock_guard for setter and getter for each member variable.
#include <iostream>
#include <omp.h>
#include <mutex>
#include <vector>
#include <map>
#include <string>
class B {
std::mutex m_mutex;
std::vector<int> m_vec;
std::map<int,std::string> m_map;
public:
... | The output you see is fine, only your expectations are off.
You add elements into the vector via:
void insertInVec(int x) {
std::lock_guard<std::mutex> lock(m_mutex);
m_vec.push_back(x);
}
and then retrive them via:
int getValAtIdx(int i) {
std::lock_guard<std::mutex> lock(m_mutex);
return m_vec[i];
}
Becau... |
61,826,994 | 61,827,372 | Minesweeper Program, unexpected output | I was doing one problem(Minesweeper) from Steven Skiena(Programming Challenges). Where you have to output the number of mines adjacent to that square.
#include<iostream>
using namespace std;
int main()
{
int n,m;
cin>>m>>n;
char a[m][n];
for(int i=0;i<m;i++)
{
for (int j = 0; j < n; j++)
{
cin>>a[i][j]... | I see a few separate issues here that, collectively, are leading to the issue you're running into.
First, as pointed out above, once you've counted the number of mines adjacent to each mine, you're currently storing the result in a way that won't print the way you expect it to. The other answers here have suggested sev... |
61,827,035 | 61,828,627 | Interpreting lower part of an uint64_t as float | I have a data stream that I get from a device. The chunks are 8 bytes, which I read as uint_64t words. A few of the higher bits are flags (not all 4 bytes) that define the type of data. Some, but not all, of the chunks have the lower 4 bytes representing a float in binary representation.
How do I correctly extract that... | Type punning may "work" in your compiler, but it is really frowned upon by the C++ standard. memcpy() (or equivalent) is really the only option the standard supports, eg:
// note that casting a pointer-to-type to a pointer-to-char for
// purposes of accessing the type's raw bytes IS allowed by the
// C++ standard...
u... |
61,827,156 | 61,827,391 | OpenGL 4.5 Direct State Access Render a Triangle - GL_INVALID_VALUE | The Description
I'm currently learning OpenGL and want to try out the the direct state access extension from OpenGL 4.5. Thus I setup a simple triangle render example (in 3D) which should render my triangle. The code below is executed each frame and draws a triangle in 3D space.
void Geometry::draw(glm::vec3 pos, g... | The 3d parameter of glVertexArrayAttribBinding is not the vertex buffer object, it is a binding index. It is an arbitrary id which you have to choose.
The following instruction associates a binding index to an attribute index (0) of the specified VAO.
glVertexArrayAttribBinding(m_VaoID, 0, m_VboID);
glVertexArrayAttr... |
61,827,326 | 61,827,374 | C++ Constructor expecting a ":" (colon) | I'm loosing my nerves over the following code, but before we start you need to know I'm kinda' new to C++
#include <CPUID.h>
namespace CPU {
class CPUGeneric {
protected:
CPUID* _cpuid;
public
CPUGeneric(CPUID* cpuid) : _cpuid(cpuid) {};
};
class CPUIntel : CPUGeneric {
public:
CP... | Welcome to SO!
If the linked code is carbon-copy of your code, then your problem might be the missing colon after "public" at line #8
|
61,827,714 | 61,827,790 | C++ warning: pragma once in main file | I'm have an issue with compiling my program with g++ 8.3. I have approx 10 classes in a program. These classes are placed in header files and their full definitions are in .cpp files. I'm including these classes the same way as in this code:
main.cpp:
#include "CPerson.h"
int main()
{
CPerson person1(10 , "Peter")... | You get the warning because you are compiling a file that contains #pragma once. #pragma once is only intended to be used in headers, and there is no need to compile headers; hence the warning. Solution: Don't compile headers.
|
61,828,086 | 61,828,178 | Why do fwrite / fread not like 56.806201550387598? | I am trying to save a struct to a file and then read it again in another program.
I never had problems with this before, but at least to my knowledge, I never tried writing a double variable with the value 56.806201550387598 to a file. Not that I have any idea why this number should make any problems whatsoever but whe... | Use Write Binary mode. Text mode will be very random for binary data.
FILE* of = fopen ("imgStats2.dat", "wb");
and
FILE *ifl = fopen ("imgStats2.dat" , "rb");
|
61,828,135 | 61,828,172 | Iterate though array of int by prime numbers at C++ | I leave the complete code so that you can understand the context.
My problem is on line 53 (it says "HERE HERE...")...
The purpose of the code is to decompose a number(n) dividing it by prime numbers and printing at all in a chart.
Basically the problem is how to iterate through an int array by prime numbers.
I hope fi... | #include <array>
#include <iostream>
const int SIZE = 10;
int main()
{
int m = 8;
std::array<int, SIZE> arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (auto i : arr) { // How to iterate all elements of std::array
std::cout << i << ' ';
}
std::cout << '\n';
// Another way to do the same th... |
61,828,152 | 61,829,138 | CMake target_include_directories does not affect header files | My project is roughly structured like this:
├CMakeLists.txt
|
├───ExampleApp
| ├───CMakeLists.txt
| ├───header.hpp
| └───main.cpp
|
└───ExampleLibrary
├───CMakeLists.txt
├───mylib.hpp
└───mylib.cpp
In the root CMakeLists.txt I call
add_subdirectory(ExampleLibrary)
add_subdirectory(ExampleApp)
To bui... | It seems like you may not have added the correct directory as an include directory for the ExampleApp. The PROJECT_SOURCE_DIR variable evaluates to the directory in which the last project() call was made in your CMake project. You have not shown where this is, but you could use the root directory of the CMake project t... |
61,828,316 | 61,828,447 | Remove code duplication with an ostream variable | I have
void fnc(std::ofstream& file){
std::cout << x;
file << x;
}
with x something complicated and I would like to remove the code duplication.
I tried something like
void fnc(std::ofstream& file){
std::ostream os;
os << x;
std::cout << os;
file << os;
}
but it doesn't work. What's the best w... | Thanks to drescherjm the solution is the following :
void fnc(std::ofstream& file){
std::ostringstream os;
os << x;
std::cout << os.str();
file << os.str();
}
|
61,828,574 | 61,830,921 | How to parse this JSON wit Qt an C++? | I have a json like this:
{
"name1": {
"path": "D:/myfolder"
},
"name2": {
"path": "D:/anotherFolder"
},
"name3": {
"path": "D:/myfolder"
}
}
And I want to get: are the names and the folder names.
like :
name1, D:/myfolder
name2, D:/anotherFolder
name3, D:/myfolder
It is not importa... | Most optimal way to do it just using single for iteration
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject json = doc.object();
for (auto it = json.constBegin(); it != json.constEnd(); ++it)
{
qInfo() << it.key() << it.value().toObject().value("path").toString();
}
|
61,828,657 | 61,828,942 | Why is a function with default-assigned argument(s) not accepted as 0-arg Generator? | The following code attempts to use ns::generateInt() as the Generator argument to std::generate_n():
// main.cpp
#include <vector>
#include <algorithm>
#include <ctime>
static int _tmp = ( srand( time( NULL ) ), 0 );
namespace ns
{
int generateInt( int offset = 0 )
{
return offset + rand() % 128;
}
}
in... | Just because generateInt() has a default argument value does not change the fact that it has an argument, which you can see in the error message:
_Generator = int (*)(int)
The default argument value is not part of the function's type.
When you call generateInt() directly, the compiler knows the full declaration of gene... |
61,828,892 | 61,841,484 | Variadic Function template not playing nice with std::function as argument | I'm trying to create a thread-safe std::map wrapper.
To avoid data-loss scenarios at the risk of misuse causing a resynchronization of the threads, I'm trying to implement a function into that wrapper that can operate directly on the internal std::map instance without breaking the std::lock_guard's scope.
I had this wo... | Let's reduce your example to the following:
#include <functional>
template <class T>
void bad_foo(std::function<void(T)>, T)
{}
int main() {
bad_foo([](int){}, 1);
}
When the compiler specializes bad_foo function template, it attempts to deduce the types of the template parameters, based on the arguments you pass... |
61,828,926 | 61,829,107 | Issue by implementing a python like "map" function in C++ : call a class member function | I have a function member :
double XC::nz(double z){
return pow(z/zrange_0,2)*exp(-pow(z/zrange_0,1.5));
}
I would like to get the equivalent but with vector form, so I did :
vector<double> XC::nz_vec(vector<double> input){
vector<double> output;
output.resize(input.size());
transform(input.begin(), in... | The problem is that nz is a member function and therefore needs to be called on its associated object. The easiest way to do this is with a capturing lambda:
std::transform(input.begin(), input.end(), output.begin(), [this] (double d) { return nz (d); });
Also, I suggest you pass input by const reference, rather than... |
61,828,965 | 61,829,242 | Lambda <-> closure equivalence in C++ | I was watching a video called Lambda? You Keep Using that Letter by Kevlin Henney, where he states that closures and objects are fundamentaly equivalent:
He then proves his point by this javascript code which implement a stack as a closure:
const newStack = () => {
const items = []
return {
depth: () =>... | Yes, of course there's a better way to do it in C++: don't use a lambda.
A lambda expression defines a class. A closure is an instance of that class--an object. We don't need comparisons to other languages to tell us that--it's exactly how lambdas and closures are defined in C++. §[expr.prim.lambda.closure]:
The type ... |
61,829,515 | 61,829,653 | Problem while initializing attribute in constructor c++ | While i try to debug
ERROR appear :
"Unhandled exception at 0x5784F2F6 (ucrtbased.dll) in Final project.exe: An invalid parameter was passed to a function that considers invalid parameters fatal."
Tried every thing can't figure out how to solve this.
using namespace std;
class Map :
{
private:
double *mhours_playe... | These statements
maps[2] = { "Summoner's rift", "Aram" };
mhours_played[2] = {};
do not make sense. maps and mhours_played are pointers that within the body of the constructor have indeterminate values. They are not arrays as you think. For example the expression maps[2] is a scalar object of the type std::string.
De... |
61,829,633 | 61,829,729 | program crash in filling array | I am getting a program crash specifically due to this part of my code where I fill an array. Even if I do it with a vector, I'm getting a crash.
long long a[200000000]{0,1};
for(long long i{2};i<200000000;i++){
a[i]=a[i-1]+i;
}
OR
vector<int> a;
a.push_back(0);
a.push_back(1);
for(long long i{2};i<200000000;i++){
... | The second one uses a vector that allocates the memory you specify on a heap. If enough memory is available,then it should work fine.
It is not entirely clear whether the first code snippet is inside a function, but if it is, then you are most likely overflowing the stack.
|
61,830,196 | 70,493,489 | deduced return type with function template | Consider the following program:
#include<functional>
template<typename T>
T f() { return T{}; }
template<typename T>
auto g() { return T{}; }
int main() {
std::function<int()> a = f<int>; // ok, clang and gcc
std::function<int()> b = g<int>; // ok, clang, error gcc
}
The error in gcc is
error: conversion... | Indeed, f() and g() are similar functions, having the same result type.
It was just a bug in GCC, which is fixed in GCC 10.3. Clang and MSVC also accept the program, demo: https://gcc.godbolt.org/z/qPvar6vTh
So the program is well formed.
|
61,830,994 | 61,831,216 | How to implement a function with char array on Arduino | I am doing a sketch using an ESP8266 as a WiFi server, I need to send a character string to the Client, for this I am using this piece of code:
char sbuf[] = "Hello world!\n\r";
size_t len = strlen(sbuf);
for (i = 0; i < MAXCLIENTS; i++) {
if (serverClients[i] && serverClients[i].connected()) {
serverClien... | sizeof doesn’t do what you think it does here. You’re getting 4 because that’s the size of a pointer. Use strlen instead. It will tell you how long up to the \n. Add two if you want the \r too.
void sendDataToClient( char *sbuf[]) {
This line is also not doing what you think. It is passing an array of pointers.... |
61,831,114 | 61,831,208 | C++ | How to get input from the arrow keys with Linux | I'm super new to C++ and was wanting to add arrow key functionality to my snake game. I've been scouring the Internet trying to find a way to do this without "conio.h" as I am using Linux. How would I go about doing this and can I get some example code?
Thank you!
| You'd be best off using ncurses - just google for some tutorials to get yourself started. It can do simple things like clear the screen, get the terminal dimensions, position the cursor at arbitrary coordinates, write text in arbitrary colours, and yes - read characters from the keyboard without waiting for enter to b... |
61,831,409 | 61,831,581 | int64_t to std::vector<bool> using only `std` | Suppose that x is an int64_t. How can I efficiently convert it to a std::vector<bool> with 64 elements, one for each bit of x, without using other libraries than std?
Edit: std::bitset<64> is not an option to me, for instance because I need to call push_back and std::find on it.
| The makeVec function below will allow you to turn a 64-bit value into a boolean vector:
#include <iostream>
#include <vector>
#include <cstdint>
std::vector<bool> makeVec(int64_t x) {
std::vector<bool> retVal;
uint64_t mask = 1ULL << 63;
for (int i = 0; i < 64; ++i) {
retVal.push_back((static_cast<... |
61,831,475 | 61,831,597 | Covert gcc arguments to CMake file | So I am trying to learn CMake and I want to convert the following
gcc "-DARCH=\"`uname -a`\"" cli_arch.c arch.c
to a CMakeLists.txt file.
This is what I got so far:
Running cmake -DCMAKE_C_COMPILER=/usr/bin/gcc "-DARCH=\"`uname -a`\"" ..
// CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(cli_arch)
a... | The trick is execute_process.
execute_process(COMMAND uname -s
OUTPUT_VARIABLE uname_output
OUTPUT_STRIP_TRAILING_WHITESPACE
)
add_executable(cli_arch cli_arch.c arch.c)
target_compile_definitions(cli_arch
PRIVATE "-DARCH=\"${uname_output}\""
)
I had to use uname -s since at least on my system, uname -a h... |
61,832,014 | 61,832,196 | sizeof operator returns 1bytes for VOID operator | I was looking over the sizeof operator in C++. I came across an unexpected semantic error. I had read that void data types has no memory size. But, here in case of my program, sizeof operator returns 1 for a void data type. How is this possible?
#include<iostream>
int main()
{
std::cout<<"Void: "<<sizeof(void)<<" ... | This is a GCC extension:
In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.
A consequence of this is that sizeof is also allowed on void and on function types, and returns 1.
The option -Wpoint... |
61,832,173 | 61,887,404 | Why is a Core i5-6600 faster at non-square matrix multiplication than a Core i9-9960X? | The following minimal benchmark rebuilds single-threaded code with -O3 -march=native on each machine, multiplying matrices that are either square or highly non-square (one dimension = 2).
#include <Eigen/Core>
#include <chrono>
#include <iomanip>
#include <iostream>
std::string show_shape(const Eigen::MatrixXf& m)
{
... | As suggested by Peter Cordes in his comment, it seems to boil down to memory throughput.
Results of mbw 1000 show it:
i5-6600:
AVG Method: MEMCPY Elapsed: 0.13856 MiB: 1000.00000 Copy: 7217.059 MiB/s
AVG Method: DUMB Elapsed: 0.09008 MiB: 1000.00000 Copy: 11101.625 MiB/
i9-9960X:
AVG Method: MEMCPY Elapsed:... |
61,832,272 | 61,833,025 | Fix a large class using inheritance | It seems to me that my class is too big and complicated, I would like to reduce it. Can I use inheritance in this way, given that I created the InitCar class only to inherit it and am not going to use objects of this class explicitly.
Before refactoring. People and License are not my own classes, I cannot change them.
... | Although it is true that you can use inheritance to reduce the size of you classes and reduce code duplication for other classes (which can also inherit InitCar for similar base functionality), it is actually not a good idea.
Functionality-wise, it does work, it does reduce code duplication and class sizes. However, it... |
61,832,346 | 61,832,439 | Data member alters itself automatically when a member function is called | I"m trying to build a rudimentary Binary Tree for learning purposes. I use three classes:
template<typename Elem>
class Node
template<Typename Elem>
class BinaryTreet;
and a nested iterator class
template<typename Elem>
BinaryTreet<Elem>::iterator;
The Node and BinaryTreet classes are implemented like this:
templat... | The problem is that you are storing pointers to objects which have been destroyed. Your insert function essentially does this
template<typename Elem>
void BinaryTreet<Elem>::insert(Node<Elem> z){
...
some_pointer = &z;
}
But z no longer exists when the insert function exits, so you are left with a pointer to a... |
61,832,699 | 61,832,960 | Sort Array of 0 ,1 and 2 | What is wrong in my code why it is not giving correct output??
input
84
1 0 1 2 1 1 0 0 1 2 1 2 1 2 1 0 0 1 1 2 2 0 0 2 2 2 1 1 1 2 0 0 0 2 0 1 1 1 1 0 0 0 2 2 1 2 2 2 0 2 1 1 2 2 0 2 2 1 1 0 0 2 0 2 2 1 0 1 2 0 0 0 0 2 0 2 2 0 2 1 0 0 2 2
Its Correct output is:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0... | The main problem is in your input reading:
for(int i=0;i<n;i++) {
cin>>arr[n];
}
You are reading into arr[n] which is undefined. You want to use i as index:
for(int i=0;i<n;i++) {
cin>>arr[i];
}
Since the array is going to contain only 0, 1, or 2, you can simplify the sorting algorithm, too:
void sort... |
61,832,941 | 61,833,057 | Reverse a linked list using only 2 pointers using XOR operation | I found this code online for reversing a linked list using only 2 pointers using xor operation :
void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
// at last prev points to new head
while (current != NULL) {
current = (struct Node*)((ut)pre... | Have you read this: Iteratively Reverse a linked list using only 2 pointers?
while (current != NULL) {
// This expression evaluates from left to right
// current->next = prev, changes the link fron
// next to prev node
// prev = current, moves prev to current node for
// ... |
61,833,239 | 61,896,231 | cuda 10.2 in Qt 5.14 ubuntu 18.04 | I am planning to start cuda programming in Qt framework. I would like to start with a simple example.
system information :
OS : ubuintu 18.04 LTS
Qt version : 5.14
Compiler : GCC
CUDA version : 10.2
GPU : NVIDIA GTX 1060 with compute capability 6.1
I searched a lot and came across this useful topic:
https://cudaspace.w... | I solved this problem with the @Gred's solution in this link :
https://forum.qt.io/topic/114853/cuda-10-2-in-qt-5-14-ubuntu-18-04/12
This line in the .pro file:
SOURCES += main.cpp \
cuda_code.cu
should get changed to :
SOURCES += main.cpp
And then remove #include "cuda_code.cu" from the main.cpp.
And Now every... |
61,833,363 | 61,833,432 | Can't print char* in WCHAR* with swprintf | I have that function that work (I just have to turn wstring to WHAR* at the end):
wstring stringtowstring(string str)
{
WCHAR ch[256];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, (LPWSTR)ch, 256);
return wstring(ch);
}
But I would like to know why that doesn't:
WCHAR tmp[256];
swprintf(tmp, L"%s", "te... | Assuming Visual Studio in the context, this is a documented non-standard behavior of swprintf.
Character and string arguments that are specified by using c and s are interpreted as char and char* by printf family functions, or as wchar_t and wchar_t* by wprintf family functions. Character and string arguments that are... |
61,833,578 | 61,833,629 | max_element() is giving very weird error messages | While learning c++, I'm attempting to make a rock-paper-scissors bot that (in a very stupid way) might discover any patterns in the opposing player.
#include <iostream>
#include <array>
using namespace std;
int check_winner(int a, int b) {
if (a == b) {
return 2;
}
else if (b - a == 1) {
re... | You need to do:
bot_choice = std::distance(rocks.begin(), std::max_element(rocks.begin(),rocks.end()));
See example section of:
https://en.cppreference.com/w/cpp/algorithm/max_element
|
61,833,681 | 61,848,994 | Get a label address out of the function scope in gcc/clang (C++) |
I'm making some kind of interpreter and I'm computing a static const jump table thanks to local label addresses.
You know the drill,
static const int JUMP_TABLE[] = { &&case0 - &&case0, &&case1 - &&case0 and so on.
For various reasons, mostly performance, I'd like to copy/compress this table in an object during init.
... | I'm not aware of ways to achieve this within pure GNU C so approaches below use other mechanisms.
Double compilation
You can compile your object file twice, collecting offsets on the first run and using them on the second. For example
int foo(int x) {
#ifdef GENERATE_ADDRESSES
static __attribute__((section(".foo_of... |
61,833,729 | 61,833,860 | How can i optimize this Codewars c++ code? | i was doing a Codewars training in c++ and my code is working good but it says that it is not fast enough to pass all the tests. In this training, i need to check if a portion of str1 characters can be rearranged to match str2 (all passed as parameters and being const). Pretty simple subject but how can i optimize it ?... | Your current metode is to actually do a rearrangement, with a lot of memory movement. But actually you could just count the amount of each letter in S2, then run through S1 until you have accumulated the same number of letters.
Achtung totally untested code.
// assuming all is lowercase
int matches = S2.length();
std::... |
61,834,059 | 61,834,161 | How to convert tbb concurrent_hash_map to regular std::map? | I am working on some concurrent program and don't know how to convert tbb::concurrent_hash_map to regular std::map or get values, stored in the concurrent map in another way.
Can anyone help?
| I would do it the naive way, iterating the hashmap and adding the items to the std::map in the loop.
|
61,834,698 | 61,835,022 | Translate C++ code into R code for data generating purposes | I wish to create some data according to the following code for my master thesis but i am only familiar with R , some guidance on what the following code does or an implementation of it in R would be appreciated.
case 9: // generates a 20-dim affine space in 100- dimensions
dim=20;
// allocate memory fo... | Here is one translation that maybe you can try
vectors <- matrix(nrow = 20,ncol = dim)
for (i in 1:20) {
for (j in 1:dim) {
vectors[i,j] <- ifelse(i==j,1,0)
}
}
for (i in 1:20) {
for (j in 1:dim) {
data[i*(dim-1+j)] <- 0
for (k in 1:20) {
data[i*(dim-1)+j] <- data[i*(dim... |
61,834,856 | 61,834,944 | What is wrong in this code related to pointer | /* The structure of the Linked list Node is as follows:
struct Node
{
int val;
struct Node *next;
Node(int data){
val = data;
next = NULL;
}
};
*/
void intersection(Node **head1, Node **head2,Node **head3)
{
cout<<*head1->val;
}
The above code in not working but when I take an... | In this code snippet
void intersection(Node **head1, Node **head2,Node **head3)
{
cout<<*head1->val;
}
the expression
*head1->val
is equivalent to
*( head1->val )
(because the postfix operator -> has higher priority than the unary operator *) but the pointer head does not point to an object of the structure ty... |
61,834,924 | 61,835,477 | Heap corruption detected (String makes heap corruption) | C++ | I dont know why this function has made the heap corruption, I'm sure that the function copyFile isn't related to the error. Please check and help me TT
void copyFileToFolder(char* fileName, char* folderName)
{
char backSlash = '\\';
char *nameOfFileWithBackSlashInHead = strrchr(fileName, backSlash);
cha... | The strcat will append to folderName which is problematic. folderName is comming from outside and it might result in memory corruption if you write beyond its allocated storage. See strcat appends to its first input argument and also returns it.
Change your function signature to
void copyFileToFolder(const char* fileNa... |
61,835,024 | 61,865,763 | error LNK2005 not getting to solution to solve the problem | i am new to C++ need some help on this
mainclinet.CPP
#include "client.h"
#include "config.h*"
int main(){
g_pClientSampleConfig = new ClientSampleConfig;
g_pUaSession = NULL;
g_pCallback = NULL;
g_nsIndex = OpcUa_UInt16_Max;
g_nsIndex2 = OpcUa_UInt16_Max;
client();
}
function client(... | I suggest you could refer to the Doc:Linker Tools Error LNK2005
If mainclinet.CPP and clinet_start.cpp include clinet.h , then both are compiled with your definition of client(), so both object files will contain code for client(). When the linker gathers all the functions, he sees that client() is defined in two objec... |
61,835,042 | 61,862,892 | Does sniffing in loopback capture outside traffic? | i have a game server running on some port.
I learned to sniff packets on loopback. So if i connect to it from same computer, the packets are captured.
But somebody can connect from other computer and the packet will not be sniffed.
The packets from some computer must pass through one of my interfaces. So should i s... |
So should i sniff on that interface too inorder to get packets coming from both my computer and other computers?
Yes, you use do that - or, if you're running on Linux, you can capture on the "any" device, which should capture traffic on all interfaces.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.