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 |
|---|---|---|---|---|
68,850,314 | 68,901,066 | How to set the working directory of an executable program in Mac OSX | I created a C++ project in Xcode which successfully builds and runs a program in the Xcode environment. This program is dependent on existing in its current working directory to access several files. Outside of the Xcode environment, when I double-click on the executable file, I get a message that notifies me that the ... | So here's how I solved this:
I couldn't change the default directory that double-clicking on the program to run it would start up on.
I can use the chdir() function to move around directories. I moved to the root directory using chdir() after the program began and started me in Users/Username. More on chdir here: http... |
68,850,341 | 68,850,611 | Is it mandatory to lock mutex before signaling on condition variable? | We have implemented TaskRunner whose functions will be called by different threads to start, stop and post tasks. TaskRunner will internally create a thread and if the queue is not empty, it will pop the task from queue and executes it. Start() will check if the thread is running. If not creates a new thread. Stop() wi... |
Do I need to lock m_task_mutex before signaling [In Stop]?
When the predicate being tested in condition_variable::wait method depends on something happening in the signaling thread (which is almost always), then you should obtain the mutex before signaling. Consider the following possibility if you are not holding th... |
68,850,522 | 68,850,573 | How to break the inner while(cin>>s2) loop without breaking the outter while(cin>>s1) loop? | Please consider the C++ code below:
#include <string>
#include <iostream>
using namespace std;
void fun1() {
cout << "Calling fun1" << endl;
}
void fun2() {
cout << "Calling fun2" << endl;
}
int main() {
string s1, s2;
while (cin >> s1) {
fun1();
while (cin >> s2) {
fun2();
}
}
return 0;... |
but I want to know why does the above happen?
When you press Ctrl-D (Ctrl-Z on Windows) you close the stream, hence std::cin status returns false and internal loop terminated. As you use the same stream - std::cin in both loops and stream is closed already it would terminate them all, as this state is persistent. Via... |
68,850,660 | 68,851,035 | Allocating a large multidimensional vector causes memory "overshoot" | I observed an unexpected behavior when using a large multidmensional std::vector variable. In particular, when I allocate a 4-dimensional vector of large size, it can be seen, using a memory profiler, that my task shortly uses more memory than it would require for the variable.
An MWE to reproduce this behavior is the ... | This could be caused for different reasons, like returning without using smart-pointer (which could cause a copy).
But in your particular case, you pass something to F variable's constructor (no matter what), which takes additional memory till constructor returns.
Oh! yet another possible cause, an (un)intelligent vect... |
68,851,113 | 68,851,390 | Is a program where undefined behavior (UB) is conditional on implementation leeway a program with unconditional UB? | In the answer to
Is it valid to create closure (lambda) objects using `std::bit_cast` in C++20?
it was shown that a program could have undefined behavior "depending on" (des Pudels Kern in this question) how an implementation used implementation leeway given by the standard. As an example, [expr.prim.lambda.closure]/... | Assuming I understand the question correctly, here is a simpler example:
void* storage = ::operator new(100);
new (storage) std::string;
In some language implementation, where the string fits in the memory, the behaviour of this example program would be defined. But the standard does not provide a guarantee that any l... |
68,851,148 | 68,851,341 | C++: Simultaneous use of Integers and References to Integers | Consider the following class representing an integer parameter with upper and lower limits:
class Parameter
{
protected:
int value;
int minval;
int maxval;
};
I have a list of Parameter objects. Sometimes, a Parameter's minval/maxval will be the value of another Parameter in the list. Other times, they wil... | This is hard to answer without more information, but if you want the same class to have members that can either be an int or refer to an int that sounds like a use case for an std::variant, that is
class Parameter
{
protected:
int value;
std::variant<int, int*> minval;
std::variant<int, int*> maxval;
};
No... |
68,851,432 | 68,851,433 | Is there a strchr with boundary? | There is a char *strchr( const char *str, int ch ) function defined in <string.h>.
It has no boundary, after which it stops the search.
Is there a similar function somewhere, which you can pass a boundary to?
Edit:
I have a char* pos and a length of a substring and I want to find a specific ASCII character in it, but I... | You can try:
void* memchr( const void* ptr, int ch, size_t count )
|
68,851,481 | 68,851,695 | Is iteration order of two unordered_set-s with same contents guaranteed to be the same | If I have two unordered_set variables with same contents (if sorted), but created differently (say, first variable only had items inserted, second one had items inserted, erased, etc. in different order, but both variables ended up with same contents), will iterating over these two variables produce values in the same ... | The standard does not make such guarantee. The ordering is bound to be implementation-specific.
Consider this example to see why the ordering may be different even though the content is identical: let's start with two unordered sets A and B that have been created and filled with values in the same order until a point w... |
68,851,532 | 68,852,126 | How common is it to mix C with C++? | I wanted to know how widely used is the mixing of C++ and C. I mean as in using of C libraries/functions and call it in C++ program like how it is done here Mix C with C++. How extensive is its use in real world? Is it rarely used, avoided mostly or pretty common? Anybody can shed some lights on it??
| It is fairly common. You can either
compile the C stuff with C++ compiler without any issues OK, others noted that this is definitely not true: What issues can I expect compiling C code with a C++ compiler?
or
use both object files, static and dynamic libraries compiled with C compiler but then you should be aware ... |
68,852,597 | 68,867,131 | How to put image pixel data into an array in code? | I want to integrate the icon pixel data into the code of my C++ program. I'm using the SFML library. The window method to set the icon looks like this:
void setIcon(unsigned int width, unsigned int height, const Uint8 *pixels)
Of course, SFML provides methods to read image files and get to the pixels. However, I don't... | Expanding on Eljay's comment:
running xxd -i icon.png creates a file icon.h with the following content:
unsigned char icon_png[] = { <image file data> };
unsigned int icon_png_len = 264;
Note that icon_png does not contain the pixel data, but the whole file (thus, including the file header). With SFML, this is the cod... |
68,852,648 | 68,853,178 | Function return creates temporary despite using const references | I have a function, that returns a reference to an entry in a std::vector or a null object. I bind this object to a const & expecting it to point to the original object in the vector:
inline MyClass const & getSomeClassObject( char const * const strName ) const
{
static MyClass nullObj;
for ( auto const & entry : m_... | As discussed in the comments, the possible solution
inline MyClass const & getNullClassObject() const
{
static MyClass nullObj;
return nullObj;
}
inline MyClass const & getSomeClassObject( char const * const strName ) const
{
for ( auto const & entry : m_myClassObjectsVector )
{
if ( entry.name == strName... |
68,852,914 | 68,855,412 | Spirit X3: Rule that parses a single character and generates a string | Is it possible to create a rule in Spirit X3 that parses a single character and generates a string?
I'd like to use this in the context of a parser for version numbers, where each numeric identifier can be either a single digit, or a non-zero digit followed by one or more digits:
auto const positive_digit = char_(L"123... | It's not completely clear to me what you're trying to do. If the goal is to valid the format of a string but parse match the input string exactly, why not use x3::raw?
E.g.
auto num_id = x3::uint_;
auto version = x3::raw[num_id % '.'];
Now you can directly parse typical version strings into a string:
Live On Coliru
i... |
68,853,060 | 68,853,181 | Take generic lambda return type into consideration for SFINAE | I'd like to have a function that takes a generic lambda, but I need slightly different logic based on the lambda's return type. For example, I'd like to do something like the following (this is a contrived example):
template<typename F>
void foo(F &&function) {
auto result = function();
// Have different behavi... | You don't need SFINAE for this. As mentioned in a comment, you could just write the different logic based on the return type in different overloads, and call that overload set
void f(int); // do the logic for an int
void f(double); // do the logic for a double
// ... and so on
template<typename F>
void foo(F &&functio... |
68,853,472 | 68,854,476 | Is this a bug in Clang's C++20 concepts implementation? Unnecessary checking of constraints causes infinite template recursion | I have this definition of a C++20 concept:
#include <concepts>
template <typename T> concept Numeric =
requires(T a, T b) {
{ a + b } -> std::same_as<T>;
{ a - b } -> std::same_as<T>;
{ a * b } -> std::same_as<T>;
{ a / b } -> std::same_as<T>;
};
I have this class template which uses the concept to co... | I think this is a clang bug. Here's a reduced example:
template <typename T>
concept Numeric =
requires(T a) {
foo(a);
};
struct Deferred {
friend void foo(Deferred);
template <Numeric TO> operator TO();
};
static_assert(Numeric<Deferred>);
When checking to see if foo(a) is a valid expression... |
68,854,285 | 68,854,395 | Populate an array with templated function pointers using a loop? | I have a templated function that creates a unique static function to route a callback to various instances (workaround for an old C API with global state).
class CallbackObject
{
// callback state storage
...
public:
void callback(...){ ... };
} _slots[SlotCount];
template<size_t slot>
static void callback(.... | If you switch to using a std::array, you can write a function to do this for leveraging a variadic template. This first function takes a std::integer_sequence and uses it to create a parameter pack of std::size_t objects that will have the values of the range [0, size_provided)
template <std::size_t... Is>
auto make_c... |
68,854,860 | 68,859,567 | I can't properly add external dependency with bazel | I trying to test "Hello World" C++ project with Bazel.
I have the following project structure:
WORKSPACE
/dependencies
BUILD
BUILD.gtest
/test
BUILD
WORKSPACE has the following structure:
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# gtest
http_archive(
name = "gtest",
url = "ht... | The file BUILD.gtest is not needed.
WORKSPACE.bazel:
workspace(name = "GTestDemo")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "gtest",
url = "https://github.com/google/googletest/archive/release-1.10.0.tar.gz",
sha256 = "9dc9157a9a1551ec7a7e43daea9a694a0bb5fb8bec81... |
68,854,879 | 68,855,054 | C++ Creating Array of Objects | I'm having an issue with making one array with 3 objects. I'm trying to display the information of employees and my issue is that I don't know where I would assign the strings to the appropriate members and how to keep one variable for name. My code and an example are below:
class employee
{
private:
... | You can simply call the setter methods on the individual employee objects, eg:
int main()
{
employee employeeInfo [numEmployees];
employeeInfo[0].setName("Tom Jones");
employeeInfo[0].setIDNumber("123456");
employeeInfo[1].setName("James Blyth");
employeeInfo[1].setIDNumber("QE123");
// and s... |
68,854,955 | 68,855,164 | How to assign variables from colon-separated text file c++ | I have a .txt file:
A:One:1:2:15.
B:Two:0:6:5.
C:Three:0:4:6.
D:Four:0:4:8.
E:Five:0:6:2.
And I need to read the file, and assign each value between the (:) to an appropriate variable.
Here is my code so far:
int main()
{
ifstream theFile("Parts.txt");
if(theFile.is_open())
{
string line;
while(getline(theFil... | getline(ss, minimum, ':');
The second parameter to std::getline is always a std::string. minimum is not a std::string. It is an int, this is why this fails to compile. When calling a function in C++ all parameter types must be correct, or convertible (implicitly or by a user-specified conversion operator) to the param... |
68,855,124 | 68,855,699 | SFML starting a new song once another song is complete | #include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Audio/Music.hpp>
using namespace std;
int main (){
sf::RenderWindow window(sf::VideoMode(800, 600), "My Window");
... | If you want the music to play again, then you need to stop() the current music, even though it has come to its own end, because that will rewind the music back to the beginning.
if(music.getStatus() == sf::SoundSource::Status::Stopped)
{
music.stop(); // rewind to beginning
music.play();
}
BTW you should use s... |
68,855,382 | 68,855,452 | C++ pointer to pointer of array | how to pass array to this function ?
this is the function :
void fire(const uint8_t *const s[])
{
cout<<*s<<endl;
}
and I want to pass this array to that :
unsigned char X[10] = {255,255,255,255};
it is done by this and it works
unsigned char X[5] = {255,255,255,255};
unsigned char *pointertoX ;
pointertoX = X;
fire(... |
this is the function :
void fire(const uint8_t *const s[])
That function accepts a pointer to a const pointer to a const uint8_t.
and I want to pass this array to that :
unsigned char X[10] = {255,255,255,255};
You cannot.
In order to pass an array into a function that accepts a pointer, the function would have ... |
68,855,580 | 68,855,627 | Why aren't union member data default-initialized? | AFAIK a class/struct/union that doesn't initialize its member data int the constructor-initializer-list, then they are default-initialized. If a member data is of built-int integral type then it has an indeterminate value. If it is of a class type then its default-ctor is invoked (accessible and non-deleted default-cto... |
So as you can see: the union U didn't initialize its member data a_ and i_
A union only ever has one member active, so there is never a case where two members could be initialised.
No member of a union initialised if you don't provide an initialiser in a user defined constructor.
|
68,855,731 | 68,856,187 | How to classify an NTTP class by creating a type trait? | In C++20, NTTP extends new types which brings us the term structural:
l-value ref
integral
pointer, pointer to member, and null pointer
enumeration
floating point
A class in which: all base classes and non-static data members are public and non-mutable and the types of data members and base classes must also be struct... | template <auto>
struct nttp_test {};
template<class T>
concept structural = requires { []<T x>(nttp_test<x>) { }; };
Demo.
|
68,855,931 | 68,855,944 | How do I properly use a range-based for loop for an std::array | I can iterate through the array with a traditional for loop and a traditional for loop with iterators, but when I try to use a ranged-based for loop, I do not get the same result.
#include <iostream>
#include <array>
int main() {
std::array<int, 5> ar = {1, 2, 3, 4, 5};
for(int i = 0; i < 5; i++) {
std... | In range-based for loop for(const int& i: ar), i refers to element but not index. So
for(const int& i: ar) {
std::cout << i << " ";
}
|
68,855,999 | 69,029,516 | Why function 'constexpr' specifier should match? | Why constexpr specifier on function declaration should match with definition if it makes sense only on definitions, i.e. function with only declaration visible in TU can not be constexpr
| There was bug in my compiler implementation.
constexpr at namespace scope has internal linkage by default, so
function with only declaration visible in TU
produces link error.
|
68,856,413 | 68,864,731 | Random shape and movement generation not drawing shape | I have been working on a simple C++ and SFML program recently, but have gotten stuck. Basically I want to do two things:
I want to generate a number of circles with random coordinates
I want to make those circles move randomly around the screen
I figured using a vector for the circles would be best so that I can use ... | It seems you just have to make a few changes.
The main ones (from the output of the diff command) are:
> // Give the circles definite radius value and segment count:
> for (int i = 0; i < numPeople; i++)
> {
> person[i].setRadius(size);
> person[i].setPointCount(100);
> }
and also:
... |
68,856,433 | 68,856,925 | data validation in c++ for integer input | void addItem(struct InventoryItem inventory[], int& size){
cout << "\nEnter the item name: ";
cin.getline(inventory[size].itemName, 100, '\n');
while (strlen(inventory[size].itemName) == 0){
cout << "Invalid item name!" << endl;
cout << "Enter item name: ";
cin.getline(inventory[size].ite... | If operator>> fails to extract a value, it puts the input stream into an error state. You are not clearing that state, or ignoring the bad input that caused it to fail, so operator>> keeps failing.
Try this instead:
void addItem(struct InventoryItem inventory[], int& size){
do {
cout << "Enter the item name... |
68,856,650 | 68,856,721 | Inform c or c++ compiler loop length is mutliple of 8 | I want to write the following function in c++ (compiling using gcc 11.1 with -O3 -mavx -std=c++17)
void f( float * __restrict__ a, float * __restrict__ b, float * __restrict__ c, int64_t n) {
for (int64_t i = 0; i != n; ++i) {
a[i] = b[i] + c[i];
}
}
This generates about 60 lines of assembly, many of w... | Declare the assumption with __builtin_unreachable
void f(float *__restrict__ a, float *__restrict__ b, float *__restrict__ c, int64_t n) {
if(n % 8 != 0) __builtin_unreachable(); // control flow cannot reach this branch so the condition is not necessary and is optimized out
for (int64_t i = 0; i != n; ++i) { //... |
68,857,039 | 68,858,277 | When using a systemd <service>.socket, which file descriptor receives the socket(s)? | When I create a <service>.socket systemd file, I can include entries such as:
ListenDatagram=/run/<service>/listen.sock
ListenFIFO=/run/<service>/IPC.FIFO
etc.
The systemd.socket documentation says that those sockets are passed to my application as file descriptor. What I do not see is: which file descriptors are thes... | It would be 3, 4, 5, 6 ...
sd_listen_fds() may be invoked by a daemon to check for file
descriptors passed by the service manager as part of the socket-based
activation logic. It returns the number of received file descriptors.
If no file descriptors have been received, zero is returned. The first
file descriptor may ... |
68,857,110 | 68,961,719 | strtok() change my buffer, I need stored some data that change in an arbitrary time, how can I do this? | I have a list with coordinates sent from a Python server to a C++ client like a buffer, then I need to split each coordinate, I used strtok() for this, but when the function is tokenized for the first time do it correctly, when my while cycle repeat and received a new list of coordinates, the function returns the first... | My problem isn't my strtok() function, after reading an ancient question post by me, I can realize that my problem was in the recv() function my correction was
recv(sockClient, recvBuf, strlen(recvBuf), 0);
for
recv(sockClient, recvBuf, sizeof(recvBuf), 0);
This solved my problem and finally, I could receive a contin... |
68,857,483 | 68,857,602 | C++ How to conditionally initialize a template class object? | I have a template class
template <typename T>
class myClass
{
T variable;
....
};
I want to create an object of myClass , depending of some condition the object should either hold a string or int . how do I conditionally initialize like below :
if (condition1)
myClass<userDefinedType1> x;
else
myClass<userDefin... | If the type of the problem isn't known until runtime, then your options are limited.
If the number of possible instantiations is small/simple and you are using c++17 or above, one option is to just use std::variant:
using MyClass = std::variant<std::monostate, myClass<userDefinedType1>,myClass<userDefinedType2>>;
auto... |
68,857,590 | 68,857,660 | My object's constructor is being interpreted strangely? | I have an object declaration Bitmap image(FileRead(filename)) that is ... really confused?
When I hover over filename in Visual Studio, it gives me the tooltip FileRead filename as if I were declaring a new variable in the parameter list. When I hover over image it gives me Bitmap image(FileRead filename) as if it wer... | This is a less common case of Most Vexing Parse, which got its name from reaction similar to yours.
The idea is that by application of Murphy law, if something can be translated wrong, it will, so if a declaration of variable looks like function declaration, it is the latter.
FileRead is a type name, in consequence Fi... |
68,858,032 | 68,858,385 | C++ QT Logger object | I am trying to create a globally accessible object (but I am not sure if creating a global object is a good solution) which will log to file my output stream. I would like it to work similar to std::cout, but with the difference that it would log to file.
class Logger
{
QFile* file;
QTextStream* stream;
public... | What you need is Singleton Design Pattern. In the entire program, you need only one object of your logger class. So you need to use Singleton Design Pattern and place it into a separate file and just included it in whatever you need the logger.
For using streaming like operators (shift operator <<), you simply need to... |
68,858,433 | 68,858,501 | OpenGL issue with calculating reflection/refraction and uniforms | I'm trying to calculate the reflection/refraction but with I perform a
gl_FragColor = mix(objectColor, environmentColor, 1.0f);
I start getting uniform errors that it can't find my uniform for lightPosition. This doesn't make sense as I'm using that uniform for calculating the diffuse lighting and when I remove the mi... | mix(x, y, a) can be expressed as x*(1.0−a) + y*a.
The last argument of mix is a constant. Hence the expression can be optimized by the compiler.
gl_FragColor = mix(objectColor, environmentColor, 1.0f);
is equal to
gl_FragColor = environmentColor;
So objectColor is not used and therefore lightPosition is not used... |
68,858,728 | 68,862,276 | Converting R split() function to C++ | Consider the reproducible example in R:
test <- c(1:12)
> test
[1] 1 2 3 4 5 6 7 8 9 10 11 12
The expected result:
test.list <- split(test, gl(2, 3))
> test.list
$`1`
[1] 1 2 3 7 8 9
$`2`
[1] 4 5 6 10 11 12
I am trying to write equivalent code in C++ to produce and return the two vectors that resulted ... | We can use the nice answer by @jignatius and make it an R-callable function. For simplicity I keep it at NumericVector; we have a boatload of answers here that show show to switch between NumericVector and IntegerVector based on the run-time payload.
Code
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::List mysplit(Rcpp:... |
68,859,134 | 68,859,209 | Is there a way of using an anonymous class in a typedef? | Consider
template<class Base> struct ChildT : Base
{
};
struct NoBase{};
typedef ChildT<NoBase> Child;
Is there a way of writing this typedef so you don't need to define NoBase? I'm thinking of something like the following:
typedef ChildT<class {}> Child;
| There's std::monostate, which is defined just like your NoBase.
As you can see from the link it is not been thought for your use case, but essentially it can. After all, it's just a unit type.
I'm not sure whether std::monostate is the only empty struct in the STL. Nothing comes to mind, except std::nullptr_t, which ho... |
68,859,263 | 68,859,309 | Unable to understand why *a++ is not working and *a=*a+1 is? | Why is it that when I use *a++ it doesn't affect my answer and gives me a warning. However it works fine with *a=*a+1 in the below code?
#include <bits/stdc++.h>
using namespace std;
void incrementptr(int* a)
{
//*a++;
*a=*a+1;
}
int main()
{
int a=10;
cout<<a<<endl;
// increment(a);
// cout<<... | operator precedence: postfix ++ has higher precedence than *, hence *a++ is parsed as *(a++). It increments the pointer and dereferences a (the value before the increment) and the result of the expression is unused.
I suppose this is just to practice pointers, but there shouldn't be any pointer in your code. Only use ... |
68,859,580 | 68,859,721 | How can I use the implementation of a base class for a pure virtual method of a interface class? | I have a BASE class implementing a virtual method f(). I also have a INTERFACE class, that has a pure virtual method f(). I then have a DERIVED class that inherits both the BASE and the INTERFACE. When I try to instantiate DERIVED I get an compiler error "cannot instantiate abstract class".
class BASE
{
public:
... | Because the void f() of INTERFACE is never defined, BASE does not inherit from INTERFACE, so that is not an override of that function.
DERIVED does not define a void f(), so it also does not override that INTERFACE function, so that function has no body.
If you would want it to use the BASE::f to override INTERFACE::f(... |
68,860,276 | 68,862,575 | Unique_ptr usage for pimpl - doesn't compile even though destructor is declared | I'm trying to use unique_ptr for a pimpl idiom. So I'm declaring a destructor inside the class so the unique_ptr deletion is not instantiated where the impl class is not defined, and then I define it in another file.
This is my layout:
wrapper.h:
#pragma once
#include <memory>
struct Wrapper
{
class Impl;
~Wra... | Any constructor definition (including the implicitly defined default constructor) potentially invokes the destructor of the types of all member objects of class type. The rationale for this is that if constructing a later member throws, the destructor of all previous members would need to be called. In the case of the ... |
68,860,823 | 68,860,952 | void* data type in linked list? | I am trying to implement key, value linked list so I declared:
template<class S, class T>
class node {
public:
S key;
T value;
}
Now I want to support this function:
StatusType Add(void *DS, int key, void* value)
{
// key - the key of the node
// value - pointer to the value of the node
}
I'm confused... | If I understand you correctly, you need to implement the StatusType Add(void *DS, int key, void* value) function so it can be used by C code, but your own implementation can use C++.
In that case, the obvious choice would be std::map<int, void*>. Linked list types don't have keys.
|
68,861,326 | 68,861,678 | C++ - "unspecialized class template" in unordered_map with shared_ptr to template class | I have a class UISceneParams and I use it to store some parameters that I want to send over to a UIScene. It contains a unordered_map of shared_ptrs to DataParam instances.
The problem is that my DataParam must use a template and feature multiple data types.
Is there any way I can make the unordered_map use multiple da... | You could make your DataParam inherit from a marker interface like IDataParam, where the interface is just like
class IDataParam
{
virtual ~IDataParam() = default;
};
You could then store all your params as unordered_map<string, shared_ptr<IDataParam>> since they all have the same base type.
Then when getting the ... |
68,861,711 | 68,861,852 | Clion How to Add Debug Flags? | I used to compile my program like this:
g++ -std=c++11 –DNDEBUG –Wall *.cpp
Now I moved to use Clion, where it has the following CMakeLists.txt, can someone kindly help me on how to add the above flags to it? (Already added C++11 flag):
cmake_minimum_required(VERSION 3.20)
project(DS_WET1_PART1)
set(CMAKE_CXX_STANDAR... | Globally, you can use :
add_compile_definitions(NDEBUG)
add_compile_options(-Wall)
Otherwise, use the target specific calls:
target_compile_definitions(DS_WET1_PART1 PUBLIC NDEBUG)
target_compile_options(DS_WET1_PART1 PUBLIC -Wall)
|
68,861,767 | 68,861,818 | How to read again from the first line when end of file? | I want to read data from my input file:
Dr Lee
Dr Kumar
Dr Masji
Dr Hioh
Dr Yeoh
here is my sample code:
#include <iostream>
#include <string>
#include<fstream>
using namespace std;
int main()
{
int num = 0;
string doc[100];
ifstream inFile;
ofstream outFile;
inFile.open("hi.txt");
outFi... | You can go to the beginning of the file with:
inFile.seekg (0, inFile.beg);
|
68,862,110 | 70,081,483 | Is this a valid binary mutex implementation? | I'm not really sure if this types of questions are frowned upon here, but it is the first place I come for when I have a question in mind, so, here we go.
I have a std::vector<T> v that I use to store data. In thread t1, there is a data generator and data insertion can happen at any time. On the other hand, in thread t... | Using std::atomic_flag to implement a spin lock worked well for the last 3 months. Also, since my implementation didn't have an atomic test-and-set mechanism, I'd say, NO, it's not a valid (thread-safe) implementation. Thanks to Igor Tandetnik for his suggestion.
|
68,862,966 | 68,863,291 | Scope resolution in c++ | I have a program:
#include <iostream>
using namespace std;
class A {
public:
virtual void Output() {
cout << "A";
}
};
class B :public A {
public:
A::Output();
void Output() {
cout << " B ";
}
};
int main() {
A* a = new B;
a->Output();
return 0;
}
I don't understand... | When used in a method of a subclass of A, the A::Output() is an expression calling the Output method from the A class. As any other executable expression, it can only be use inside a method and not in the class body. Because the class body should only contain declarations (and definitions). For example, you cannot call... |
68,863,124 | 68,863,229 | Is this strict aliasing violation? Can any type pointer alias a char pointer? | I'm still struggling to understand what's allowed and not allowed with strict aliasing. With this concrete example is it violation of strict aliasing rule? If not, why? Is it because I placement new a different type into a char* buffer?
template <typename T>
struct Foo
{
struct ControlBlock { unsigned long long num... | Strict aliasing means that to dereference a T* ptr, there must be a T object at that address, alive obviously. Effectively this means you cannot naively bit-cast between two incompatible types and also that a compiler can assume that no two pointers of incompatible types point to the same location.
The exception is uns... |
68,863,258 | 68,864,565 | Dev C++ not detecting error about using only single angle bracket with cout? | I have a program for adjacency matrix implementation in C++.
Here is my code-
#include<iostream>
using namespace std;
void addEdge(int * add){
cout<<"Edge added successfully.\n";
*add = 1;
}
int main(){
int vertex;
cout<<"Enter number of vertices in the graph: ";
cin>>vertex;
i... | The compiler is taking advantage of ostream's operator bool. Before C++ 11, it was implemented as operator void * and returned a void* rather than bool resulting in a syntactically legal (but logically incorrect) pointer < pointer comparison. You've found one of many good reasons the operator was replaced with the mode... |
68,863,485 | 68,863,543 | Release memory of std::vector in VC++ 2019 | I've recently started upgrading my current projects from VS2015 to VS2019 and VS2019 is a lot more restrictive about some things. One thing I have an issue with in particular is the way I'm currently releasing the memory of vectors:
std::vector<int> v(10);
v.swap(std::vector<int>()); // v should now be empty with no me... | Your doing it backwards. To clear and release the memory for a vector in a guaranteed way, declare a temporary vector and swap the vector that needs to be cleared into it. That would tun your code into
std::vector<int>{}.swap(v);
At the end of the expression, the temporary object will be destroyed, taking the memory... |
68,863,752 | 68,863,778 | How do I check if a file pointer is valid? | I am using fseek and fread on a FILE * like this:
void CAudioDataItem::finalizeItem_ReadEncodedBytesWithoutDecoding(FILE* uFile, CLog* uLog, double& uTimeReadEncodedBytes)
{
//t.start();
fseek(uFile, iFirstByteToRead, SEEK_SET);
fread(&m_EncodedBytes[0], sizeof(unsigned char), m_lLenEncodedBytes, uFile);
... | If the question is on C++ as one of the tags imply,
There's typically no way to tell if the pointer dangles, i.e., points to memory that no longer holds the object the pointer is supposed to point to.
from Effective Modern C++, in the introduction to Chapter 4 - Smart Pointers, page 117.
If it's on C, then from the c... |
68,863,906 | 68,864,102 | How to create an operator-> for a class unique_ptr | I have to implement a simple "unique_ptr" class supporting only a constructor, destructor, –>, *, and release(). And I did below.
However, it feels weird to write "up.operator->()" to get the pointer p. I would be more logical to write "up->p". But how do I do that? Thanks!
#include <iostream>
#include <stdexcept>
tem... |
However, it feels weird to write "up.operator->()" to get the pointer p.
It feels weird because the member access operator is not generally used to get a pointer to the object (although you can do it using the operator->() syntax, as you demonstrated). Member access operator is used to access members of the object. I... |
68,863,952 | 68,906,937 | Lookup table with several different numeric types? | Background
For the UI of an embedded project have to display several variables on a screen and make it possible to edit those.
Currently, in my UI code, I have an enum containing the possible values, and I use a switch statement to find the currently selected one and show/edit it:
enum class ConfigPar {
a,
b,
... | Inspired by @Errorist's answer, I ended up with this:
class ConfigPar {
enum class ConfigParType {
ui8,
ui16,
d,
};
public:
// The nested struct is in order to have an overloaded constructor for the type and the union, but avoid
// having to strcopy the label
struct Var {
... |
68,864,176 | 68,864,325 | C++ function with noexcept in this case is actually slower? | I'm trying to experiment with code by myself here on different compilers.
I've been trying to lookup the advantages of disabling exceptions on certain functions (via the binary footprint) and to compare that to functions that don't disable exceptions, and I've actually stumbled onto a weird case where it's better to ha... |
Why is clang doing this extra code for us?
Because the behaviour of the function is different.
I didn't request any other action but calling new()
By declaring the function noexcept, you've requested std::terminate to be called in case an exception propagates out of the function.
allocated_int in the first program ... |
68,864,529 | 68,864,680 | Using define directive to get the namespace name | Having such a simple C++ code:
#include <iostream>
#define NS NS_Static
#define MAKESTRING(x) #x
namespace NS {
int global_x = 8;
void print_global_x() {
std::cout << MAKESTRING(NS) << "::global_x: " << global_x << std::endl;
}
}
I'h expected to get on output NS_Static::global_x: 8 BUT getting just NS::glo... | That's how stringizing (#x) in the C preprocessor works.
Unlike normal parameter replacement, the argument is not macro-expanded first.
To get the parameter to macro-expand, add another layer of indirection (a no-op macro like you've discovered, will suffice).
|
68,864,605 | 68,864,943 | Is it O(NlogN) or O(N^2)? | I am trying to solve a problem on BinarySearch.com:
Given a list of integers nums sorted in ascending order and an integer k, return whether any two elements from the list add up to k. You may not use the same element twice. Note: Numbers can be negative or 0. This should be done in O(1) space.
So for nums = [1, 3, ... | As noted in comments in worst case the code iterates over the array and performs binary search on the array in each step. And so the complexity of that operation is O(Nlog(N)).
I use distance(), which, as I understand, is an O(n) operation by itself.
Actually it is O(1) when used on std::vector::iterator because it i... |
68,865,386 | 68,881,781 | "malloc(): corrupted top size" when constructing vector | I'm trying to create this function:
std::vector<int> graph::getNeighbors(int n){
int i = 0; for(int el : verteces[n]) i++;
if( i != 0){
auto iter = verteces[n].begin();
std::vector<int> res = std::vector<int>{i};
for(int j=0; j<i; j++)
res[j] = *(iter++);
return res;... | Without even looking at the code, I added -D_GLIBCXX_DEBUG1 to compiler flags (to enable container bounds checks) and got this:
Error: attempt to subscript container with out-of-bounds index 1, but
container only holds 1 elements.
Then I used GDB to understand where exactly that happens:
void greedyAlgorithm(graph &G... |
68,865,599 | 68,868,438 | Simplest way to read MFC messages from HWND? | I am trying to use an api library with functions that send messages to a server, then receive back messages. One of the function's arguments is a HWND and the library document says the message will be received by it. To read the received message I studied a few MFC documents, created a class that inherits CDialog with ... | You sure don't need MFC for that. Not even a "Windows" app - a simple console app will work, just keep pumping messages:
#include <iostream>
#include <windows.h>
int main() {
HWND hWnd = CreateWindowW(L"static", L"", 0,
0, 0, 0, 0, HWND_MESSAGE, nullptr, nullptr, nullptr);
MSG msg;
while (true) {
... |
68,866,142 | 68,866,969 | Does it make sense to use different mutexes with the same condition variable? | The documentation of the notify_one() function of condition variable at cppreference.com states the following
The notifying thread does not need to hold the lock on the same mutex as the one held by the waiting thread(s); in fact doing so is a pessimization, since the notified thread would immediately block again, wai... | I think the wording of cppreference is somewhat awkward here. I think they were just trying to differentiate the mutex used in conjunction with the condition variable from other unrelated mutexes.
It makes no sense to use a condition variable with different mutexes. The mutex is used to make any change to the actual se... |
68,866,194 | 68,866,427 | Can you access another program's stack/heap if you know the address? | Just a miscellaneous question.
I have a program in C++:
#include <stdio.h>
int main()
{
while (1) {
int value1 = 1;
printf("%p\n", (void *)&value1);
void* address = (void *)&value1;
int value2 = *(int*)address;
printf("%d\n",value2);
}
return 0;
}
What this does is... | Each process has it's own address space and addresses in a program refer to that address space, independent of the addresses in any other address space. So when you put an explicit value into a pointer like that and use it, you'll get whatever is at that address in this process (which is probably invalid, so you get a... |
68,866,788 | 68,895,760 | C++ constraints on variadic template arguments | I stumbled upon this code in the SerenityOS project:
template<typename... Parameters>
void dbgln(CheckedFormatString<Parameters...>&& fmtstr, const Parameters&... parameters)
They are re-implementing an equivalent of println! from rust. An easier version of printf where you don't need to care about the argument type a... | See the https://en.cppreference.com/w/cpp/language/template_argument_deduction#Implicit_conversions :
Type deduction does not consider implicit conversions (other than type
adjustments listed above): that's the job for overload resolution,
which happens later.
How does the FormatString/IdentityType change things? The... |
68,866,903 | 68,866,944 | Why isn't this method being overridden? | In a project of mine I encountered this problem where the polymorphism seemingly doesn't work. Derived classes don't seem to override the base class, but no errors ocurr either.
This is a simplification of the code, but it generates the same problem. The usage of vector and unique_ptr is the same as in my project, I su... | You need to make_unique<B> and add a virtual destructor to the base class.
make_unique<B> creates a unique_ptr<B> that, if B is derived from A will be accepted by (moved into) a unqiue_ptr<A>.
make_unique<A>(B()) copy constructs an A from a B, slicing the B (only the A part of the default constructed B will be copied)... |
68,867,432 | 68,869,333 | Runge-Kutta 4th-Order | Right now I am trying to make my Runge-Kutta work. Actually I have to solve a ODE-System which is a lot more complicated than this ODE-System, but the runge-kutta-function is the same. I'm solving this simple system to check if the simulation converges to the analytical solution.
First of all I would like to ask you if... | I have highlighted several inconsistencies in the RK4 code
Anything that deals with y should call fy and have derivative l and anything that deals with x has derivative k.
|
68,867,954 | 68,868,377 | Why does my vector not re-size properly after erasing items? | I wrote a small program to remove 0's from a vector. But when I check, there is still a zero in the vector. why?
The size says its 4 when it should be 3 and there is still a zero showing.
int main()
{
vector<int> nums1 = {1, 2, 3, 0, 0, 0};
for(int i=0; i< nums1.size(); i++)
{
if(nums1[i] == 0)
... | When an element of the vector is erased then all elements that follow it are moved left occupying the position of the erased element.
That is if the element at the position i was erased then the element that follows it now will be at this position. So you shall not increase the position.
For example
for( std::vector<i... |
68,868,029 | 68,868,131 | In what order does tensorflow::Tensor's flat method return the data? | Let's say I create a tensor with the following dimensions
[num_tracks,num_frames,height,width,num_channels]
*output = tensorflow::Tensor(tensorflow::DataType::DT_UINT8,
{4, 11, 128, 128, 3});
And I then return the data with the flat method.
auto data = output->flat<uint8>().data();
In... | Search in TF sources the file tf_tensor.h which contains the following sentences:
// --------------------------------------------------------------------------
// TF_Tensor holds a multi-dimensional array of elements of a single data type.
// For all types other than TF_STRING, the data buffer stores elements
// in row... |
68,868,553 | 68,868,587 | Find out reason for class finalization | At some point of time, a class in my C++14 project is being terminated / finalized.
However, I don't see why it is being terminated / finalized.
I would like to find out the reason / caller for this.
It looks like this:
The call stack however, doesn't tell me. Or at least I don't see why.
How could I find out why / wh... | In the Options menu, under “Debugging/General”, deselect “Enable Just my code” and it’ll show you the full callstack. (You’ll likely need to restart the debugger.)
|
68,868,794 | 68,869,061 | Is it safe not to destroy an object of a class type that is a member of a union? | I have this example:
struct A{
A(){std::cout << "A's def-ctor\n";}
~A(){std::cout << "A's dtor\n";}
A(A const&){std::cout << "A's copy-ctor\n";}
A& operator = (A const&){std::cout << "A's copy-assign op\n"; return *this; }
};
struct Foo{
Foo() : curMem_(INT), i_(0){}
~Foo(){
if(curMem_ ... | The exact wording of the standard given in [basic.life]p6 is:
For an object of a class type, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression ([expr.delete]... |
68,868,991 | 68,875,827 | Calling a function on weak pointer | I have written the following code:
#include <iostream>
#include <memory>
using namespace std;
class Foo
{
int x = 0;
public:
int get() const { return x; }
void set(int x) { this->x = x; }
};
int main(){
auto sp = shared_ptr<Foo>(new Foo());
weak_ptr<Foo> wp;
wp = sp;
return 0;
}
I wan... | You cannot operate on a weak_ptr. If the shared_ptr has been deleted, it would be like dereferencing a raw pointer that had been deleted.
Whenever you want to access the pointer contained in it, you would lock it to verify your shared_ptr still exists.
if (auto sp = wp.lock()) {
sp->set(10);
} else {
// sp no long... |
68,869,162 | 68,869,432 | How to change what value begin() iterator points to? | In C++ using the STL, I have a std::forward_list<int> whose iterators I want to modify, but I'm not sure how to/if it is even possible.
Say I have a forward list of the following elements:
std::forward_list<int> list {1,2,3,4,5};
Here, list.begin() returns 1. How can I move list.begin()? Say I want to set the beginnin... | Let's look at a picture. You have a singly-linked list with five elements.
1 --> 2 --> 3 --> 4 --> 5 --> null
^ ^
| |
begin end
Now you want to make the beginning of the list point to the node with 4.
1 --> 2 --> 3 --> 4 -->... |
68,869,179 | 68,880,979 | How do I associate two Tcl_Interp? | I have a code that looks like this:
myCmd::myCmd(std::string outFile) : _tclInterp(Tcl_CreateInterp()), _outFile(outFile)
{
_myParser = CC::CmdParser(_tclInterp, registerAllCommands);
}
The thread which created the Tcl_CreateInterp() might be different from what is being used in the CC::CmdParser. Internally CC::C... | Tcl interpreter objects internally use thread-specific data extensively in order to avoid most global locks. This goes as far as including thread-specific memory management pools, at least for common allocations, and Tcl code is executed as part of initialising the interpreter state, so it's really not possible to use ... |
68,869,453 | 68,869,534 | Overriding assignment operator in derived class | Assume class D is derived from a base class B where D doesn't have any data members
I came up with the following to overload the assignment operator = for class D
#include<iostream>
#include<string>
using namespace std;
class B {
private:
std::string* str = nullptr;
public:
const B& operator=(const B& rhs... | I think a better implementation would be:
if (this != &empl)
B::operator= (empl);
This avoids the cast, which is, at best, dubious.
But, as @Some programmer dude says, what is the purpose of D::operator= anyway? It doesn't do anything that B::operator= doesn't do, so you don't need it.
|
68,869,485 | 68,869,557 | Finding prime numbers in an array | I am trying to iterate through an array and determine if each number is prime or not.
Here is my code:
constants.h
#pragma once
#ifndef CONSTANTS_H
namespace constants {
constexpr int randomOne[10] = { 1,3,5,7,9,12,13,15,18,23 };
}
#endif // !CONSTANTS_H
main.cpp
#include <iostream>
#include "constants.h"
int... | Apart from the out-of-bounds error mentioned in the comments, you get the logic backwards -- saying that if count==2 then the number is not prime -- and you neglect to reset count.
In short, your code is full of bugs which you could have spotted if you had started with something small and simple that worked perfectly, ... |
68,869,727 | 68,869,742 | C++ Initialized Variable Keeps Printing out as Zero Even though Function is Passed | I passed a function to calculate the sum of all the numbers in an array but it outputs as 0 which is what I initialized it to. The function is in a separate file from the actual program (I also created a class called Stats). When I display the total sum in the function, it shows the correct number. It's only when I ini... | Following up on @Someprogrammerdude's comment. You have to reassign the value of total to the value returned from calcTotal(), like this:
total = rainStats.calcTotal(rainFall, total);
|
68,869,761 | 68,870,168 | Using c++11 <thread> with COM threading apartments on Windows - hints, tips, pitfalls? | I am working on a Windows application that uses multiple USB sound interfaces with ASIO drivers. Each driver exposes an in-process COM server and has to be run using a Single Threaded Apartment.
My plan is to run each in it's own STA responsible for processing callbacks and controlling the devices while the heavy lifti... | Whether you create a thread via a framework call like std::thread or _beginthreadex(), or if you just call the Win32 CreateThread() directly, ultimately it all ends up in the same place within the OS.
COM is a system component, as are threads. They are independant of any particular compiler, but they do depend on the O... |
68,869,971 | 68,870,368 | C++ template, linking stage undefined reference error | I'm using C++ templates and encounter the following issue.
I try to use class ImplG's method func in class ImplM, however the linker reports an error.
user:/home/test/build# make
Scanning dependencies of target main
[ 50%] Building CXX object CMakeFiles/main.dir/main.cc.o
[100%] Linking CXX executable main
/usr/bin/ld:... | Make your class abstract (by adding = 0), something like:
template <class T, class R>
class Gathering {
public:
virtual R gather(const T&) = 0;
};
|
68,870,009 | 68,870,111 | Equivalent of python walrus operator (:=) in c++11? | Recently I have been using the := operator in python quite a bit, in this way:
if my_object := SomeClass.function_that_returns_object():
# do something with this object if it exists
print(my_object.some_attribute)
The question
Is there any way to do this in c++11 without the use of stdlib?
for example in an ar... | Python's := assignment expression operator (aka, the "walrus" operator) returns the value of an assignment.
C++'s = assignment operator (both copy assignment and move assignment, as well as other assignment operators) does essentially the same thing, but in a different way. The result of an assignment is a reference to... |
68,870,053 | 68,870,587 | How to get world coordinates from the screen coordinates | I am trying to get world coordinates from the screen coordinates.
This is my process.
Get the Screen coordinates from the mouse click
Multiply projection with view matrix
FinalMatrix = projectionMatrix * viewMatrix;
3)Inverse the matrix
finalMatrix = glm::inverse(finalMatrix);
Get the position in world coord... | I assume that screenPoint.xy is the poisition of the mouse in window coordinates (pixel). And screenPoint.z is the depth from the depth buffer. You must transform the position to Normalized Device Cooridnates. NDC are in range (-1, -1, -1):
glm::vec3 fC = screenPoint;
glm::vec3 ndc = glm::vec3(fC.x / 1920.0, 1.0 - fC.y... |
68,870,516 | 68,877,021 | Does std::thread constructor completion actually synchronize with the beginning of the thread of execution? | The C++11 standard (N337, 30.3.1.2) states about the synchronization of the std::thread constructor:
Synchronization: The completion of the invocation of the constructor synchronizes with the beginning of the invocation of the copy of f.
Reading it, I thought the constructor completes before the start of the new thre... |
Reading it, I thought the constructor completes before the start of the new thread
"synchronizes with" is a term of art. When the standard mandates that two operations synchronize with each other, that carries with it certain requirements for evaluations before and after the two operations. For example, accessing a ... |
68,870,677 | 68,871,376 | Must destructor be just available (public) or fully valid for default initialized class members? | Please consider a struct A having a field u of type U<R> with a default initializer. The destructor ~U<R> is only declared:
template<typename T>
struct U {
~U();
};
struct R;
struct A {
U<R> u = U<R>{};
};
All compilers accept this code, demo: https://gcc.godbolt.org/z/oqMjTovMo
But if we define the destruct... | [dcl.init.aggr]/8: (emphasis mine)
The destructor for each element of class type is potentially invoked ([class.dtor]) from the context where the aggregate initialization occurs.
[basic.def.odr]/8:
A destructor for a class is odr-used if it is potentially invoked.
[basic.def.odr]/10:
Every program shall contain ex... |
68,870,729 | 68,871,254 | Multi-threaded code not working as expected | As I am very new to the concept of Multi-Threading, I'm trying to keep things very simple. The complete program I have written below in Visual Studio 2019 was an attempt to compare the performance of a single thread vs 3 threads running simultaneously. Each thread has its own data to work on so I have assumed there is ... | First, your fib1, fib2, fib3 arrays are small, and probably share the same CPU cache line on a modern processor (e.g. some Intel or AMD in 64 bits mode, designed after 2015). So you could have contentions. Read about cache coherency protocols.
Did you try with arrays larger than the page size (usually 4Kbytes at least ... |
68,870,810 | 68,874,781 | compiler suggests two candidates for class | I am learning c++98 and I get this error while compiling my Node class:
Node.cpp:13:1: error: no declaration matches ‘Node::Node(Node::dataType&)’
13 | Node::Node(dataType& initData){
| ^~~~
In file included from Node.cpp:7:
node.h:13:7: note: candidates are: ‘Node::Node(const Node&)’
13 | class Node{
... | The confusion here stems from the compiler’s thoroughness in reporting the candidates. The first is the implicitly declared copy constructor, which refers spatially to the class name because, well, it’s implicit. That’s not very helpful to see here because you can’t define an implicitly declared function anyway, but ... |
68,871,498 | 68,899,962 | Switched OS version, vulkan program stopped working | A program I was developing stopped working when I upgraded from Ubuntu 20.04 to 21.04
What I suspect is happening is, I am using conan to install dependencies, including what would be inside the sdk (the loader, the headers, the validation layers).
vkcube and vulkaninfo run, so vulkan itself is fine.
The conan package ... | This reddit comment seems to have been the solution:
https://www.reddit.com/r/Fedora/comments/krz20h/vulkan_swrast_lavapipe_is_getting_used_instead_of/
specifically:
After reading through Archwiki, I've discovered that lavapipe is indeed being used instead of radeon.
exporting VK_ICD_FILENAMES=/usr/share/vulkan/icd.d/... |
68,871,812 | 68,872,747 | android ndk - cast jchar* to char* | why when casting jchar* to char* , c++ add a zero between each array element ?
java :
public char[] mychar;
.
.
mychar = new char[3];
mychar[0] = 10;
mychar[1] = 20;
mychar[2] = 30;
c++ :
Java_com_example_bb_mainact_getchar(JNIEnv *env, jobject thiz) {
jclass cls = env->GetObjectClass(thiz);
jfieldID fi... | jchar is a 16-bit type. char is usually an 8-bit type.
You could fix this e.g. by treating data as a pointer to a bunch of 16-bit elements, or by using a byte[] instead of a char[] on the Java side.
|
68,871,929 | 68,896,918 | How are gzip content stored in a file? | I am able to compress certain content with "gzip" format and store it in a file. This content can be decompressed programatically within my code.
But I can't "gunzip" them using command line or other tools. e.g. "Hello World" (11 bytes) is compressed properly as 'test.txt.gz', but upon double clicking or from command l... | The problem is that you wrote a gzip header, and then followed that with a zlib-format stream! You need to follow the gzip header with raw deflate data, with no zlib-format wrapper.
Don't use compress2(), which can only make a zlib stream. Use the deflate functions, documented in zlib.h. You can request that deflate pr... |
68,872,214 | 68,872,429 | Why does C++ allow this pointer polymorphism of private parent? | If I inherit a derived class privately from a base class, I cannot get the polymorphism of the inhritetted class.
But I can get the polymorphism of 'this' pointer inside the derived class.
I'm very curious about why 'this' pointer is allowed to polymorphism to its private parent, however, a pointer outside of the class... | The question asked here is why a base class is accessible when privately inherited.
The answer is rather simple: Because base classes are always visible to inherited regardless of the type of inheritance.
You can static_cast to a base class when the base is visible within the context.
class base
{
};
class inherited... |
68,872,572 | 68,872,590 | lambda "call operator" and "parenthesized lambda" | I've read an answer and stumbled upon sample code below which is Elliott's answer from other SO question HERE
I have issue trying to understand two things (and to know how this syntax is called) :
#include <iostream>
template <typename ... T>
void Foo (T && ... multi_inputs)
{
int i = 0;
([&] (auto & inpu... |
f is a lambda here
auto f = []() { return 42; };
int i = f(); // i = 42
whereas, adding () immediately call the lambda:
int i = []() { return 42; }(); // lambda called immediately
// i = 42;
(f<Ts>(), ...) or (f(args), ...) are fold expressions (with comma operator) to expands variadi... |
68,873,296 | 68,873,536 | Store object instances of PCA9635 in array | I am working with a hardware PWM-LED-Controler called "PCA9635". This chip can be controlled in Arduino with the Library "PCA9635".
In the example provided in the library, an ledArray with the i2c address 0x70 is initiated by:
#include "PCA9635.h"
PCA9632 ledArray(0x70);
My Project requieres an unknown number of PCA9... | Try
PCA9635 ledControlers[2] = {PCA9635(0x70), PCA9635(0x71)};
or
PCA9635 ledControlers[] = {PCA9635(0x70), PCA9635(0x71)};
|
68,873,315 | 68,880,797 | How to use static library that contains C++20 modules | I have a static library project UserInterface that contains the following module:
// Foo.ixx
export module Foo;
export void MyFunc();
void MyFunc()
{
[]() {};
}
The module Foo is imported in the main header of the library like this:
// NuiLibrary.hpp
#pragma once
import Foo;
// Windows
#define WIN32_LEAN_AND_M... | What was the cause ?
After a day of trying my specific problem was that the Microsoft Package Server was file locking the .ifc file causing the could not find module error.
How to detect ?
You can find out if you have this issue by trying to compile the module just by itself via right click module -> Compile. It will t... |
68,873,415 | 68,873,669 | CUDA NPP min-max returns wrong output | I'm using the following code to test the CUDA NPP min-max function.
#include <string.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string>
#include <math.h>
#include <assert.h>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include "cuCom... | Regarding to the NPP documentation, Min and Max must be stored on the device memory (or at least accessible from the device) and not on the host memory like in your code. On way to fix that is to allocate some memory to store the min/max values and then transfer the values back to the host to print them like in the doc... |
68,873,605 | 68,873,670 | Why does #define not multiply numbers as expected in arduino/c++? | Arduino has been giving me unexpected values when trying to multiply numbers together in preprocessor.
e.g.
#define msPerDay (24 * 60 * 60 * 1000)
void setup() {
Serial.begin(9600);
Serial.println(msPerDay);
}
void loop() {}
This should output 86400000 but instead I get
23552
In the serial monitor. Also
#defi... | Your int is a 16 bit integer. A 16 bit integer holds values up to 2^15-1 if signed, and 2^16-1 if unsigned.
As those have no suffix, they are all ints, so overflow is undefined.
In practice, your compiler is doing math modulo 2^16.
Odds are that long on your platform is 32 bits. Append an l to those values. It is qu... |
68,873,894 | 68,873,906 | what is wrong in this easy if else c++ code? | This question is in hackerrank conditional statements and i wanted to solve it without using array.The code runs but gives wrong output. Can anyone see what is the mistake in this code , Why would it not work?
#include <bits/stdc++.h>
using namespace std;
int n ;
cin >> n ;
int main()
{
int n ;
cin>>n;
... | You should use '==' not '='
because "if (n=1)" behaves the same as "if(true)"
== is compare
= is assignement
|
68,874,047 | 68,874,338 | Avoiding multiple includes c++ | My header files are structured as follows
base.h
/ \
/ \
utilities.h parameters.h
\ /
\ /
kernels.h
Where utilities.h consists only of functions and parame... | It seems to be not possible to avoid include headers several times, because you need usualy to include headers which are needed by the source code. But you can use include guards. There are two kinds of it:
#ifndef BASE_H
#define BASE_H
... <your code>
#endif
or another method is the following:
#pragma once
Both ... |
68,874,175 | 68,874,321 | Why is `typename` prefix still required in such a case in C++20? | According to https://stackoverflow.com/a/61991146/508343:
One of the new features in C++20 is Down with typename.
In C++17, you had to provide the typename keyword in nearly all†
dependent contexts to disambiguate a type from a value. But in C++20,
this rule is relaxed a lot. In all contexts where you need to have a
t... | The answer is speaking loosely about what "context" means. What the feature is doing is finding places where it is grammatically impossible for anything other than a typename to appear in that location. It is those places where typename is no longer necessary.
For example, using name = X;. Grammatically, this is a type... |
68,874,264 | 68,874,832 | What is the best method to find the difference between two unsigned 16-bit numbers? | Introduction:
Assume that you have two 16-bit unsigned numbers that can have values from 0 to 65535.
Let's say we have a array arr[2] and it's located inside a while loop:
i = 0;
while(1){
arr[i++] = Get_New_Value();
if(i == 2)
i = 0;
}
It's easy to say that this can be measured, just by changing the while lo... | If we assume that Get_new_value is called more often than around once every 3 seconds, that means that the value (after accounting for wraparound) will never change by more than half the range of a uint16_t.
Based on that, we can deduce that the most recent value is the one that the result of subtracting the other from... |
68,874,784 | 68,875,253 | "Use of undefined type" error even though I have forward declared the type | I am making a chess game and I have some classes that roughly look like this.
struct MovementValidator;
struct Piece
{
Piece(MovementValidator* movementValidator) :
movementValidator{ movementValidator }
{
}
virtual ~Piece() { delete movementValidator; }
enum class Type
{
PAWN... | struct PawnMovementValidator;
is a declaration, not a definition. It tells the compiler that a struct exists with the name "PawnMovementValidator", but in the constructor of Pawn it needs to know the size of the struct in order to allocate memory for it. In other words, its definition needs to be known.
Solution: Not ... |
68,875,446 | 68,875,478 | How to convert an integer to a character in C++ | Say I have an integer and I want to convert it to a character? What methods are available or should I use in C++? For example, refer to the given code below
#include <bits/stdc++.h>
using namespace std;
int main
{
int i = 1;
// Say I want to convert 1 to a char '1';
... | char c = digit + '0' ;
It will do your work.
|
68,875,759 | 68,875,866 | How to compile cpp project in github repository to exe? | I'm new to programming, so this might be a stupid question :)
So I found this project on github - https://github.com/GPUOpen-Effects/FidelityFX-CLI
and I want to "compile it to executable", but have 0 idea how to do that.
The project is done in VisualStudio
Can someone help me with that?
Thanks for reading :)
| It's got sub-modules which makes it tricky.
Start with this regardless of how you want to compile:
git clone https://github.com/GPUOpen-Effects/FidelityFX-CLI
cd FidelityFX-CLI
git submodule init
git submodule update
Then (command line - assumes you've run the vcvars32.cmd or equivalent)
cl.exe /EHsc /MT FidelityFX_CL... |
68,875,809 | 68,875,891 | CMake cannot find OpenCVConfig.cmake even after specifying OpenCV_DIR | I'm running a C++ program using OpenCV. I've installed all necessary libraries but it seems cmake cannot find OpenCV libraries.
The command port content opencv3 shows my opencv libraries are under these folders:
/opt/local/libexec/
/opt/local/bin/
/opt/local/lib/
/opt/local/include/
but adding set(OpenCV_DIR /opt/local... | CMake commands do not separate their arguments via ,. Thus when you wrote:
set(OpenCV_DIR, /opt/local/share/OpenCV)
You in fact set a variable named OpenCV_DIR, to /opt/local/share/OpenCV. You can "fix" it by removing the comma:
set(OpenCV_DIR /opt/local/share/OpenCV)
I say "fix" because this is not a good way of doi... |
68,876,134 | 68,881,101 | Passing a vec3 to glm::lookAt appears to modify it | I have encountered a situation where passing a glm::vec3 to the glm::lookAt function appears to modify it.
The following code is about shadow frustum calculation in a C++ / OpenGL game engine. The problem arises in the glm::lookAt function, at the end.
void Shadows::updateFrustumBoundingBox()
{
// Here we convert ma... |
I have encountered a situation where passing a glm::vec3 to the glm::lookAt function appears to modify it."
I don't think so. You use frustumCenter to caclucalte lightView, but before you do that, you use lightView to calculate frustumCenter: frustumCenter = invertedLight * frustumCenter;
So my educated guess on what... |
68,876,199 | 68,876,668 | In C++20 when should use `iterator_traits<I>::value_type` and when should I use `iter_value_t`? | C++20 concepts adds an alternative way to access iterator traits. For example iter_value_t<I> gives a similar result as iterator_traits<I>::value_type.I have noticed that iterator_traits do not appear to work in concept constraints.
iter_value_t works for concepts, but it also works everywhere else.
So my hunch is I sh... | You should always use std::iter_value_t<I>.
First of all, simply consider the length:
std::iter_value_t<I>
vs.
typename std::iterator_traits<I>::value_type
Because value_type is a dependent type, you'll need that extra typename keyword, so this is a mouthful.
Secondly, the former is simply defined in more cases than ... |
68,876,264 | 68,876,478 | Why am I getting this error? Error: invalid operands to binary expression | Hi When I am running this peice of code, it shows this error ->
Error: invalid operands to binary expression
Please find below code
#include<iostream>
using namespace std;
int main(){
int number = cin>>"Enter your number";
if(int number%2 == 0){
cout<<"Even Number"<<endl;
}
else{
co... | Not really sure if I can best explain this, but i'll try.
What is std::cin?
std::cin is a C++ function that reads input into "somewhere else"
That "Somewhere" is usually variable. It will then proceed to read the input into that variable.
For Example: cin >> Character Would read the input into the Variable Character
T... |
68,876,460 | 68,881,655 | The "(optional)" marker in cppreference.com documentation | Last week, I had a discussion with a colleague in understanding the documentation of C++ features on cppreference.com. We had a look at the documentation of the parameter packs, in particular the meaning of the (optional) marker:
(Another example can be found here.)
I thought it means that this part of the syntax is o... | The opt / (optional) suffix means the symbol is optional [for the C++ programmer to use; not the compiler to support]
As this question has been tagged language-lawyer, and as general when we look for a definite reference, let's move away from CppReference and into the standard.
Where CppReference uses the (optional) su... |
68,876,532 | 68,895,397 | Isometric tile placement | I am trying to make an isometric tile map with vertices. I managed to complete it without vertices. In my head it should be as easy as not doing it with vertices, but I can not get it to work. Dozens of attempts have been made, but I am missing something important.
const uint16_t tileMapSize = 16;
quad = &this->tilesD... | quad[0].texCoords = sf::Vector2f(tu * tileSize.x, tv * tileSize.y);
quad[1].texCoords = sf::Vector2f((tu + 1) * tileSize.x, tv * tileSize.y);
quad[2].texCoords = sf::Vector2f((tu + 1) * tileSize.x, (tv + 1) * tileSize.y);
quad[3].texCoords = sf::Vector2f(tu * tileSize.x, (tv + 1) * tileSize.y);
Since i made an error i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.