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 |
|---|---|---|---|---|
65,741,227 | 66,139,485 | Why does Boost.Hana use macros for opening/closing namespaces? | One of the many examples of two macros being used to open and close a namespace respectively is in /usr/include/boost/hana/transform.hpp:
BOOST_HANA_NAMESPACE_BEGIN
// stuff
BOOST_HANA_NAMESPACE_END
Those macros are defined like this in /usr/include/boost/hana/config.hpp:
#define BOOST_HANA_NAMESPACE_BEGIN namespace b... | This was originally for forward compatibility with using inline namespaces, however this never became relevant. I re-opened https://github.com/boostorg/hana/issues/288 and will change it to normal namespace declarations.
|
65,741,530 | 65,741,695 | How do I swap the last and maximum element in the array? | How to swap the maximum and last element of an array?
I want to write the program which requests natural number NN (no more than 100), further sequence from NN of various numbers, changes places of the last element and the maximum, leaving other elements without change, and deduces the received array.
Sample Input 1:
8... | #include <algorithm> // max_element, iter_swap
// ...
auto me = std::max_element(arr, arr + n); // get an iterator to the largest element
std::iter_swap(me, arr + n - 1); // swap the value at "me" with the last element
|
65,741,887 | 65,749,448 | OpenGL Spaceship thruster is not circular at base | I am developing a space shooter game using OpenGL. Trying to create a thruster effect for the player's spaceship using particles. I am facing a problem where the base of the thruster is not circular under some angles of the spaceship. You can see the effect in the video.
This is the code for calculating the circular ba... | The solution was the following for anyone having the same problem:
glm::vec3 up = (mUp * random);
glm::vec3 right = (mRight * random);
particle.Position = mPos + glm::cos(angle) * up + sin(angle) * right;
mUp is the Up vector, mRight is the right vector of the spaceship, angle is the angle for the specific point (0-36... |
65,742,287 | 65,742,539 | How can I include Vulkan-hpp with glfw? | I'm developping a game engine using vulkan and glfw. As indicated here, with glfw there's a bunch of macros to include OpenGL/OpenGL ES/Vulkan. Since it is now included in the vulkan sdk, how can I setup glfw to include vulkan-hpp. Do I just need to put GLFW_INCLUDE_NONE and add #include <vulkan/vulkan.hpp> or do I ne... | If we take a look at GLFW.h, it just includes vulkan.h only if the GLFW_INCLUDE_VULKAN macro is defined. So if you want to include the vulkan.hpp file, just undefine the GLFW_INCLUDE_VULKAN macro and include the file explicitly.
Why?
GLFW is a C library. vulkan.hpp file contains C++ stuff inside so there could be comp... |
65,742,402 | 65,742,614 | Multiplying 1 million | Why when you do this:
int a = 1000000 , b = 1000000;
long long product = a * b;
cout<<product;
It gives some random trash value?Why do both a and b need to be long long in order to calculate it?
| You are observing the effects of undefined behavior. This:
a * b
is an (arithmetic) expression of type int, as both operands a and b are of type int. Trying to store the value of 1000000000000 into an int results in the so-called signed integer overflow which is undefined behavior.
Either cast one of the operands t... |
65,742,505 | 65,742,781 | What principle of presence std::getline in std::string? | I'm trying to figure out, paritcularly, where does class std::string get method std::getline from? It's said that this method is non-member function of std::string and it's overloaded in std::string. But where is commencement of getline existence? What order of getting it into std::string class? Is this method inherite... |
where does class std::String
There is no class std::String. You may have intended to write std::string which does exist.
get method std::getline from?
std::string doesn't have such member function. There is a free function (template) by that name instead.
It's said that this method is non-member function of std::S... |
65,742,659 | 65,742,894 | LabVIEW not responding when I run this code. C++ code issue or LabVIEW issue? | For some background, I am compiling in Visual Studio 2019 and running the code inside LabVIEW 2017. The reason I am doing it in LabVIEW is for research to control a robotic gantry. This is the vision system and it is supposed to detect rectangles (wirebond pads for silicon detectors).
I need it to atleast show me a pic... | Well there is one error here
vector<vector<double>> dimRects;
...
for (int i = 0; i < contours.size(); i++)
{
...
dimRects[i].push_back(rectWidth);
dimRects[i].push_back(rectHeight);
dimRects has zero size but your code treats it as if it has the same size as contours.
|
65,742,866 | 65,754,073 | glewInit() Causes memory leak according to valgrind | I am trying to debug and fix all memory leaks in my program. I have went through the entire source code and there is not one call of new or malloc() which isn't supported by a free() or delete. I tried running the program in valgrind. Valgrind found that a consistent(throughout multiple executions of the program) 844 b... | I started using GLAD and it stopped causing the memory leak.
|
65,743,055 | 65,743,184 | How can I tell whether a pointer/address is dynamically allocated? | I'm trying to mitigate memory leaks.
Obviously the best solution is to not leak memory in the first place.
But in my case, I need to look at existing pointers, and determine if any of them are dynamically allocated and need to be deleted.
Given a specific address/pointer, does C++ provide a way to determine whether the... | In C++ (and C) a pointer points to any address. To know what type of memory you are pointing to, you need to look at the process memory map. This will be platform specific.
On Linux the /proc/<pid>/maps file contains this info.
However, even if the pointer points to the heap, it still might not be deletable if it is an... |
65,743,267 | 65,745,115 | Does OpenCV suppress OpenMP? | I got a question concerning OpenCV and OpenMP.
I used to parallelize my code using OpenMP, since I have to do some heavy computing on large images. Up to now (I did not use OpenCV so far) the parallelization worked fine for me.
Then I needed some functionality of the OpenCV library. Since I incorporated OCV in my code,... | This installation guide assumes that the OS is Ubuntu. I post it because it will probably help solving your problem.
Install OpenCV dependencies.
sudo apt-get install build-essential
sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
sudo apt-get install python-dev pyt... |
65,743,364 | 65,746,248 | Cmake (< 3.6) compiler flags in custom command | Suppose I have a set of compiler flags and I have two targets
set(COMPILE_FLAGS "-a -b -c")
add_executable(exe main.cpp)
set_target_properties(exe PROPERTIES COMPILE_FLAGS ${COMPILE_FLAGS})
add_custom_target(target1 DEPENDS exe)
add_custom_target(target2 DEPENDS exe2)
separate_arguments(COMPILE_FLAGS)
add_custom_com... | target_compile_options() goes back to at least CMake 3.0 and should probably be the preferred way to set these kind of flags. It takes a list.
CMakeLists.txt (Note: I used -D??? as the flags. Normally one should use target_compile_definitions() for defines.)
cmake_minimum_required(VERSION 3.6)
project ("example" CXX)... |
65,744,116 | 66,218,318 | How to reuse OpenSSL context to avoid reallocations of BIO and itself? | I would like to reset and use the SSL context of the previous disconnected client for the newly connected client and avoid reallocations.
OpenSSL is used in project just for cryptography and TLS protocol support, the networking is controlled manually. The client class has a pointer to crypto-backend, which looks like ... | You may not find an answer to that question, as even the manual cannot recommend an alternative to reallocating. You may instead need to consider a using pooled memory for allocations, though that is a separate question and answer. What follows is the relevant warning from the manual page:
SSL_clear() resets the SSL o... |
65,744,829 | 65,745,097 | My program doesn't execute because of an static value | I have this chunk of a program that merges two arrays in one. The matter is that I got this message once the program is compiled:
main.cpp:20:21: error: storage size of ‘cont’ isn’t known
Why does it happen?
Leave my code below:
int * merge(int *array_1, int *array_2, int n1, int n2)
{
static int cont[n1 + n2];
int i... | In C++ a static array needs to have a size which is known during compile time. If you do not know the size beforehand it is by default a dynamic array independently if it residing on the stack: int my_array[n] or on the heap: int* my_array = new int[n] (The latter is strictly speaking not an array but behaves similar)
... |
65,744,843 | 65,816,079 | It seems FlushFileBuffers() doesn't set end-of-file (and therefore can lead to corrupted files) | Consider following sequence of calls captured with process monitor:
Here is what happens here:
file is opened
15-bytes file write
FlushFileBuffers() call is made
... which leads to 4kb file write issued by OS
file handle is closed via Close()
... which results in SetEndOfFileInformation() call which sets end-of-file ... | No. According to further investigation second write (step #4) doesn't change file size.
|
65,744,845 | 65,746,751 | Decoding AAC audio with ffmpeg | I'm trying to decode an AAC audio stream in an ADTS container, which is streamed from an external hardware H264 encoder.
I've parsed out the ADTS and it tells me I've got a 2 channel, 44100 AAC Main profile frame. I setup the extra data bytes for the ffmpeg decoder and decode the frame successfully? as follows:
(pseudo... | This was nothing more than a difficult bug to find. Zooming in on the audio sample in Audacity revealed the repeating pattern of 1024 samples wide.
A buffer was in fact not being updated properly and I was processing the same audio frame over and over:
for(var offset = 0; offset < packet.Length; offset++) {
var frame... |
65,744,903 | 65,744,929 | How to refer to a nested type of a templated base class | I have the following structure of base and derived class:
template<class T>
class Base {
public:
Base();
protected:
struct Foo{
int a;
int b;
};
int c;
};
template<class T>
class Derived : Base<T> {
public:
Derived();
...
};
I now want to access the protected part of the base class within the de... | For dependent types you need to use typename keyword to indicate that the name refers to a type.
template <class T>
class Derived : Base<T> {
public:
Derived() : foo{1, 2} {}
typename Base<T>::Foo foo;
};
|
65,744,921 | 65,745,520 | Designing and implementing an interface in C++: I'm damned if I do and I'm damned if I don't | I need some help with inheritance and coding to interfaces in C++. I'm creating a state machine from which I'll derive another state machine. Therefore I have two interacting parts, a StateMachine and a State. The problem is that with this design, I cannot derive a specialised State from either the StateMachine or a De... | I don't fully understand your design, but you can do what you need like this:
class StateMachine; //fwd
class State {
public:
virtual void action(StateMachine *engine) = 0;
virtual ~State() = default;
};
class StateMachine {
public:
StateMachine() = default;
explicit StateMachine(State &state) : sta... |
65,744,963 | 65,745,026 | Templated member variables in C++ | Often when writing templated code, I find myself needing to store an instance of the template type in a member variable. For example, I might need to cache a value to be used later on. I would like to be able to write my code as:
struct Foo
{
template<typename T>
T member;
template<typename T>
void... | This is possible in the library by combining existing facilities.
The simplest implementation would be
std::unordered_map<std::type_index, std::any>
This is mildly inefficient since it stores each std::type_index object twice (once in the key and once inside each std::any), so a std::unordered_set<std::any> with custo... |
65,745,013 | 65,745,131 | C++ regex capture group confusion | I'm implementing the nand2tetris Assembler in C++ (I'm pretty new to C++), and I'm having a lot of trouble parsing a C-instruction using regex. Mainly I really don't understand the return value of regex_search and how to use it.
Setting aside the various permutations of a C instruction, the current example I'm having t... | gcc warns about unknows escape sequence \- Demo.
You have to escape \,
std::regex("([AMD]{1,3}=)?([01\\-AMD!|+&><]{1,3})?(;[A-Z]{3})?");
or use raw string
std::regex(R"(([AMD]{1,3}=)?([01\-AMD!|+&><]{1,3})?(;[A-Z]{3})?)");
Demo
|
65,745,048 | 65,745,162 | Is it possible to open a html page upon clicking a 'Help' button in my C++ program? | I am trying to develop a C++ program which also has a Help button on its menu bar. I'd like to know if it is possible upon clicking this button, if a html document can be opened on the browser, and if so could you explain how to please? I tried researching this but to no avail. I intend to use the html document in conj... | On Windows, you can do:
ShellExecute (NULL, __T ("open"), url, __T (""), __T ("."), SW_NORMAL);
where url is the page you want to open (e.g, __T ("https://stackoverflow.com/")).
This will open the page in the default browser (initially Edge, but users can change it).
|
65,745,503 | 65,745,580 | C++ dynamic array allocation and strange use of memset | I recently ran into this code in C++:
int m=5;
int n=4;
int *realfoo = new int[m+n+3];
int *foo;
foo = realfoo + n + 1;
memset(realfoo, -1, (m+n+2)*sizeof(int));
Only the variable "foo" is used in the rest of the code, "realfoo" is never used (just freed at the very end).
I can't understand what that means.
What kind ... | This:
foo = realfoo + n + 1;
Assigns foo to point to element n + 1 of realfoo. Using array indexing / pointer arithmetic equivalency, it's the same as:
foo = &realfoo[n + 1];
|
65,745,859 | 65,745,955 | how to use std::copy for int** | My2DClass::My2DClass(const int r, const int c, int mat[3][3]):m_r(r),m_c(c)
{
matrix = new int*[r];
for (int i = 0; i < r; i++)
matrix[i] = new int[c];
for (int i = 0; i < m_r; i++) {
for (int j = 0; j < m_c; j++) {
matrix[i][j] = mat[i][j];
}
}
//std::copy(&mat[0... | You are allocating an array of pointers to arrays, so a single call to std::copy() will not work. You would have to call std::copy() on every array individually. So really, only your inner-most loop can be replaced with std::copy(), eg:
My2DClass::My2DClass(const int r, const int c, int mat[3][3])
: m_r(r), m_c(c)... |
65,745,993 | 65,746,163 | How to construct template hierarchy for singly and doubly list nodes c++ | I just want to implement two types of nodes(only nodes):
A node for singly linked list and a node class for doubly linked list.
The obvious solution would be to define two separate classes:
template <typename T>
struct SinglyNode
{
using node_pointer = SinglyNode<T>*;
SinglyNode(T data = T{}, node_pointer next ... | With CRTP, you might do something like:
template <typename Derived, typename T>
struct SinglyNodeCRTP
{
using node_pointer = Derived*;
SinglyNodeCRTP(T data = T{}, node_pointer next = nullptr)
: m_data{ data },
m_next{ next }
{}
T m_data;
node_pointer m_next;
};
template <typename ... |
65,746,198 | 65,746,245 | some weird behavior of std::make_pair with deduction of string_view | std::string api_key_ = "123456789-5c51509f-8c5c5dc2-b6557";
std::pair<std::string_view, std::string_view> yy = std::make_pair("AccessKeyId", api_key_);
std::cout << "yy.second:" << yy.second << std::endl;
compile with c++17 this will output:
yy.second:9-5c51509f-8c5c5dc2-b6557
while this is good without deduction
std... | std::make_pair("AccessKeyId", api_key_); returns a temproray std::pair whose 2nd element is an std::string. Then yy is initialized from the temporary and its 2nd element std::string_view is constructed from the std::string of the temporary std::pair (but not api_key_). After the full expression the temporary std::pair ... |
65,746,442 | 65,748,392 | Clang not detecting stack variable assignment to reference as unused | I have Clang's -Wunused flag set but its failing to detect an assigned (but unused) stack variable.
Below I create an instance of a typedef'd array on the stack, but never use it:
class AClass
{
void func();
ATypedefdArray& marray; // Initialised within ctor, omitted to simplify example
};
AClass::func()
{
... | const ATypedefdArray arr = marray; will call copy constructor, and destructor will be called at end of scope.
if both are trivial, then clang/gcc succeed to detect unused variable Demo.
If any are non trivial, they might have side effects, and so are used. they might have expected side effect have some intentional RAII... |
65,746,547 | 65,746,653 | Can there be memory contention even if there are no locks? | I am writing a multithreaded code where a bunch of std::async calls spawn a fixed number of threads for the duration of the entire program. Each thread works off the same const BigData structure on a read-only basis. There are frequent, random reads from const BigData but the threads are otherwise totally independent. ... | Yes there can be a slowdown. Main memory (RAM) bandwidth is limited, and if you have multiple cores reading a lot of data quickly you may saturate the memory bus. The maximum memory bandwidth is typically tens of gigabytes per second (see the page for your specific processor, e.g. i9-9900K which shows 41.6 GB/s).
As ... |
65,746,742 | 65,747,349 | Getting runtime error in linked list implementation | I was trying to implement the insert function of singly linked list.
My implement function should insert the newnode at the head position rather than tail.
when i try to compile this c++ code i get runtime error.
here is my code :
#include <iostream>
using namespace std ;
struct node {
int data ;
struct node * next ;... | The error caused by below line;
struct node *head = NULL;
first in c++, you don't need struct to declare objects.
second you can declare head inside main local scope to avoid global pollution.
third, the main cause of your error, you must allocate memory to access any object.
so, change your main and insert function t... |
65,746,905 | 65,746,982 | C++: "Short Circuit" in the if statement not working and giving error | I'm just starting out with c++ and wrote a very basic program.
#include <iostream>
using namespace std;
int main()
{
int count = 0, limit = 10;
if ((count == 0) && (limit < 20))
cout << "expr1 ran well" << endl;
if (count == 0 && limit < 20)
cout << "expr2 ran well" << endl;
if ((limit... | The problem has nothing to do with short circuit. You used the following comparison x < y, but you never defined nor declared x and y.
if they are variable then define them beforehand like:
int x = 3;
int y = 4;
if they are constants then define them beforehand like:
const int x = 5;
const int y = 6;
or if they are s... |
65,747,118 | 65,747,290 | issue with float value printing in cpp | #include <iostream>
#include<bits/stdc++.h>
using namespace std;
int solve(int t){
float ans = static_cast<float>(320)/100;
cout<<fixed<<setprecision(2)<<ans;
}
int main(){
int t=320;
cout<<solve(t);
return 0;
}
output:3.204745728
how should I get output as 3.20
| You are using cout twice, when you only want to output one thing. You are also outputting the return value of solve when you don't return anything from solve, this explains the extra digits that you see.
Either do the cout in solve or do it in main, don't do it in both places.
First way
#include <iostream>
using namesp... |
65,747,311 | 65,747,335 | initializing member variable 2D vector in constructor | I have a member variable two-dimensional vector in a class, like this:
#include <vector>
...
class MyClass {
private:
int vector_size;
std::vector<std::vector<int> > vector_2d;
public:
MyClass(int _vector_size);
~MyClass();
} // class MyClass
I want to know the best way of implementing the constructor ... | std::vector have a constructor overload which takes a size for the vector.
You can use this to initialize your vector:
MyClass::MyClass(int size)
: vector_size(size),
vector_2d(size)
{
}
This will initialize vector_2d to have size elements. Each element is a default-constructed std::vector<int> object (the t... |
65,747,413 | 65,747,584 | read the file that is opened with my console application in C++ | I have written a console application in C++ and I need to read the file that is opened with my console app:
right click on txt file
select open with
choose my console application
then I want to read that .txt file. how?
my source code
| You just need to declare arguments to your main like this:
int main(int argc, char *argv[])
{
...
}
And the file path will be passed as one of the argument. If you open multiple files, it will run one process per file.
|
65,747,490 | 65,747,504 | Why can't a parent pointer be assigned to a child pointer? | I have a trivial inheritance case following:
class Person {
public:
const char* name;
public:
Person()
: name("Unknown person") {}
Person(const char* name)
: name(name) {}
};
class Student : public Person {
public:
Student()
: Person("Unknown Student") {}
};
If I assign a ... | Person *p = s;
works because every Student is also a Person.
Student *s = p;
doesn't work because a Person is not necessarily a Student.
|
65,747,569 | 65,747,815 | const char* cannot be used as a constant value for std::char_traits<char>::length | I have the following code:
constexpr uint32_t countWords(const char* str) {
constexpr std::size_t length = std::char_traits<char>::length(str);
std::uint32_t count = 0;
for (std::size_t i = 0; i < length; i++) {
if (str[i] == ' ') {
count++;
}
}
return count;
}
My proble... | From the comments it seems you are interested in using this on string literals.
All you need to do to make that work is to remove constexpr from length.
The function has to be callable at run-time as well as compile-time.
But when you call it with a string literal it can be calculated at compile time. You can verify th... |
65,747,683 | 65,747,806 | Does simultaneous read/write cause any other problems other than data race? | I was having the understanding that when two threads simultaneously read and write from/to the same variable, the application would crash. I wrote a small program to simulate this scenario. I ran it several times but do not notice any crash. What am I missing here?
#include <iostream>
#include <thread>
using namespace... | As mentioned by Jerry Coffin, you are getting undefined behaviour. However, not all UB means you will get a crash. A crash typically happens because of two things:
Reading from/writing to a memory location that is not mapped into the program's memory space
Executing invalid instructions
Since the threads are executin... |
65,747,768 | 65,748,600 | Failure on partial template specialization with gcc 9.3, was working before | I checked This stackoverflow post, but I still cannot understand.
I have this code (yes I know <functional> achieves the same thing) which worked (if memory serves me right, it was gcc6) and now fails with gcc9.3.0
Given these class definitions
template <typename D>
class Callback{
public:
virtual void operator()(D ... | This is a GCC bug filed here if I am not mistaken.
It is introduced in GCC 7.1.
|
65,748,000 | 65,771,468 | Initializing a C++ static member that stores a lambda function | I have defined a struct A with a member f that holds a lambda
function. The type is given as a template parameter, and f is
initialized in the constructor using an argument to the
constructor. The following code has worked well.
template <typename f_t>
struct A {
f_t f; /... | To save place, you might redesign to something like:
template <typename F>
struct A {
F f;
std::vector<int>* v;
A(F f, std::vector<int>* v) : f(f), v(v) {}
int g(int i, int x) { return f(f(x)) + v[i]; }
};
nt main() {
int p, q; std::cin >> p >> q;
auto f1 = [&](int x) -> int { return p * x + q; };
auto f... |
65,748,157 | 65,748,180 | How do I assign an object containing an unique_ptr to a vector of its type when a move assignment operator is defined? | The self-contained program section below leads to this error on Visual Studio 2019:
"function "partition_data::operator=(const partition_data &)" (implicitly declared)" is a deleted function.
Based on research around this type of problem I have defined a move assignment operator because of the unique_ptr but I still ge... | You have to move your object:
V[0] = std::move(A);
V[1] = std::move(B);
or even construct in place
std::vector<partition_data> V;
V.reserve(2);
V.emplace_back(5, 0.1);
V.emplace_back(5, 0.2);
|
65,748,309 | 65,748,385 | c++ iterate through list [and then manipulations of different iterators from the same class] | Let's assume we have a class named Student and data is the list.
std::list<Student>::iterator<Student> it;
for(it = data.begin(); it != data.end(); ++it){
std::cout<<(*it)->name;
it->print();
}
std::list<Student>::iterator<Student> it2;
for(it2 = data.begin(); it2 != data.end(); ++it2){
std::cout<<(*it... | If this compiles:
Student mult = (*it) * (*it2);
there is an operator* overload defined for Student - but it doesn't have anything to do with the iterators. The iterators are dereferenced (*) so you have two references to Students being multiplied.
The most likely place to find the answer:
Student operator*(const Stud... |
65,748,634 | 65,748,684 | On the weak semantics of references-to-const (and pointers-to-const) | This has probably been already asked.
Why is it allowed to assign a reference-to-const to a non-const variable?
Why is this allowed
int mut {0};
const int & r_to_c {mut};
mut = 1;
// now r_to_c changed to 1!
// But it was supposed to be a reference to something constant!
?
Sure, I cannot mutate the value from the refe... |
but isn't the const qualification enforcing too little? I would expect, from a promise of const-ness, that binding to mutable variables was disallowed.
No it is not "too little". You are expecting the wrong thing.
First, whether you bind a const reference does not make the object itself const. That would be strange:
... |
65,748,894 | 65,753,164 | Double rounding error, even when using DBL_DIG | I am trying to generate a random number between -10 and 10 with step 0.3 (though I want to have these be arbitrary values) and am having issues with double precision floating point accuracy. Float.h's DBL_DIG is meant to be the minimum accuracy at which no rounding error occurs [EDIT: This is false, see Eric Postpisch... |
generate a random number between -10 and 10 with step 0.3
I would like the program to work with arbitrary values for the bounds and step size.
Why is this happening ....
The source of trouble is assuming that typcial real numbers (such as string "0.3") can encode exactly as a double.
A double can encode about 264 dif... |
65,749,055 | 65,749,109 | When a 64bit int is cast to 64bit float in C/C++ and doesn't have an exact match, will it always land on a non-fractional number? | When int64_t is cast to double and doesn't have an exact match, to my knowledge I get a sort of best-effort-nearest-value equivalent in double. For example, 9223372036854775000 in int64_t appears to end up as 9223372036854774784.0 in double:
#include <stdio.h>
int main(int argc, const char **argv) {
printf("Corres... | In general case yes, both should be true. The floating point base needs to be - if not 2, then at least integer and given that, an integer converted to nearest floating point value can never produce non-zero fractions - either the precision suffices or the lowest-order integer digits in the base of the floating type wo... |
65,749,228 | 65,749,457 | Parameter unpacking next to operator | I am writing a little variadic summing function (using c++20, but my question would remain the same with c++17 syntax). I would like to make the following code as short and clear as possible (but without using folding expressions. This is only a toy problem, but in later applications I would like to avoid fold expressi... | Embrace the power of negative thinking and start induction with zero instead of one:
auto sum(auto &&val, auto &&...vals) {
if constexpr (sizeof...(vals) == 0)
return val;
else
return val + sum(std::forward<decltype(vals)>(vals)...);
}
The above definition has the side effect that sum(x) will... |
65,749,299 | 65,749,363 | Macro for push_back giving problems | I am starting to code in c++.
I was learning macros when this happenned:
#include <bits/stdc++.h>
using namespace std;
#define PB push_back
int main() {
vector<int> hello;
hello.PB(3);
hello.PB(2);
cout << hello < "\n";
}
My compiler shows, pointing to line 3:
Error: statement cannot resolve address of over... | For your code I get problems with the < instead of << and what I assume the main problem:
error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<int>’)
cout << hello << "\n";
It is telling you that there is no known way to output a whole vector to cout.
Th... |
65,749,455 | 65,751,382 | Why splice syscall fails when my program runs on Linux but succeeds when it runs in gdb? | I try to run a book's sample code. Its function is to accept a line of input and output it to the standard output and operation parameters specified file.
Here is the code:
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
int main( int argc, char* arg... | In linux manual splice(2), there is a description of ERRORS: EINVAL The target file is opened in append mode.
The stdout in my terminal is at append mode, that's why the third splice syscall fail.
And to solve this problem, we can add fcntl(STDOUT_FILENO, F_SETFL, fcntl(STDOUT_FILENO, F_GETFL) & ~O_APPEND);before the s... |
65,749,725 | 65,749,827 | How To Declare Static Const Array | I coded like this in class with public modifier:
static const string brands[] = {"Coca-Cola","Pepsi","Ruffles"};
And it gives me this error code:
E1591
How can I solve that ?
| As far as I know you can't have in-class initializer for your static const std::string [].
You should initialize it outside the class declaration.
For instance:
#include <string>
class Foo
{
public:
static const std::string brands[];
};
// in your Foo.cpp file
const std::string Foo::brands[] = {"Coca-Cola","Pepsi",... |
65,749,895 | 65,750,203 | Google Benchmark BaseClass Initialization happens before static variable assignment causes problem | I want to use google benchmark to run my codes, which contains a static global variable. In the benchmark's base class, I need to read this variable to perform some setup. But when the benchmark base class is initialized, that static variable is not initialized yet and cause problems.
The Minimal Reproducing Example be... | Your problem here is that global variables in C++ have an undefined initialization order between different translation units (i.e. .cc files).
I see a few options to resolve it:
Move the code from test.cc to the top of benchmark_main.cc, as globals are initialized in declaration order within a single file. This is tri... |
65,750,020 | 65,753,907 | Does random indexing an array have any performance implications over sequential indexing? | Lets say that we have a long array named DataList. And we have two other arrays which contains indexes, one contains the indexes in the ascending order (ie: 0, 1, 2, 3, 4, ...) named sIndexes, the other array is made of indexes which are randomly packed (ie: 6, 5, 1, 9, 7, ...) named rIndexes.
These index arrays (sInd... | Linear access is much faster, because:
The minimum size to fetch from RAM is one cache-line (usually 64 bytes). If you only use one byte from that, you are wasting precious memory bandwidth.
Modern CPUs can detect regular access patterns and will pre-fetch data from RAM, so it will be cached before you even access it.... |
65,750,626 | 65,750,627 | C++/libpng - fclose() "triggers a breakpoint" after a call to png_write_png() | I remade a function I found in a tutorial for testing purposes, where I just fill a 512 by 512 canvas with pixels of different colors and save that to a file. Then the title happens. Should I comment the call to png_write_png() out, no breakpoints are left in sight.
int save_test_png()
{
const string path = "D:\\te... | The "triggered a breakpoint" exception disappeared when I linked my Debug x64 configuration to .lib files built under a Debug x64 configuration and also placed a .dll file built under the same configuration in the project's x64/Debug folder, where the executable file is located.
|
65,750,678 | 65,750,963 | Where should I store project constants definition/declaration | I have a project, for example game application. I have a lot of classes in there. So, where should I store initial variable declaration/definition of game parameters?
For example, I have a 'plane' which has initial parameters speed,height, e.t.c.
After game has started this parameters somehow depends on game process, a... | You can declare the variables as extern in your header, and have a .cpp with the actual values.
Parameters.h
namespace WINDOW_PARAM {
extern const unsigned int WIDTH;
extern const unsigned int HEIGHT;
}
namespace PLANE_PARAM {
extern const char *TEXTURE_PATH;
}
Parameters.cpp
namespace WINDOW_PARAM {
c... |
65,750,889 | 65,752,758 | Why is my generated precompiled file so big when using a boost based library? | I'm working on a project using libraries handled through vcpkg.
As compile time wasn't that great, I did some headers clean up and configured the project to use precompiled headers, putting STL and vcpkg headers inside.
I started to run into the infamous C1076, C3859 and C1060 errors, and a quick check to the generated... |
Header only libraries work because there are no details left out of those headers.
Precompiled headers contain all the compiled information of the headers before start of the translation unit.
A large part (the majority) of boost libraries are header only. To add insult to injury, they're highly generic meaning ther... |
65,751,068 | 65,751,121 | Creating a random string results in just duplicate strings c++ | So i have tried using rand(), and random but it results in the same problem each time, all strings created are duplicate. I think the problem may come from the number generator but i have no idea.
#include<iostream>
#include<unistd.h>
#include<fstream>
#include<string>
#include<cstdlib>
#include<time.h>
#include<random... | for (int i = dis(gen) ; count != 13; count++){
The first time your code calls this function, this for loop will count this up until this count reaches 13. This is fairly simple, and basic.
But you will be surprised to learn that the second time your code calls this function, count is still what it was last time: 13. W... |
65,751,390 | 65,755,696 | Index sequence adding arrays together | I've been trying to make use of std::index_sequence, I've been trying to get this piece of code to work any help or pointers?
template <typename tty,
std::size_t ssz,
typename is = std::make_index_sequence<std::min(sz, ssz)>>
auto operator + (ss::array_helper<tty, ssz> right) const
{
auto re... | Very interesting question. Jarod42 showed already the solution using C++20. But, in C++17 we do not have templated lambdas.
In order for you to have a C++17 solution, I will present an implementation that uses a templated member function for the addition.
Since I do not know your definition for data type array_helper, ... |
65,751,685 | 65,752,005 | Reverse the number algorithm | cout<<"enter a number n"<<endl;
int n{0};
cin>>n;
int lastDig{0};
int revNum{0};
while(n>0)
{
lastDig= n%10;
n=n/10;
revNum = revNum*10+lastDig;
}
cout<< revNum <<endl;
This works just fine in reversing the number. But inside the while loop, if I write the third line as int revNum = revNum*10+lastDig; it... | If you change the third line in your loop to:
int revNum = revNum*10+lastDig;
Then you are declaring a new variable revNum each time through the loop. And your original revNum variable will not change (will stay zero).
You should not include the int and then the code within the loop uses your existing variable.
|
65,752,008 | 65,752,135 | std::fill segmentation fault error when the array is large | I have the following class which resembles a scalar field in two dimensions, but since periodic boundary conditions may be used, there are also ghost zones (simply view this as a 2D matrix).
#include <algorithm>
#include <iostream>
#include <fftw3.h>
class RectMesh
{
private:
int cols_x;
int rows_y;
int nghost;... | int len = (cols_x+2*nghost)*(rows_y + 2*nghost);
Plugging in 1e6 for cols_x and rows_y, and 2 for nghost, and then multiplying the end result by sizeof(double) which is 8, the grand total is:
8000064000128
bytes, or over seven terabytes of memory you're trying to allocate. One of two things are happening here:
fftw_... |
65,752,084 | 65,757,915 | Why assigning a function to a `std::function` cause undefined reference? | #include <functional>
int foo(size_t);
std::string bar(size_t);
int main() {
std::function<void(size_t)> f;
f = foo;
f = bar;
return 0;
}
In the snippet above, I am trying to assign to a std::function two functions foo and bar which are declared as such. I haven't called the functions yet, so why does this r... | To create a pointer to a function requires the address of the function. The compiler does not know the address of the function, so it inserts a symbolic reference that the linker will try to fix up later.
It's important to remember that linking happens after optimization. So if the optimizer removes all references to a... |
65,752,273 | 65,790,768 | C++ implementing vector field | I'm trying to recreate a Plasma Simulation from Lubos Brieda (Plasma Simulations by Example). In doing so, I need to implement a 3D field filled with physical vectors containing the data of the electric field. (I don't want to use the template, I'm referring to vectors in the mathematical/physical sense.)
The book sho... | I found a way to avoid the error, because it only comes up, when trying to initialize a vector field using operator=(0). But this command has to be used, if i want to initalize a scalar field with zeros. Thus using the same command for a vec3-type results in the error mentioned above, since the overridden operator= onl... |
65,752,467 | 65,755,543 | How to add random term in different steps of numerical integration | For the function below, I would not add the noise (Inoise in the code below) in every time step but, for example, only in every second time step. So while dt=0.0025 serves as the time step for the numerical integration, I would, for example, add Inoise only in every second time step (i.e. in 0.005 steps).
What is the b... | You could accumulate the elapsed time and only add the noise once enough steps have passed:
double elapsedTime = 0;
double INoiseThreshold = 0.005;
for(int j=0; j<runs; j++){
//...
for(int i=0; i<t_steps; i++){
//...
double Inoise = 0;
elapsedTime += dt;
if(elapsedTime >= I... |
65,752,626 | 65,752,925 | Concept for smart pointers | Given a class template like this:
template<typename T>
struct foo
{
T data;
};
How may one determine whether T is a smart pointer such as std::shared_ptr<T_underlying> using C++20 concepts?
I want to add functionality to foo<T> based on this criteria. For example, Instead of using SFINAE, I'd like to use the new c... | You might first create a traits to detect if type is a std::shared_ptr (way depends if you want to consider inheritance or not).
And then use the traits to build a concept:
template <typename T> struct is_shared_ptr : std::false_type {};
template <typename T> struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {}... |
65,753,116 | 65,753,223 | how to declare function in vb.net to call c++ dll | I need to call a function located in a C++ dll from a VB.NET project.
The definition in C++ dll documentation is:
HRESULT GetStatus(LPBYTE lpSize, LPBYTE lpStatus, HWND hWnd = 0)
lpSize Data: size of lpStatus
lpStatus: Specify a pointer of an area to store the Device Status.
The Status and following data are stored.
2... | LPBYTE would normally be declared ByVal lpSize As Byte() so:
Public Function GetStatus(ByVal lpSize As Byte(), ByRef lpStatus As Byte(), ByVal hwnd As Long) As Integer
Check the C++ function is actually StdCall, it may be CDecl.
EDIT
Looking at the small amount of info you provided, I very much doubt that lpSize is d... |
65,753,224 | 65,753,479 | how to ensure proper indentation in datas ifstreamed from a file. Look at my code , it's not giving desired results | if(role==2)
{
int arr;
ifstream record("total.txt");
record>>arr;
record.close();
string names[arr];
int age[arr];
ifstream file("names.txt");
ifstream file0("ages.txt");
for(int i=0;i<arr;i++)
{
getline(file, names[i]);
... | You can use setw and left IO manipulators:
for(int i=0;i<arr;i++)
{
std::cout << std::left << std::setw(32)
<< names[i] << " " << age[i] << std::endl;
}
left ensures the following data is aligned to left, meaning any fill characters will be appended after the output data. setw set width of the following da... |
65,753,525 | 65,756,412 | reading transparent images boost.gil C++ | I have a image with a transparent background and I want to copy it over another image both images are png format I've tried using boost::gil::rgba8_image_t but it still copies the transparent image with a gray background instead.
this is what I've used
#include <boost/gil.hpp>
#include <boost/gil/extension/io/png.hpp>
... | Mmm. Reading this it seems to do exactly what you ask it:
bg::resize_view(bg::view(temp), bg::view(pic), bg::bilinear_sampler{});
This fills the pixels with a resized view of your input image. The new size matches exactly that of your jail. Now:
bg::resize_view(bg::view(temp), bg::view(pic), bg::bilinear_sampler{});
... |
65,754,093 | 66,179,959 | Best place for constant array declaration | While attempting to write the fastest factorial function that evaluates at run-time, I found myself questioning whether it is a good idea to declare the constant array f[] at the function level or at the unit level.
#include <stdint.h>
#include <cassert>
// uint64_t const f[21] = { 1,1,2,6,24,120,720,5040,40320,36288... | In my humble opinion the best is to let the compiler decide and do evrything with constexpr. The compiler will make the best decision for you.
And because the number of factorials that will fit into an unsigned 64 bit value is very low (21), a compile time array will use mainly only 21*8 = 168 bytes.
168 bytes
That num... |
65,754,250 | 65,754,938 | Add extra methods at compile time according to some enum value | Imagine I have the following class:
class Extra final
{
public:
void Method1() const {std::cout << "Method 1" << std::endl;}
void Method2() const {std::cout << "Method 2" << std::endl;}
};
I created, for some class T, a class template that can enable/disable methods using Extra at compile time according to di... | Alternatively, you can put the enable_if into the template instead of the return type declaration. I personally find this a bit more readable, and it has the advantage that you can use return type deduction.
template<typename T, Scenario R>
class ExtraAdder : public T {
Extra m_extra;
public:
template<
... |
65,754,444 | 65,754,569 | Use '&' to create pointer to member error upgrading VS 2013 to 2019 | This code compiles file in VS 2013 but in VS 2019 I get this error almost anywhere I try to use Callee function's
typedef void (XMessage::*FUNCTION)();
void FgAddTimer(FUNCTION function, DWORD dwTime);
CursorMsg.FgAddTimer((XMessage::FUNCTION) XCursorMsg::OnTimer, 200);
gives
'XCursorMsg::OnTimer': non-standard s... | Solved it.
Don't do
&OnLoad
but instead do
&CStaticModel::OnLoad
|
65,754,511 | 65,755,858 | Accesing variables across all struct in C++ | Let's say a have a following code:
struct Joe {
const double weigth = 88.6;
const double heigth = 185.6;
const double X = Alice().heigth; // Error: undeclared identifier.
};
struct Alice {
const double weigth = 65.2;
const double heigth = 179.1;
const double X = Joe().heigth; // No issues
};
I... | I don't believe there exists a solution given that you require that Joe::X must be default initialized as Alice().height and v.v for Alice::X. The very declarations of the classes are dependent on each other and are thus circular.
If you don't require that said variables must be default initialized, you can declare the... |
65,754,713 | 65,757,148 | How to force google benchmark to run multiple iterations? | I use google benchmark to test two C++ functions. One runs for ~630,000,000 ns and one runs for ~1,000,000,000 ns. But both only run one iteration. How can I force the benchmark to run more iterations? I would like it to run at least 10 times.
| For those who encounter similar problems:
There is no way to directly control the number of iterations for a benchmark. Instead, one can use benchmark_min_time to indirectly configure the number of iterations a benchmark runs. A simple way to do this is:
BENCHMARK(YourBenchmark)->MinTime(10); // 10 seconds
|
65,755,221 | 65,755,438 | How do I define a variable in a namespace with "using namespace"? | So I have a namespace thing with extern int variables declared in a header. I'm trying to define them in a .cpp with using namespace thing; to simplify initialization, but it doesn't seem to work the way I expected when trying to define a variable in thing.cpp. What gives?
main.cpp:
#include <cstdio>
#include "thing.hp... | using namespace thing allows you to use identifiers from the thing namespace without prefixing them with thing::. It effectively pulls them into the namespace where the using directive is (or the global namespace).
It doesn't put further definitions into the namespace thing. So when you define int a;, it's just in the ... |
65,755,445 | 65,755,495 | error with "expression must have a constant value" | I am a newbie with C++. I am trying to make a program that can find the average, max, min, and median. I am not sure what I did wrong in my code, I am getting an error with double scores[n];:
#include <iostream>
#include<iomanip>
#include "ArrayFunction.h"
using namespace std;
int main()
{
int n;
double sco... | You can declare an array with known size at compile time! so the size must be constant!
int values[10];
int values2[] ={1,2,3};
constexpr int size = 10;
int values3[size];
const int size2 =5;
int values4[size2];
All of above examples are defined at compile time with const size!
for runtime initialization you can use... |
65,755,996 | 65,756,006 | Please explain why these logical operators are not working as it seems they should in CPP | Sorry if this is a noob question or formatted strangely, I'm new to programming and also new to StackOverflow. So my brother and I were trying to code a short program that utilizes a do-while loop and a switch statement within it. This is a short version of the code that illustrates the issue we were having.
#include <... | Read the condition (selection != 'Q' || selection != 'q') very carefully, token by token:
"do... while the selection not equal to 'Q' OR while it's not equal to 'q'".
Since selection can't be q and Q at the same time, it's always the case that it's either not equal to q, or not equal to Q, or both.
Your intention is to... |
65,756,419 | 65,756,541 | I want to convert int to char array where 0-7 bits of int are 1st char 8-15 2nd etc | So here is the code but for some reason intToChar function returns "abcd" and some gibberish at the end. I was trying to change my newly created array to 0 first but then I'm getting access violation errors.
int charToInt(char x[])
{
int z = 0;
for (int i = 0; i < sizeof(int) / sizeof(char) && x[i]; i++)
{
... | As noted in the comments, your use of sizeof(z) is sizeof(a_pointer) -- not what you want. Instead, given that sizeof(char) is always 1, you can simply do:
#include <iostream>
int charToInt (char *x)
{
int z = 0;
for (size_t i = 0; i < sizeof(int) && x[i]; i++)
{
z <<= 8;
z |= x[i];
... |
65,756,911 | 65,756,965 | Can an if condition be a for loop? | Just wondering if the condition of an if statement can be a for loop in C++14. For example:
using namespace std;
if (for (int i = 0; i < 10; i++)){
cout << "The number now is " << i << endl;
}
| A condition has to be something which can be evaluated as a boolean (such as a boolean literal, a function call which returns a boolean, you name it), or something convertible to a boolean e.g. via a bool() type conversion operator. A for loop is not evaluated as anything. It is simply a block of code which runs under ... |
65,757,009 | 65,759,547 | Why did the error of the result of my ANN program only decreased a little while i was training it? | I tried to train a 3-layer ANN with the function xor, but it doesn't work.
the input is 2 boolean number and the output is 2 number which represent the probability that the result is 1 or 0;
This is its variance at the beginning.
...
0 0
res: 0.24121 0.197543
variance: 0.35106
...
This is its variance after it has tra... | I think I've just fixed it, there are few problems in my code.
I updated w[i,j] in the wrong way
The wrong one is:
w[i,j] <- w[i,j]+ trainingrate * delta[i] * net[i,j]
However the correct way is:
w[i,j] <= w[i,j]+ trainingrate * delta[j] * net[i,j]
The learning rate should be bigger (thanks to Alexander Guyer 's a... |
65,757,816 | 65,760,404 | Is there any input that would cause getline to fail in C++? | Except for inputs like ctrl c etc.
To my understanding getline can only fail when reaching EOF, but I'm not very sure.
| The short answer is : Anything that causes the input stream to be in an error state.
An "error state" of a standard stream (derived from std::istream) is expressed in terms of one or more of std::ios_base::failbit, std::ios_base::eofbit (associated with end of file), or std::ios_base::badbit being set. ios_base is a... |
65,757,865 | 65,770,590 | How to detect which swapchain is out of date? | I have multiple swapchains and one of them gets out of date.
if (swapchain_count) {
VkPresentInfoKHR present_info = {
VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,
NULL,
0,
NULL,
swapchain_count,
swapchain_array,
swapchain_index_array,
NULL,
};
vkQueueP... | The VkPresentInfoKHR structure has a pResults field: if non-NULL, each entry in pResults will be set to the VkResult for presenting the swapchain corresponding to the same index in pSwapchains.
// Provided by VK_KHR_swapchain
typedef struct VkPresentInfoKHR {
VkStructureType sType;
const void* ... |
65,757,898 | 65,757,912 | How to reference template parameters of outer classes in innter classes? | The following code
template<typename T>
void f();
template<typename T>
class A{
class B{
void f(){
f<T>();
}
};
};
does not compile, and gives the following error
<source>:10:15: error: expected primary-expression before '>' token
10 | f<T>();
What is th... | Your problem is that f is not the name of a template on that line. It is the name of the method.
::f<T>(t);
Try that.
|
65,758,047 | 65,758,138 | GCC template : error : expected ',' or '...' before '< ' token | I'm a new bee to C++.
I'm having below errors when tying to compile below templates example copied from "Essential C++", I simply copied the example on the book.
"error : expected ',' or '...' before '< ' token"
"error : 'vec' was not declared in this scope
I was wondering what could be the problem, could you help spar... | There's a lot of issues with the code that prevent from compilation:
The functions fibon_seq and is_size_ok are not defined. You have to define them in this file or include them with a #define macro.
The code appears to be including the std namespace. You need to include this with using namespace std;, usually at the ... |
65,758,110 | 65,758,692 | Copy event objects through the interface | I am currently working on a little project and adding an event system. I'm trying to defer the events so that they can be handled in an event part of the update stage. But the problem is that I can't figure out how to copy or create an Event* from an Event&.
Here is a simplified version of the problem:
#include <list>
... | I don't think that polymorphically copying the event objects is what you actually need (although that will work) but rather transferring the ownership of these event objects to and from the event queue.
Very likely, the events are generated somewhere and then stored in the event queue. Eventually, the events stored in ... |
65,758,139 | 65,758,684 | Referencing a template from an inner class | I have the following code
template<typename VP,bool b>
class ValueProcessor{
template<typename Access,typename X> void processValue(X& x){}
};
template<typename VP>
class ValueProcessor<VP,true>{
public:
template<typename Access,typename X> void processValue(X& x);
};
template<typename VP>
... | As pointed out in the comment the solution is to add a .template discrimitaor before the member function name:
valPro.template processValue<Access,X>(x);
This is necessary because the type of ValueProcessor<VP,false> valPro is a dependent type (i.e. it's actual type depends on the type of the template parameter VP) the... |
65,758,145 | 65,758,174 | Why isn't my binary search giving me a result for the first element? | I'm trying to return the index of the element to be searched. All the elements are being detected except the first element. What's wrong? Why is the function not returning index 0?
using namespace std;
int binsearch(int a[],int x,int y)
{
int low=a[0];
int high=a[x-1];
while(low<=high)
{
int mi... | int low=a[0];
int high=a[x-1];
should be
int low=0;
int high=x-1;
|
65,758,198 | 65,758,214 | Can I use "using" instead of "typedef" for a pointer to class member variable? | #include <iostream>
using namespace std;
struct Pos {
int x;
float y;
};
typedef int Pos::* pointer_to_pos_x;
//using pointer_to_pos_x = ???;
int main()
{
Pos pos;
pointer_to_pos_x a = &Pos::x;
pos.*a = 100;
cout << pos.x << endl;
}
Can I use using instead of typedef in this situation?
I ha... | Just this:
using pointer_to_pos_x = int Pos::*;
Virtually all cases of a typedef XXX aaa; can be converted readily to using aaa = XXX;. You may also find this Q/A useful: What is the difference between 'typedef' and 'using' in C++11?
|
65,758,227 | 65,758,313 | How to independently check more than one variable? | This is the part of the code with the error:
int value = analogRead(LM351);
float Temperature = value * 500.0 / 1023.0;
lcd.setCursor(6,0);
lcd.print(Temperature);
lcd.setCursor(11,1);
int value1 = analogRead(LM352);
float Humidity = value1 * 500.0 / 1023.0;
lcd.setCursor(10,1);
lcd.print(Humidity); ... | You could include both conditions in the first if-else statement:
if (Temperature > 24 || Humidity > 10){
digitalWrite(motor, HIGH);
digitalWrite(LedRed, HIGH);
digitalWrite(LedGreen, LOW);
lcd.print("");
}
else {
digitalWrite(motor, LOW);
digitalWrite(LedRed, LOW);
digitalWrite(LedGreen, HI... |
65,758,234 | 65,758,449 | string concatenation, log4cplus, and MISRA compliance | I am using log4cplus, and my misra-checks for something as innocent-looking as
LOG4CPLUS_INFO(
logger,
std::string("ABC") + std::string("DEF"));
yield (among others) The underlying type of `0L` is implicitly reduced from `8-bit signed char` to {code{bool}}.. This happens also when I put the respective ... | I had a look at LOG4CPLUS_INFO and that is a macro defined as:
#if !defined(LOG4CPLUS_DISABLE_INFO)
#define LOG4CPLUS_INFO(logger, logEvent) \
LOG4CPLUS_MACRO_BODY (logger, logEvent, INFO_LOG_LEVEL)
and LOG4CPLUS_MACRO_BODY is defined as:
#define LOG4CPLUS_MACRO_BODY(logger, logEven... |
65,758,558 | 65,850,202 | Test Programs are not running | I've been creating a game engine. When I was testing the code I was receiving following errors:
Application.cpp
namespace SkyEngine {
__declspec(dllimport)void Print();
}
void main() {
SkyEngine::Print();
}
Test.cpp
#include "Test.h"
#include<stdio.h>
namespace SkyEngine {
void Print() {
printf(... | It looks to me like you have set up the build incorrectly.
As I could see, your entry point is in the project "SkyEngine" but its built as a dll.
Project "Sandbox" as I guess, depends on the "SkyEngine.dll" file but contains the exports. I guess its the executable file in your solution.
Since you have not provided a l... |
65,758,662 | 65,758,835 | How to use struct with stack? | Normally when we use stack we do this....
stack<int>st;
st.push(1);
st.push(2);
st.push(3);
cout<<st.top<<"\n"
But my question is how to push and access data when we use struct instead of int/char type variable? For example...
struct st
{
int index, value;
};
int main()
{
stack<st>STACK;
/*
code
*/
}
... | You can push to std::stack by using Aggregate initialization, or adding a constructor to your structure or std::stack::emplace.
By using constructor:
struct st
{
st(int _index, int _value) : index(_index), value(_value) {}
int index, value;
};
std::stack<st> s;
s.push(st(10, 20));
By using Aggregate initializatio... |
65,758,888 | 65,758,933 | How do you allow comma to be used for user input for integer based input c++? | I am pretty new to c++ and I am trying to make a program that prints out the number based on user input. But when you add a , it breaks the code since it is not part of integers. What should I do?
I made a simplified code because I want to do more with the integers:
#include <iostream>
using namespace std;
int main()... | Read the input in as a string:
std::string input;
std::cin >> input;
Remove the commas, using the erase-remove idiom:
input.erase(std::remove(input.begin(), input.end(), ','), input.end());
which from C++20 you can write like this:
std::erase(input, ','); // C++20
Convert the string to an int:
int player_input = ... |
65,758,939 | 65,759,267 | Filling a vector of bytes with random bytes | I wanted to fill a std::vector<BYTE> with random or pseudo-random bytes of data. I have written (in other word, find it) the following source code in the stackoverflow but it doesn't compile in my Visual Studio.
#include <Windows.h>
#include <vector>
#include <random>
#include <climits>
#include <algorithm>
#include <f... | The answer from Evg is correct.
If you really want to have random bytes only, I would use a custom generator function that generates values between [-128, 127] or any desired range.
For instance:
#include <iostream>
#include <Windows.h>
#include <vector>
#include <random>
#include <algorithm>
#include <limits>
int ma... |
65,759,054 | 65,759,160 | OpenGL texture rendering does not match original | I am trying to render a texture with OpenGL. The texture I am using as a test is a bunch of black rectangles on a white background, as follows:
However, when rendering, the texture seem to be duplicated and overlayed multiple times on top of itself:
I set the scene up using:
std::string vertexSource = ShaderLoader::l... | When an image with 3 channels (GL_RGB) is loaded to a texture object, GL_UNPACK_ALIGNMENT needs to be set to 1. By default GL_UNPACK_ALIGNMENT is 4, so each line of an image is assumed to be aligned to 4 bytes. The pixels in the buffer have a size of 3 bytes and are tightly packed, this would cause a misalignment.
glPi... |
65,760,697 | 65,760,774 | Defining an array of a custom struct type | I have tried to make an array of a struct I have defined like in Creating an array of structs in C++ but I get an `no matching function to call to Simplex::simplex()' error. What is going wrong? Underneath is (what I think is) the relevant code. The error is in the Simplex simplices[numberOfSimplices] line.
struct Simp... | Simplex simplices[numberOfSimplices];
is going to create numberOfSimplices number of Simplex's. Since you don't convey how to create those objects, the assumption is Simplex objects are default constructable using Simplex(), but there is no default constructor available in Simplex class, the only constructor available... |
65,760,856 | 65,778,109 | Visual Studio / Qt - Cannot open source file "QApplication" | I have VS 2017, qt-opensource-windows-x86-msvc2015_64-5.8.0, qt-vsaddin-msvc2017-2.6.0-rev.07.
https://api-2d3d-cad.com/c-qt/ to setup.
Qt VS Tools widget is present, can make Qt Console Application.
But:
#include <QMainWindow>
#include <QLabel>
Cannot open source file "QApplication"
Cannot open source file "QLabel"
... | To use Qt libs in Visual studio do next steps! This answer is based on Visual studio 2017! on other versions, differences are only on menus or settings interfaces!
Install Qt Vs Tools, check its version compatibility with Visual studio
Go Qt VS Tools -> Qt Options menu
In Qt Versions tab, add installed Qt libs with... |
65,760,940 | 65,761,090 | Reversing a String Using Iterators | I'm trying to reverse a string (e.g change "bro" to "orb") using iterators. Unfortunately, my code doesn't work. Here's my code:
for(std::string text; std::cin >> text;){
for(std::string::const_iterator it = text.cend() + 1; it <= text.cbegin(); --it)
std::cout << *it;
}
return 0;}
Where did I go wrong?... | Firstly your code isn't reversing a string, it's printing a string backwards. Not the same thing at all.
The easy way to print a string backwards would be to use a reverse iterator
for (auto it = text.rbegin(); it != text.rend(); ++it)
std::cout << *it;
But if you want to do it with a regular iterator then the fol... |
65,761,365 | 65,761,586 | Why in OpenGL my camera rotates 180 degrees every other time? | I want to do something like a 3d-shooter.
The calculations seems to be correct, but it is works every other time with a spread with 180 degree rotation on every call glutPostRedisplay(). I understood that thanks to that red line.
I do this with such IDE: Code Blocks / Qt Creator under Linux(Ubuntu x64).
main.cpp
#inclu... | You're using the fixed function stack, so you'll have to learn what glMatrixMode does and how transformation matrices are managed in those old ways.
Anyway, consider this a possible implementation of glMatrixMode
void glMatrixMode(GLenum m)
{
switch(m){
case GL_MODELVIEW: ctx->M = &ctx->matrix_modelview; brea... |
65,761,547 | 65,761,920 | How to use default constructor while using composition? in visual studio | i keep getting when i declare Game object in the main : // C2512: no appropriate default constructor available , I am using visual studio , on other compilers that error doesn't always appear .
I tried to change the way to define and initialize but It keep giving me the same error, something like this was in a question... | The constractur Game(Screen& ok, string nam = "minecraft"); needs to get a reference to Screen object.
And when you create Game object like this:
Game gg;
there's no reference to Screen object.
A good example of a constactur call would be:
Screen s;
Game gg(s);
Other tip is the to put the implementation on other file ... |
65,761,961 | 65,762,015 | How to change objects inside of vectors globally c++ | When an object is placed inside a vector, the vector makes a copy of the object, this means that any changes to the object does not change the object inside the vector. How do i make so any changes to the object also change the object inside the vector.
#include <iostream>
#include <vector>
using namespace std;
class ... | You can do this in two way
change the object from the vector like :
#include <iostream>
#include <vector>
using namespace std;
class objectClass {
public:
int x = 0;
};
vector<int> my_vector;
int main()
{
objectClass testObject;
vector<objectClass> my_vector = {testObject};
my_vector[0].... |
65,762,111 | 65,776,786 | Is there any way to pass ordinary function and call template function? | #include<iostream>
using namespace std;
template<class T>
void display(T a){
a += a;
cout << "Template Function: " << a << endl;
}
template <class T1, class T2>
void display(T1 a, T2 b){
cout << "a: " << a << endl << "b: " << b << endl;
}
void display(int x){
cout << "Ordinary Function: " << x << end... | The syntax for calling a template function is:
functionName<dataType>(arg1, arg2, ...);
By default, the compiler will call the ordinary function of the same name, if it finds the exact match. Which is void display(int x) in this case. If you want to call the template function, instead of its ordinary version, you nee... |
65,762,357 | 65,762,390 | Can't get rid of volatile from template type argument | In my code I have the following class (a bit simplified for this question, obviously):
template<typename T>
class MappedMemory
{
private:
T* localAddress;
public:
void* getGenericDataPointer()
{
return reinterpret_cast<void*>(localAddress);
}
}
It doesn't work when f... | You need to apply remove_volatile or remove_cv traits to the type T itself, not the pointer to it.
auto normalAddress = const_cast<typename std::remove_cv<T>::type*>(localAddress);
Note that remove_cv removes both const and volatile qualifiers, while remove_volatile only removes the latter.
|
65,762,500 | 65,762,732 | Failing to compile explicitly specialized template struct on g++/clang++ with std::enable_if | I've tried to compile this with msvc and it compiles fine. On the other hand I failed to compile it with g++ and clang++. Error I get is no type named ‘type’ in ‘struct std::enable_if<false, void>’. How would I resolve this error?
#include <type_traits>
template <bool v>
struct a {
template <typename T = typename... | You are not using SFINAE correctly because the bool you pass to enable_if (which is v) is not dependent on the function template parameters.
The canonical way to selectively add or remove members of a class template is to use template specialization. For example:
template <bool v>
struct a {
void function();
};
te... |
65,762,520 | 65,762,642 | how to use ros | cmake with gitlab-ci | I have a simple project but i have no experiences with GitLab-ci. I use ROS and cmake to build my project on my local machine(ubuntu18-04).
now I want to build my project on GitLab but this doesn't look easy for me.
Steps:
1-) installed binary runners from here
2-) registered runners from here for Linux
- used docker a... |
Which system exactly am I working on right now
You clicked selected ruby:2.6 default image so you are on ruby:2.6. You may then browse docker hub : https://hub.docker.com/_/ruby and dockerfile https://github.com/docker-library/ruby/blob/8e49e25b591d4cfa6324b6dada4f16629a1e51ce/2.6/buster/Dockerfile - I see it has "bu... |
65,762,952 | 65,763,035 | C++ strcat_s String is not null terminated | My code gives me an error:
Debug assertion failed.
Expression: (L"String is not null terminated" && 0)
class Rectangle {
private:
char* objID;
}
Rectangle::Rectangle(const Rectangle& rect ) {
std::cout << "Copy constructor for: " << rect.objID << std::endl; // отладочный вывод
objID = new char[strlen(rect.... | It should be something like;
const char* psuffix = "(кoпия)";
size_t size = strlen(rect.objID) + strlen(psuffix) + 1;
objID = new char[size];
strcpy_s(objID, size, rect.objID);
strcat_s(objID, size, psuffix);
size_t size2 = strlen(rect.name) + 1;
name = new char[size2];
strcpy_s(name, size2, rect.name);
The second p... |
65,762,984 | 65,763,027 | The dining philosophers problem with critical section | I'm trying to solve the dining philosophers problem and each time it's printing that only 2 are eating.
Each thread I created was a philosopher and each section was a fork and according to the algorithm, each time we send a philosopher we try to get his forks(for the first it's fork1 and fork2) and the forks are the cr... | probably two of the threads or more accessing to the same criticalSection and overlap eachother.
try adding timer between each creation of a thread.
HANDLE WINAPI th1 = CreateThread(...);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
HANDLE WINAPI th2 = CreateThread(...);
|
65,763,150 | 65,763,280 | How exactly cross platform libraries works for different machines | Recently, I was learning about networking in C++ and I found boost.asio which is a cross platform library, and then I got a thought about how this library is a cross platform since Windows provides different library for networking and even mac also,
so how its function works on different machines, does cross platform l... | There are several possible ways:
Use ifdefs
char* doFoo(void){
#ifdef _WIN32
return "win32";
#elif ...
return ...;
#endif ...
}
The pro is, that it doesn't require much setup.
The con is, that it clutters the code, if you do it too much.
Have different implementations in different directories.
As a folder stru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.