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 |
|---|---|---|---|---|
71,432,328 | 71,432,342 | How to set global Clang flags? | I'm using Clang on MacOS. When I compile C++ with clang++, is there a way to specify -std=c++17 without writing it every time? Is there some sort of a global clang config file?
| alias c++="c++ -O2 -W -Wall -std=c++17"
You can add something like that to your bashrc or whatever shell you use.
Another thing that should work on MacOS, works on every other unix, would be to create a wrapper script in /usr/local/bin/. Assuming you have that in your $PATH. Otherwise the problem recurses to exetending... |
71,432,398 | 71,432,419 | What is causing this baffling compiler error with templates and inheritance? | It took quite a while to distill this down to a manageable size, but here's the code:
template<typename T = uint8_t> struct ArrayRef {
T* data;
size_t size;
size_t capacity;
ArrayRef<T>(T* d, size_t c, size_t size) : data(d), size(size), capacity(c) {}
void Add(T* buffer, size_t size) { }
};
struct ByteArr... | When the name Add is found at the scope of class ByteArray, name lookup stops, the scope of class ArrayRef<uint8_t> won't be checked.
You can introduce ArrayRef<uint8_t>::Add into the scope of ByteArray, then it could be found and take part in overload resolution.
struct ByteArray : ArrayRef<uint8_t> {
ByteArray(uint... |
71,432,513 | 71,453,008 | Writing to a 3D Texture Using Framebuffers and Saving as Image | I'm trying to generate a 3D worley noise texture for some volumetric effects. I am simply generating a set of random points and for each fragment, I will find the closest point and get the distance between the fragment and the pixel. The distance is then used as the final color of the image. The result looks something ... | My issue was not with the texture but rather with how I was saving the images. I changed my texture saving function from this:
void Utils::SaveTexture3DAsBMP(const std::string& savePath, Texture3D* texture)
{
unsigned int size = texture->GetWidth() * texture->GetHeight() * 4;
float* data = new float[size];
... |
71,432,656 | 71,432,722 | Where is the usage of struct with flexible array memeber defined in the C/C++ standards? | If I have code like this
struct s { int x; char b[]; };
int main() {
struct s s[10];
}
and I compile with "gcc -O2 -W -Wall -pedantic" then I get:
<source>:4:14: warning: invalid use of structure with flexible array member [-Wpedantic]
4 | struct s s[10];
| ^
And gcc is totally right. ... | In C, it's §6.7.2.1, paragraph 3:
A structure or union shall not contain a member with incomplete or function type,… except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a struc... |
71,432,796 | 71,432,850 | Why does the Quantlib::Error class allocate a std::string on the heap? | In a code review recently, I had some less than kind words for something I thought awful. It turns out that it was obviously inspired by the QuantLib::Error class, which looks like this:
//! Base error class
class Error : public std::exception {
public:
/*! The explicit use of this constructor is not advised.
... | This is following the behavior of standard library exception types.
They are supposed to be copyable without throwing exceptions, since throwing an exception during construction of an exception handler parameter would cause a call to std::terminate (and possibly in some other situations requiring a copy of the exceptio... |
71,432,992 | 71,433,112 | C++ - Compile and link multiple files | I have a project with the following structure:
Item.cpp
Item.h
main.cpp
Makefile
The following source code is in the Item.h file:
class Item {
public:
Item();
~Item();
};
The following source code is in the Item.cpp file:
#include <iostream>
#include "Item.h"
Item::Item() {
std::cout << "Item... | I'm surely you ignored this warning :
warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]
#include "Item.h"
#include <iostream>
int main() {
std::cout << "Initialize program..." << std::endl;
Item item_1;
std::cout << "Hello world!" << std::endl;
return 0;
}
jus... |
71,432,993 | 71,434,511 | Why does delete[] work in one case but not another? | Could someone explain to me how delete[] works in the function below?
Specifically, arr = arrtemp; delete[] arrtemp; fails, but delete[] arr; arr = arrtemp works.
void AddElement(int *&arr, int &n, int pos, int val){
int *arrtemp = new int[n + 1];
for(int i = 0; i <= pos; i++){
*(arrtemp + i) = *(a... |
My thought was that I assign arr = arrtemp so that pointer arr now points to the added array, and I delete[] arrtemp should have no effect on arr,
Strictly speaking, this much is true. However, if you take this viewpoint, then strictly speaking, delete[] arrtemp should have no effect on arrtemp. Deleting the memory t... |
71,432,999 | 71,435,405 | nlohmann json parsing key and value to a class | I have the following data file
{
"France": {
"capital": "paris",
"highpoint": "20",
},
"Germany": {
"size": "20",
"population": "5000"
}
}
I am using nlohmann/json to parse it
I need to parse it into a country class
country.h
class Country {
public:
friend void to_json(json &j ,... | I think you need to customise to/from JSON for a vector of Country instead of the individual objects.
You need to parse the outer object in the JSON file and add the name to each of the objects before parsing the inner map values.
#include <map>
#include <string>
#include "nlohmann/json.hpp"
#include <sstream>
#include... |
71,433,130 | 71,433,344 | Why does template not discard the co_return? | I'd like to make a function with both sync and coroutine version, without using template specialization, i.e. with an if constexpr.
This is the function I wrote:
template <Async _a>
AsyncResult<int, _a> func(int a) {
if constexpr (_a == Async::Disable)
return a;
else
co_return a;
}
But when I instantiate t... | The standard explicitly says this is not possible. As per Note 1 in stmt.return.coroutine#1
... A coroutine shall not enclose a return statement ([stmt.return]).
[Note 1: For this determination, it is irrelevant whether the return statement is enclosed by a discarded statement ([stmt.if]). — end note]
So you won't be... |
71,433,398 | 71,434,040 | How to improve my custom unique_ptr class? I want to realize that derived class can cast to base class | I realize a unique_ptr class by myself as below, and use it to manage another class:
namespace mcj {
template <typename CallbackT>
class unique_ptr {
public:
unique_ptr(CallbackT* ptr = nullptr) : ptr_(ptr) {
std::cout << "unique_ptr normal constructor" << std::endl;
}
unique_ptr(unique_ptr<CallbackT>&& ptr... | foo<B> is not a subclass of foo<B> in c++. Google 'contravariance and covariance in c++ smart pointers',
You will have to extract the pointer cast it and create a new unique_ptr to return
|
71,434,180 | 71,434,322 | When object is a argument of function, why does function use copy constructor? | I'm studying about copy constructors now. I learned that copy constructor is called when we make a object with already made object. And I heard that When we use object as a argument in function, copy constructor is called.
I want to know what happens inside function. How can function knows that function have to use cop... |
I think inside function, the passed argument is assigned to function parameter
No. The arguments are essentially local variables of the called function, except they are created by the caller before the execution goes into the function. The function does not even know how they were constructed.
why does function use ... |
71,434,475 | 71,434,540 | How to use a concept for STL containers? | Based on this old stack overflow question How do you define a C++ concept for the standard library containers?
I see that it's possible to define a concept for STL containers. However, I am unsure how to actually apply the concept to anything, because it requires 2 containers, container a and container b.
For example, ... | The definition of this concept is in fact
template <class ContainerType>
concept Container = /* */;
which only constrains one type ContainerType, so the function that applies this concept would be
template <Container C>
void f(C& c);
|
71,434,630 | 71,436,706 | What does this mean in gdb after executing the last line of a function? | Line 31 is the last line in this C++ function. After stepping over it, this strange number 0x00007ffe1fc6b36b is printed, and it starts walking back up the function, going back to line 30. I imagine it is calling destructors now. I'm just curious what the strange number means.
31 _sock->bind(addr);
(gdb) n... | If the actual $pc value does not match the start of a line (according to the line table within the debug information), then GDB will print the $pc before printing the line number, and source line.
That's what's going on here. For line 31 GDB stopped at the exact address for the start of line 31, and so no address was ... |
71,434,795 | 71,434,866 | Integer literal as parameters of function declaration in cpp | I'm almost familiar with c and c++ programming. Today I was searching about function declaration when I suddenly came across a strange syntax in c++ language.
I wrote below code:
#include <iostream>
using namespace std;
int foo('3');
int bar(3);
int main(){
}
I've never seen defining the literals as function para... | It means int foo = '3'; and int bar = 3; respectively.
But it's not exactly equivalent, e.g. with classes = doesn't permit explicit constructors.
|
71,435,269 | 71,435,414 | why type name is not allowed? | I want that when passing a certain enumeration property, the corresponding operator with type checking is output, here is a simple code example
#include <iostream>
#include <typeinfo>
//#include <memory>
enum MessageType : uint16_t
{
Display,
Warning,
Error
};
#define MESSAGE(_MessageType, _Text)\
if(... | std::type_info::name returns a c-string. MessageType is not a string, its the name of a type. You can compare the string returned from typeid(_MessageType).name() to the string returned from typeid(MessageType).name().
However, identifiers starting with leading _ followed by capital letter are reseved. If you use them ... |
71,435,595 | 71,436,077 | C++: average of vector of structs | My struct is a 2D coordinate:
template<typename T>
struct coordinate {
std::pair<T, T> coords;
coordinate() : coords({0, 0}) {}
const T x() const { return coords.first; }
const T y() const { return coords.second; }
// functions to set and manipulate x and y
};
I have a std::vector<coordinate<doub... | Like I said, if you want to do arithmetic operations on your type, you likely want to overload the operators. Thus you can do
#include <numeric>
#include <vector>
template<typename T>
struct coordinate {
std::pair<T, T> coords;
coordinate() : coords({0, 0}) {}
coordinate(T x,T y) : coords(x,y) {}
T x()... |
71,436,069 | 71,443,720 | Writing and reading ADTF3 Files | I am using ADTF Libraries to write a structure data. I need to verify whether the data is being written properly. How can i do this?
|
I am assuming you are writing structured data to a .dat/.adtfdat file. In that case, you can always convert a .dat/.adtfdat file into a csv to verify. See examples on how to do so.
If you have access to MATLAB, then the easiest way would be using a simple function in MATLAB : adtffilereader
Alternatively, there are ... |
71,436,279 | 71,436,395 | convert uint_8 ascii to string | I am sending a string from RaspberryPi to ESP32 via BT.I am getting an ascii values one per line. How to convert it into a whole one String? I tried as follow but I get an error while running the method printReceivedMEssage(buffer):
invalid conversion from 'uint8_t {aka unsigned char}' to 'uint8_t* {aka unsigned char*}... | One error that should be fixed is the incorrect sizeof(). The code is getting the size of a pointer, which in C and C++ does simply that (you will get the value 4 for 32-bit pointers for example), but doesn't return the size of any "contents" being pointed to. In your case, where the buffer contains a null-terminated... |
71,436,332 | 71,441,824 | Converting from std::chrono:: to 32 bit seconds and nanoseconds? | This could be the inverse of Converting from struct timespec to std::chrono::?
I am getting my time as
const std::Chrono::CRealTimeClock::time_point RealTimeClockTime = std::Chrono::CRealTimeClock::now();
and I have to convert it to a struct timespec.
Actually, I don't, if there is an altrerntive; what I have to do is... | I'm going to ignore std::Chrono::CRealTimeClock::now() and just pretend you wrote std::chrono::system_clock::now(). Hopefully that will give you the tools to deal with whatever clock you actually have.
Assume:
#include <cstdint>
struct my_timespec
{
std::uint32_t tv_sec; // Seconds - >= 0
std::uint32_t tv_ns... |
71,436,670 | 71,436,903 | I want to get the encoded string as output . But not able to | Input:
101101110
1101
Expected Ouput:
000000000011
My output:
It just keeps on taking the input.and not showing any output.
Please help me . what is wrong with my code. Any help would be aprreciated.I have given the names of the variables such that its easy to understand.This code is only for the senders side.
#incl... | Look at these lines properly:
if (encoded[i + j] == polynomial[j]) {
encoded[i + j] == '0'; // Line 1
}
else {
encoded[i + j] == '1'; // Line 2
}
See? You are using == while you should be using =. == is a comparison operator which returns a boolean (true/false). It does not assign values. So to fix your proble... |
71,436,877 | 71,437,040 | Perfect forwarding c++ | Is this correct way to use std::forward?
struct Command {
public:
int32_t uniqueID{0};
public:
Command() = default;
template<typename T>
Command(T&& _uniqueID) : uniqueID(std::forward<int32_t>(_uniqueID)) //
{
//
}
};
Or I should use this line?
Command(T&& _uniqueID) : uniqueID(std::forward<T>(_uni... |
Is this correct way to use std::forward?
No, there's no point to use std::forward here. Moving a primitive type is same as copying it. I recommend following:
Command(std::int32_t _uniqueID) : uniqueID(_uniqueID) {}
Or alternatively, let the class be an aggregate:
struct Command {
std::int32_t uniqueID{0};
};
|
71,437,288 | 71,441,827 | Why GetDeviceToAbsoluteTrackingPose(...) doesn't return the HMD position in OpenVR? | I'm trying to implement a basic OpenVR C++ app. This is my code:
#include <iostream>
#include <thread>
#include <chrono>
#include <openvr.h>
int main()
{
vr::EVRInitError eError = vr::VRInitError_None;
vr::IVRSystem * pvr = vr::VR_Init(&eError, vr::VRApplication_Utility);
std::cout << "Error code: " << ... | Okay, I've found the solution.
pvr->GetDeviceToAbsoluteTrackingPose(vr::TrackingUniverseStanding, 0, &trackedDevicePose, 1);
The last parameter should be 1 (in my case). It's an array count parameter, not the device ID.
|
71,437,422 | 71,440,328 | ambiguity of overloaded function taking constant Eigen argument | I've designed a class with two overloaded functions taking Eigen data structures of different sizes.
The code compiles as long as I'm passing lvalues but if I pass an rvalue I get a compiler error ambiguity because both return the same ConstantReturnType.
Here is a MWE:
#include <iostream>
#include <Eigen/Geometry>
us... | Your example does not work because the return type of Zero() is not a matrix, but an Eigen expression.
Thus, one way of achieving what you want with minimal changes is to use explicit matrix evaluation:
moa.ambiguousOverload(Eigen::Vector4d::Zero().eval());
You may also want to consider writing functions taking Eigen ... |
71,437,485 | 71,437,826 | Detect if a vector is a palindrome in C++ | I set myself a challenge of trying to make a program that detects if a given vector is a palindrome. Here is the code:
#include <iostream>
#include <vector>
bool isPalindromeArray(std::vector<int>& nums) {
float size = nums.size()/2;
int k = 0;
if(size = int(size)) {
for(int i = 0; i < size; i++) ... | It is highly recommended if you learn how to use algorithms delivered by standard library:
template <typename T>
bool is_palindrome(const T& container)
{
return std::equal(std::begin(container),
std::begin(container) + std::size(container) / 2,
std::rbegin(container));
}
Live test
|
71,437,697 | 71,437,812 | CMake MSBUILD : error MSB1009: Project file does not exist | I need to build my CMake based project under MSVC 2013 and MSVC 2019.
With MSVC 2019 using Ninja generator I build it successfully with following commands:
cmake -S . -B build -GNinja "-DCMAKE_BUILD_TYPE:STRING=Release"
cmake --build build --target all
On MSVC 2013 I have no Ninja available, so I tried the following:
... | In contrast to other generators (like Makefiles or Ninja) CMake does not generate an all target for Visual Studio solution but an ALL_BUILD target.
So cmake --build build --target ALL_BUILD --config Release should succeed.
|
71,439,116 | 71,439,309 | array class member, with dynamically changeable length during runtime | I am trying to make a network application. Its class blueprint is roughly like this-
class Node
{
public:
// member functions
private:
int nodeID;
// other members
};
class NodeNetwork
{
public:
// member functions
private:
Node nodeArray[MAX_NODES];
// other members
};
Here, t... | You can use dynamically array allocation for this purpose:
int* arr = new int[5];
..and anytime you wish to change the number of elements:
int size = 5;
int* arr = new int[size] {};
int* new_arr = new int[size + 1];
for (int i = 0; i < size; i++)
{
new_arr[i] = arr[i];
}
delete[] arr;
arr = new_arr;
// Now arr h... |
71,440,067 | 71,443,339 | Python ctypes argtypes for class object pointer | I have this C++ code to integrate my class Foo based code into python.
class Foo{
public:
Foo(){};
int do_thing(int arg){ return arg*2; }
};
extern "C" {
Foo* get_foo_obj(){
return new Foo;
}
int do_thing(Foo* ptr, int arg){
return ptr->do_thing(arg);
}
}
Now I want to assign argtypes and restype for... | ctypes.c_void_p works (void* in C), although you can be more type safe with an opaque pointer type like:
import ctypes as ct
class Foo(ct.Structure):
pass
lib = ct.CDLL('mylib.so')
lib.get_foo_obj.argtypes = ()
lib.get_foo_obj.restype = ct.POINTER(Foo)
lib.do_thing.argtypes = ct.POINTER(Foo), ct.c_int
lib.do_thin... |
71,440,305 | 71,440,417 | free(): double free detected in tcache 2, in linked List deletion of a node in c++ and how destructor is working in this code | class Node{
public:
int data;
Node* next;
Node(int d){
data = d;
next = NULL;
}
~Node(){
delete next;
}
};
class List{
public:
Node* head;
Node* tail;
List(){
head ... | ~Node(){ delete next; } makes it hard to delete a single node from that list. It'll delete all nodes after it too.
I suggest that the individual Nodes do not delete following Nodes:
class Node {
public:
int data;
Node* next;
Node(int d) : // colon starts the member initializer list
data(d), next(nu... |
71,440,327 | 71,441,763 | Align struct while minimizing cache line waste | There are many great threads on how to align structs to the cache line (e.g., Aligning to cache line and knowing the cache line size).
Imagine you have a system with 256B cache line size, and a struct of size 17B (e.g., a tightly packed struct with two uint64_t and one uint8_t). If you align the struct to cache line si... | To address (2), it is unclear whether the extra overhead of using packed structs (e.g., unaligned 64-bit accesses) and the extra math to access array elements will be worth it. But if you want to try it, you can create a new struct to pack your struct elements appropriately, then create a small wrapper class to access... |
71,440,372 | 71,440,769 | lifetime of a temporary object when passed as an argument to std::move | Can somebody explain how the lifetime of a temporary object gets affected when (and not) is passed as an argument to std::move. In the below code I'm creating r-value references using with and without std::move. And to my surprise I didn't get expected results.
#include <iostream>
class A {
public:
A() {
s... | The lifetime extension of temporary objects does not work when you pass that temporary through a function. When you do
A&& a_ref = std::move(A());
The rvalue reference that A() binds to is not a_ref but instead the parameter of move. That parameter is destroyed when the fucntion ends, which means the temporary it is... |
71,440,526 | 71,441,989 | Plotting multiple dataset in same gnuplot window | I have two data set (x,y1) and (x,y2) which I got from the result of computation and wrote those files in "data1.tmp" & "data2.tmp". I want to use this two data set to plot in Gnuplot.
#include <iostream>
#include <cstdlib>
int main()
{
FILE* gnupipe1, *gnupipe2;
const char* GnuCommands1[] = {"set title \... | You are opening two different gnuplots, you don't need to do that.
#include <iostream>
#include <cstdlib>
int main()
{
FILE* gnupipe1;
const char* GnuCommands1[] = {"set title \"v vs x\"",
"plot \'data1.tmp\' with lines, \'data2.tmp\' with lines"};
gnupipe1 = _popen("gnuplot -persist... |
71,440,707 | 71,440,918 | How to find the Final Path from the Traversal Path while performing BFS/DFS algorithm | I am trying to solve a problem which apples a Breadth-First Search Algorithm as well as Depth-First Search algorithm on a Tree and finds out the traversal and final paths that are found by both these algorithms.
What I am actually confused with is how do I calculate these two different paths? And are they really differ... | One [out of many possible] approach is to maintain a map of target to source node. Every time you advance, record which source node was made to make that advance. So, in BFS case it will look like:
parents = {
'A': NULL,
'B': 'A',
'C': 'A',
'D': 'B',
'E': 'B',
'F': 'C',
'G': 'C'
}
Then, from the final n... |
71,441,047 | 71,441,228 | I was trying to convert String into ASCII value using Recursive function. By using the string only as parameter | This is my code (I want to use string as the parameter only):
#include <iostream>
using namespace std;
int i = 0; //to take string character by character
void parseToInteger (string s1)
{
char convert;
string another;
if (convert == s1.length()) //at null character function terminates
{
... | Your if (convert == s1.length()) is very strange. That expression is comparing an uninitialized char variable to the length of the s1 string (which will be of size_t type). What you should be doing is comparing the i variable to the length (and that i would be better defined as size_t type).
Also the static_cast <int> ... |
71,441,341 | 71,441,886 | Overloading insertion operator for std::array | I'm trying to overload the insertion (<<) operator to output elements of an std::array. The following yields a compilation error:
// overload operator<< to display array objects of any type T and size N
template<typename T, int N>
std::ostream &operator<<(std::ostream &Output, const std::array<T,N> &Arr) {
for (con... | The 2nd template argument of std::array is a size_t, not an int.
Also, return output; needs to be return Output; as C++ is case-sensitive.
// overload operator<< to display array objects of any type T and size N
template<typename T, size_t N>
std::ostream &operator<<(std::ostream &Output, const std::array<T,N> &Arr) {... |
71,441,443 | 71,441,512 | can I add optional types parameters in C++ | the title says it all.
I have this function that couts the parameter:
void outlog(string par) {
std::cout << par;
}
but Par can only be a string. how can I make its type optional.
| C++ (and many other languages) makes it available to have generic functions. Here you can read more about it: Generics in C++ Here is the sample code for your function. Note: the object should be printable (if it is a class object, it should have the << operator overloaded):
template <typename T>
void outlog(T& input){... |
71,441,900 | 71,446,441 | How to unit test bit manipulation logic | I have a method which converts RGBA to BGRA. Below is the method
unsigned int ConvertRGBAToBGRA(unsigned int v) {
unsigned char r = (v)& 0xFF;
unsigned char g = (v >> 8) & 0xFF;
unsigned char b = (v >> 16) & 0xFF;
unsigned char a = (v >> 24) & 0xFF;
return (a << 24) | (r << 16) | (g << 8) | b;
};
H... | Inspired by @Yves Daoust's comment, why can't you just write a series of checks like below? You can use the nice formatting of C++14:
unsigned int ConvertRGBAToBGRA(unsigned int v) {
unsigned char r = (v)&0xFF;
unsigned char g = (v >> 8) & 0xFF;
unsigned char b = (v >> 16) & 0xFF;
unsigned char a = (v >> 24) & ... |
71,442,134 | 71,442,466 | Can you Avoid Multiple Operator Overloads for Mathematical Operators? | Say I have a very simple Rational class like the one below:
class Rational
{
int numer;
int denom;
public:
Rational(const int& numer, const int& denom) : numer(numer), denom(denom) {}
void operator*(const Rational& other) { std::cout << "multiply, simple as\n"; }
}
All well and good. Then say that I... | The issue with having a single function is that the type of the left and right operands to * would vary (and you would have to use them differently).
This can be solved by fixing both of the argument types to Rational and creating an implicit conversion from an int x to Rational x/1 (which is probably desirable anyways... |
71,442,143 | 71,442,325 | Overloading and LinkedList | I was trying to overload cout operator to print a class.
The class consists of an integer value and a pointer. So I was hoping to print an integer value and a memory address, but I got an error. I got confused since the class itself already has a pointer and couldn't figure out the problem.
The compiler gives "expected... | First, generally we need to add a friend declaration for the overloaded operator<< so that the be-friended function can access the private fields of the class type as shown below. But since both the data members of your class type are public you can skip the friend declaration.
Second, Node.value should be replaced by ... |
71,442,472 | 71,444,732 | C++ : Throw Away threads vs Thread Pool | So I have a main application thread in my opengl application with all rendering and stuff. Now i need some really heavy calculation which takes about 2 3 seconds so I moved it to a seperate thread here is how I manage it:
std::atomic<bool> working = false;
void work(){
if(!working)
{
working = tru... | You could use std::launch as some people have suggested. Or you could do a google for "c++ thread pool library" and probably find something waiting for you.
But the reality is simple: writing a thread pool is close to trivial and is a good exercise. So you could write your own and learn something. As has been suggested... |
71,442,515 | 71,442,749 | Inheritance and random number generation in const member function | I have the following class inheritance structure
#include <random>
class ABC{
protected:
std::mt19937_64 rng;
double a();//calls random correction
virtual double random_correction() const=0;
public:
double x;
explicit ABC(const double x0) :
rng(std::random_device{}()), x(x0){}
ABC(const ... | Generating random number doesn't change the state of u. It's state is just what range of values to be generated.
But it does change the state of rng. Pseudo-random number generators are usually deterministic meaning that rng() is determined by the current state and the state will change upon evaluation so next time a d... |
71,443,639 | 71,443,830 | Issue with std::wstring when calling from c# with DllImport | I was going to call an unmanaged function in a c++ library from c#, but it crashed. While troubleshooting I narrowed it down to std::wstring. A minimal example looks like this:
C++
#include <iostream>
extern "C" __declspec(dllexport) int __cdecl Start()
{
std::wstring test = std::wstring(L"Hello World");
retu... | This is something I noticed:
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
Exporting functions from an EXE instead of a DLL isn't standard. (I think it can be done, but I wouldn't recommend it.)
Build your C++ code as a DLL instead of an EXE. Statically link the DLL with the C++ runtime libraries... |
71,443,997 | 71,444,773 | Creation of a driving simulator : how to rotate the circuit around the origin? | I have a circuit in my driving simulator in cpp and I want to know how to rotate the circuit around the origin, I tried to dig into some trigonometry because i know this is what will help me but I'm at a point where I'm stuck.
For your information, the circuit is stored inside a vector of pair (std::vector<pair<double,... | you just get to apply a 2d rotation matrix (https://en.wikipedia.org/wiki/Rotation_matrix). This should work, you just get to iterate at each point:
#include <math.h>
void rotate(float &x,float &y,float teta)
{
float newX = x*cos(teta)+y*sin(teta);
float newY = x*sin(teta)-y*cos(teta);
x = newX;
y =... |
71,444,098 | 71,444,301 | Automatic generation of a brace-enclosed initializer list in C++ using language features (NOT pre-processor directives) | I'm looking for a solution using only native C++ language features (up to C++17) for accomplishing the following:
std::array<Type, unsigned int Elem> array_{Type(), // 1 - Call constructor on Type()
Type(), // 2 - ...
... , //... | Like this:
#include <array>
#include <memory>
#include <utility>
template <std::size_t ...I>
std::array<std::shared_ptr<int>, sizeof...(I)> foo(std::index_sequence<I...>)
{
return {(void(I), std::make_shared<int>())...};
}
std::array<std::shared_ptr<int>, 4> array_ = foo(std::make_index_sequence<4>());
Guarantee... |
71,444,249 | 71,444,560 | calculation of the midpoint of the coordinate values entered by the user. (x, y, z axes) Need class topic | I have an assignment, here is the description:
Create a class named Point. It must have three private float field named as x, y, z to keep coordinates in space and public get and set functions to access these data members ( getX(), getY(), getZ(), setX(), setY(), setZ() ). Create another function that is defined outsi... | As the instructions says:
In Space function, you will find the middle point between two points and create a new Point object that will keep calculated coordinates.
Per Mid Point Formula in 3D:
A midpoint is the exact center point between two defined points. To find this center point, midpoint formula is applied. In ... |
71,444,527 | 71,445,271 | Find base period of sequence in C++ |
For a sequence of numbers a1, a2,...,an, we say that there is a period if 1≤p<n and if it holds that it is ai=ai+p for all values for which this equality makes sense.
For example, the sequence of numbers 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 has period 5, because ai=ai+5 for all values such that both indices i and i+5 ar... | For starters it is unclear why you are using a vector with the value type double instead of the type int when all initializers have the type int.
The function period should accept a vector by constant reference.
The variable p is not initialized. As a result the function can return an indeterminate value.
The range ba... |
71,444,896 | 71,444,957 | Having a member variable only conditionally present using requires clause | I wish to make the existence of member within dat dependent on B (or some other concept).
template <bool B>
struct dat {
void member_func() requires (B) {} //ok
std::byte member requires (B); //err
};
I know this is possible to do with specialisation but as far as I am aware that would get very ugly if multipl... | There's a couple approaches to this (see Conditional Members).
One is you use the condition to change the type of member:
struct E { };
[[no_unique_address]] std::conditional_t<B, std::byte, E> member;
This isn't really a conditional member variable, member is always present. But it's sometimes the type you care about... |
71,445,161 | 71,445,207 | clang standard library bug or c++ undefined behavior? | Does the following C++ program contain any undefined behavior?
int
main()
{
struct entry
{
uint32_t hash;
uint32_t idx;
};
entry arr[31] = {
{ 7978558, 0}, { 9241630, 1}, { 65706826, 2},
{ 639636154, 3}, {1033996244, 4}, {... | Yes, the comparator is not a strict weak ordering which violates the preconditions of std::sort, resulting in undefined behavior.
For two arguments a and b (possibly identical), a strict weak ordering comp should never evaluate both comp(a,b) and comp(b,a) to true. In other words, it should model the behavior of the bu... |
71,445,233 | 71,445,712 | Properly initialise a struct in C++, specifically addrinfo | I am wondering how I can properly initialise a struct in a "C++-way".
I am filling an addrinfo-structure with the relevant information for my hints (to use in getaddrinfo()).
Depending on how I initilise the struct, I will later on be able to get said addrinfo and let the network thing do its networky thing or fail wit... | In C++ the initialization stacks. A class member and all base classes are initialized before the program enters the body of the constructor and will call the appropriate constructors to do so. Everything afterward, including inside the constructor's body, is assignment. To initialize a member you need to use either a d... |
71,445,432 | 71,478,695 | Why can compiler not optimize out unused static std::string? | If I compile this code with GCC or Clang and enable -O2 optimizations, I still get some global object initialization. Is it even possible for any code to reach these variables?
#include <string>
static const std::string s = "";
int main() { return 0; }
Compiler output:
main:
xor eax, eax
ret
_GLOB... | Compiling that code with short string optimization (SSO) may be an equivalent of taking address of std::string's member variable. Constructor have to analyze string length at compile time and choose if it can fit into internal storage of std::string object or it have to allocate memory dynamically but then find that it... |
71,445,466 | 71,445,602 | Simpler, portable way to iterate over all char values? | For a class I'm teaching I needed to write a piece of code to iterate over all possible char values. I wanted to do this in a way that was portable across different C++ implementations. This meant that
I can't assume char is signed or unsigned,
I can't assume char is eight bits,
I can't assume that sizeof(int) > 1,
I ... |
but perhaps there's a fundamentally different approach available that more closely resembles a traditional for loop.
Well, you can use an actual for loop:
#include <limits>
#include <iostream>
void process(char ch)
{
std::cout << static_cast<long>(ch) << ' ';
}
int main()
{
for ( char ch = std::numeric_limits<c... |
71,445,682 | 71,445,909 | How can I add function to vector in this case? | I have this case, I can't figure it out.
I want to add a function in a vector of functions from an object to his child like this:
Child:
std::vector<void (*)(STATE oldState, STATE newState)> stateChangeHandlers;
void Digital_Output::addOnStateChangeHandler(void (*function)(STATE oldState, STATE newState)) {
this->... | Your vector holds C-style function pointers. However, a capturing lambda cannot be converted to a function pointer (which is what the error message is trying to tell you), only a non-capturing lambda can. To store capturing lambdas, you will have to use std::function instead.
Also, your lambda returns a void*, but you... |
71,445,684 | 71,452,950 | Copy one vector to another in for loop c++ | I need to implement a simple version of schedule for monthly tasks. For example payment of electricity bills, subscription fees for communications, etc. I want to implement a set of the following operations:
ADD(i,s) - assign a case with name s to day i of the current month.
DUMP(i) - Display all tasks scheduled for d... | What you need is a set of vectors for each month. Either another vector if you want to number the months 0 - 11, or maybe a map of month name to vector. Lets go with the former
Also too many nested vector is hard to read. Lets define some types.
typedef vector<string> day; // the tasks for a day
typedef vector<day> mo... |
71,445,747 | 71,445,772 | Check if number is period of sequence in C++ | I need to check if number is a period of sequence.
EXAMPLE: { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 }
Periods are 5 and 10. Base period is 5 because it is the smallest period.
#include <iostream>
#include <vector>
int p=0;
int period(std::vector<double>v , int x)
{
int p = 0;
for (int i = 1; !p && i < v.size(); i+... | The function can be defined the following way
bool period( const std::vector<double> &v , size_t n )
{
bool is_period = false;
if ( n < v.size() )
{
size_t j = 0;
while ( j < v.size() - n && v[j] == v[j + n]) ++j;
is_period = j + n == v.size();
}
return is_period;
}
Here i... |
71,445,766 | 71,445,840 | How to properly call getInsertData and getDeleteData in main? Am I doing this part correct? | I am working on a linked list assignment, however I am having trouble figuring out how to properly call getInsertData() (get values from cin and put them in a list) and getDeleteData() (delete numbers in the list) in main().
The instructions say something about defining an instance variable of NumberList, which I have... | You are declaring a variable named NumberList of type int. You need to instead declare a variable of type NumberList.
Try something more like this:
int main() {
NumberList myList;
cout << "Displaying list after inserting numbers" << endl;
getInsertData(cin, &myList);
cout << "Displaying list after dele... |
71,446,211 | 71,447,231 | Why there are so many duplicates while loading vector | I need to load vector with infinite loop and to print it. Loading is over when 0 entered.
OUTPUT:
Enter numbers: 1 3 1 4 2 1 3 1 4 2 1 3 0
1 3 1 4 2 1 3 1 4 2 1 3
Code:
#include <iostream>
#include <vector>
int main()
{
std::vector<double>vektor;
double a;
for(;;)
{
std::cout << "Enter numbers: "... |
Could you explain me why there are so many duplicates of string "Enter numbers: "?
Because you are outputting Enter numbers on every loop iteration before reading a new number. Simply move that statement above the loop instead.
Also, your loop can be simplified. You are ignoring the error state of the stream after ea... |
71,446,686 | 71,986,985 | how to properly link mingw libraries using cmake and vcpkg? | I've getting used to simple cmake codes like this
cmake_minimum_required(VERSION 3.20)
project(trial VERSION 0.1.0)
set(CMAKE_CXX_STANDARD 20)
find_package(fmt CONFIG REQUIRED)
add_executable(trial main.cpp)
target_link_libraries(trial PRIVATE fmt::fmt)
however, it doesn't work on Mingw, the errors are something l... | I am rather late, but here it in case it helps:
Specifying library locations by hand shouldn't be required, the problem is somewhere else.
This error is at build time so it seems that it is passed cmake configuration without errors. Can you post the cmake conf log? perhaps if you tried specifying both --triplet= and --... |
71,446,914 | 71,446,946 | Vector of a class resetting member variables after for loop | I have an assignment where we need to use this basic structure of vectors and classes to learn about parent and child classes and polymorphism. Here is the code of the function I'm supposed to write:
void assignStudents(vector<Student*>& v) {
for (int i = 0; i < 5; i++)
{
cout << "Enter a study level: "... | I'll just focus on one part, as the same issue appears twice in your code.
{
Graduate inputClass; // create local student "on the stack"
Student* inputParentClassPtr = &inputClass;
v.push_back(inputParentClassPtr); // store address of student
v[i]->addToVector(input);
inputParentClassPtr = nullptr; ... |
71,447,012 | 71,451,246 | How to determine when a socket receives EOF? (C++20 boost asio coroutines) | Consider a simple echo server:
#include <boost/asio.hpp>
#include <boost/asio/experimental/as_tuple.hpp>
#include <iostream>
#include <vector>
using boost::asio::awaitable;
using boost::asio::buffer;
using boost::asio::co_spawn;
using boost::asio::io_context;
using boost::asio::detached;
namespace ip = boost::asio::ip... | You can catch the exception:
for (;;) {
try {
auto n = co_await s.async_read_some(
buffer(data_buf, data_buf.size()), use_awaitable);
auto ep = s.remote_endpoint();
std::cout << "R from " << ep.address().to_string() << " "
<< ep.port() << " L=" << n << std::endl... |
71,447,337 | 71,447,540 | Find sum of bits of a char | I need a queue of size about 8 booleans. Every push should destroy an item from the tail. This can be achieved by a char in the resource limited application.
However I only care about the sum of those "flags", not their individual status. How can I find the sum of the set bits of an 8 bit char?
| I come up with two methods.
A method is using a varible to count the sum, whenever you push, you maintain the varible, the change of the varible depends on what you push and what will pop.
Another method is an algorithm called "lowbit"
int lowbit(int x) {
return x & -x;
}
it will return the last 1 int the binary r... |
71,447,402 | 71,447,428 | Unable to access helper functions not in the namespace: undeclared identifier | I currently have a namespace set up like this:
SomeClass.h
namespace somenamespace {
class SomeClass {
public:
foo();
}
}
SomeClass.cpp
namespace somenamespace {
SomeClass::foo() {
somehelperfunction();
}
}
void somehelperfunction() {
std::cout << "hejflsdjf\n";
}
Wit... | Functions must be declared before called.
|
71,447,915 | 71,448,255 | Calculating Integrals | I am trying to calculate a integral in C++ and i am trying to use Simpson's 3/8 Rule (Also known as Simpson's second Rule) to calculate it. I wrote a program but it gives the wrong result. When i used the same rule on paper it works. I don't know what's wrong.
simpsons.cpp :
#include <iostream>
double f(int x) {
ret... | Final version of code (simpsons.cpp) :
#include <iostream>
double f(double x) {
return 3*(x*x)+2*x+5;
}
float integralf(double lower_end, double high_end) {
double a = lower_end;
double b = high_end;
double h = (b - a)/3;
double area = 0.0;
area = ((3*h)/8)*(f(a) + 3*f((2*a+b)/3) + 3*f((a+2*b)/3) + f(b));... |
71,447,954 | 71,449,539 | C++ where intermediate value store? | My question can be pointed out regarding any programming language, but I wanna know regarding C++. I want to know where the intermediate value will store in C++? For example in the below code:
int func1(int);
int func2(int);
int func3(int);
int main(){
int a = 10;
int b = func1(func2(func3(a)));
cout<<b<<en... | Since you only declared the function I will assume they are in separate compilation units. So the compiler has to generate a function call for them. No inlineing or specialization of the functions possible (lookup link time optimization for how that isn't always true).
The way functions are called, arguments are passed... |
71,448,113 | 71,448,170 | OpenMp warning: ignoring #pragma opm parallel | I am getting this warning After I enter "g++ test1.c -fopenmp -Wall" with OpenMP directives on Windows:
wtest1.c:6: warning: ignoring #pragma opm parallel [-Wunknown-pragmas] #pragma opm parallel for private(x)
OpenMp doesn't seem to beworking. Waht should I do?
| It's #pragmaomp, not #pragmaopm
|
71,448,160 | 71,448,225 | ERROR: Cannot use parentheses when declaring variable with deduced class template specialization type | Good afternoon! Can someone explain why an error occurs when using a function where only one vector is passed?
Well, that is, there you can transfer constants without pain: 3, "asdf" 2.3, etc., but named variables are not. But for some reason a crossbreed is possible. Why is this suddenly possible?
#include <iostream>
... | clang's error message is oddly specific – g++ and vc++ only complain about conflicting declarations of v– but note that it says "declaring a variable".
Since func is a type, and you can have parentheses around the identifier in a variable declaration, and because of the "if it can be interpreted as a declaration, it is... |
71,448,227 | 71,455,218 | boost::asio::ssl::context crash during construction | I can't figure why the following instruction crashes:
boost::asio::ssl::context ctx(boost::asio::ssl::context::tlsv12);
I got the following error: Process returned -1073741819 (0xC0000005)
There is nothing more to catch regarding exceptions and AFAIK the boost documentation doesn't mention incompatibility issues betw... | The openssl cygwin package I installed is not a stable one, so the include and lib files are missing and I'm using the wrong ones (incompatible with the x86_64-w64-mingw32-g++ compiler). I've installed another stable version and the desired files are available now.
|
71,448,594 | 71,449,660 | What is causing the threads to execute slower than the serial case? | I have a simple function which computes the sum of "n" numbers.
I am attempting to use threads to implement the sum in parallel. The code is as follows,
void Add(double &sum, const int startIndex, const int endIndex)
{
sum = 0.0;
for (int i = startIndex; i < endIndex; i++)
{
sum = sum + 0.1;
} ... | The problem here is hardware.
You probably know that CPUs have caches to speed up operations. These caches are many times faster then memory but they work in units called cachelines. Probably 64 byte on your system. Your 2 doubles are each 8 byte large and near certainly will end up being in the same 64 byte region on ... |
71,448,813 | 71,448,814 | How can I override the C++ compiler CMake uses for CUDA? | I'm using a CUDA version which does not support the GCC version installed on my system (my GCC is too new). I'm trying to build a repository which uses CMake for build configuration.
I know how to override the C++ compiler, traditionally:
export CXX=/path/to/other/compiler-binary
and CMake picks this up. I can also us... | CMake will not (for now) default to using your CMAKE_CXX_COMPILER as the C++ compiler for CUDA host-side code; there's a different setting for that. Run your build configuration like so:
cmake -DCMAKE_CUDA_HOST_COMPILER=/usr/bin/g++-9
(replace the path with to your chosen C++ compiler of course)
|
71,448,963 | 71,449,259 | Why can't I put an Object into the start of a vector C++ | I'm writing a program in which I have to read complex numbers from the console into a vector, containing Complex objects. I have overwritten the >> operator in order to do this, but my vector gets indexed in the in the interval [1..vector.size()] instead of [0..vector.size()). I want it to go from zero, but I can't fig... | The problem is that you're reading the first number with cin >> num_of_complex;, but this does not move the cursor to a new line! This means that the next call (i.e. the first call to your overridden >>) with getline will read only an empty line and try to convert nothing into a complex number.
You can fix this by igno... |
71,449,293 | 71,449,425 | Which one is faster? raw pointers vs thrust vectors | I am a beginner in Cuda, and I just wanted to ask a simple question that I could not find any clear answer for.
I know that we can define our array in Device memory using a raw pointer:
int *raw_ptr;
cudaMalloc((void **) &raw_ptr, N * sizeof(int));
And, we can also use Thrust to define a vector and push_back our items... | The data in thrust::device_vector is ordinary global memory, there is no difference in access speed.
Note however that the two alternatives you present are not equivalent. cudaMalloc returns uninitialized memory. Memory in thrust::device_vector will be initialized. After allocation it launches a kernel for the initiali... |
71,449,580 | 71,449,783 | Return type is a template of templates | I have the following class:
class Inject{
template<template <class> class Daemon>
RETURNTYPE register_inj();
}
There are a number of implementation to this template function where the template arguments are explicitly specified one example is returning a class ServiceA which has one template argume... | I believe this question mixes two separate things.
The number of template arguments of the function template argument Daemon has nothing to with the return type. In fact, your specialisation for ServiceA indicates that you are not even asking for a template template argument. ServiceA<CacheA> is not a template - it is... |
71,449,644 | 71,449,668 | Java equivalent of memcpy'ing a char[] to short | In Java or Kotlin, what would be the equivalent of this C++ code:
char* data = new char[size];
//read file to this array
short version = 0;
memcpy(&version, data, 2);
I tried this:
//java equivalent of the kotlin code below
Integer.parseInt(String(Arrays.copyOfRange(data, 0, 2)))
//kotlin:
data.copyOfRange(0, 2).c... | Try using ByteBuffer:
byte[] data = new byte[size];
ByteBuffer buffer = ByteBuffer.wrap(data);
short version = buffer.getShort();
If needed you can also change the byte order
|
71,451,712 | 71,452,148 | Different behaviour in C++ std::vector construction with gcc and clang | In the example below I am expecting v to have 1 element, whos var will be of type Vector and will contain two "int" Variants 10 and 20.
This is the behaviour I can see with gcc.
With clang, 'v' contains two elements which are the two "int" Variants 10 and 20.
I think gcc's vector is created via the initializer_list con... | This is CWG 2137, which only gcc implements at present.
Clang bug: https://github.com/llvm/llvm-project/issues/24186
See also C++ constructor taking an std::initializer_list of size one - this is slightly more complicated in that the initializer list element is constructible from its argument (of the type being initial... |
71,451,719 | 71,451,820 | How can you generate a JSON compilation database using the CLI? | As described here one can generate a JSON compilation database using the UI of Visual Studio. Is it possible to do this in the CLI?
(The use case for this is to use the database with clangd to provide autocompletion to another editor)
| Apparently there is a powershell script that can be used like this:
clang-build -export-jsondb
If this generates a compile_commands.json file in the current directory of the projects in current directory.
|
71,451,996 | 71,452,190 | Why do I get "functions that differ only by return type cant't be overloaded" error when nothing is really overloaded? | I have following example of c++ code in visual studio 2022:
#include<iostream>
#include<string>
employee get_employee() {
employee out = { 1, "John"};
return out;
}
class employee {
public:
int id;
std::string name;
};
int main() {
std::cout << get_employee().name;
return 0;
}
But when I run... | The problem here is fairly simple. You're trying to use employee before you've defined what it means. Move your definition of employee before the definition of get_employee.
#include<iostream>
#include<string>
class employee {
public:
int id;
std::string name;
};
employee get_employee() {
employee out = {... |
71,452,118 | 71,474,093 | Bazel: Tests cannot see library headers but app can | I have a pretty simple C++ project with Bazel that I am trying to implement gtest in and it has 3 BUILD files when including the test one. The problem I am having is that my headers in my library are visible to the app directory but not the test one and when I try to build my simple test it fails.
My project structure ... | Instead of copts = ["-Ilib"], use includes = ["."] on the cc_library. That tells Bazel that anything which depends on that cc_library should get that directory on the include path, regardless of the relative path to get there.
Specifically, remove all the copts = ["-Ilib"], and change lib/BUILD to this:
load("@rules_cc... |
71,452,848 | 71,452,874 | Error while trying to use a member class in a vector | I'm creating a container with files and directories, file and directory are a derived class from a parent class called resource, my problem appears while trying to use a member function of the directory class, find() searches for a name in the contents of a directory, this contents can either be file or directory find(... | Just remove (*ip)-> from qq = (*ip)->find(*ip->name());. find is not a member function.
qq = find((*ip)->name());
Perhaps the flags should be passed to the call
qq = find((*ip)->name(), ff);
|
71,453,109 | 71,453,186 | Is this Union Find really O(n) as they claim? | I am solving a problem on LeetCode:
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. So for nums = [100,4,200,1,3,2], the output is 4.
The Union Find solution to solve this is as below:
class Solution {
publ... | They are right. A properly implemented Union Find with path compression and union by rank has linear run time complexity as a whole, while any individual operation has an amortized constant run time complexity. The exact complexity of m operations of any type is O(m * alpha(n)) where alpha is the inverse Ackerman funct... |
71,453,531 | 71,453,629 | SFML: image gets drawn and moves when I press a key, but doesn't move when I try to create a vector of them | The following code works... Basically when I press the spacebar, it draws a line, which continually moves in the Y direction on the screen.
// <Code that initializes window>
// set the shape
sf::CircleShape triangle(50, 3);
triangle.setPosition(300, 500);
sf::RectangleShape line;
// Start the game loop
while (windo... | When iterating over the lines, you create copies of the rectangles, and then move those copies, instead of the instances stored in the vector.
Use reference in your for-range loops.
for (sf::RectangleShape& l : laserStack) {
l.move(0, -0.3);
}
for (sf::RectangleShape& laser : laserStack) {
window.draw(laser);
}
|
71,453,536 | 71,453,603 | C++ edit function, return vector | May I ask how to modify the vector<CContact>& addContact(const CContact &c) method to pass this assert? Am I correct that the function should return a vector according to the assignment? I am adding reduced important functions.
class CTimeStamp
{
public:
CTimeStamp(int year, int month, int day, int hour, int minu... | The way your methods are written, you cannot chain addContact() with another addContact() (or any other CEFaceMask method).
Either change the way you are calling addContact() the second time:
test.addContact ( CContact ( CTimeStamp ( 2021, 1, 12, 12, 40, 10 ), 123456789, 111222333 ) );
test.addContact ( CContact ( CT... |
71,453,555 | 71,454,661 | How do you convert an FString of delimited floats to a TArray<uint16> using Unreal C++ | Given an FString of "123.2222,446.4444,55234.2342" how do you convert this to a TArray of type uint16?
Current attempt is to parse the string into an array using
TArray<FString> Parsed;
HeightMapData.ParseIntoArray(Parsed, TEXT(","), false);
This seems to work well. Next is the problem of how do I convert this to ... | You can't reinterpret_cast and pretend your array of strings is an array of integers. You need to convert each string to an integer in a new array:
TArray<uint16> intArray;
for (const auto& str : Parsed)
intArray.Add(FCString::Atoi(str));
Ref: https://docs.unrealengine.com/4.26/en-US/ProgrammingAndScripting/Progr... |
71,453,755 | 71,454,485 | Is it legal to use an unexpanded parameter pack as the type of a template template parameter's non-type template parameter? | gcc and clang disagree about whether the following code should compile:
template <typename... Args>
struct tuple {};
template <typename>
struct Test;
template <
typename... Types,
template <Types> typename... Outer, // XXX
Types... Inner
>
struct Test<tuple<Outer<Inner>...>> {};
template <long T> struct ... | It is not valid because:
a type parameter pack cannot be expanded in its own parameter clause.
As from [temp.param]/17:
If a template-parameter is a type-parameter with an ellipsis prior to its optional identifier or is a parameter-declaration that declares a pack ([dcl.fct]), then the template-parameter is a templa... |
71,454,015 | 71,454,148 | Passing Array into Function in C++ | I am currently working on a c++ program that uses the function. When I run the code, I am getting 3 error that
error: ‘userInput’ was not declared in this scope
error: ‘displaySum’ was not declared in this scope
error: ‘displayAverage’ was not declared in this scope
I'm not sure if the problem is the passing the array... | userInput(numbers, 10);
When your C++ compiler reaches this line it will have absolutely no idea what this mysterious function called userInput() is all about. The C++ program gets compiled in logical order, from beginning to the end, and this function has not been declared yet.
You will need to add a forward declarat... |
71,454,051 | 71,461,439 | What is clang version 10.0.7 for Android NDK? | I did
strings Image | grep -i clang
to my Poco M3 kernel extracted from an official ROM for Android 11 and got
Linux version 4.19.113-perf-ga223430d113c (builder@m1-xm-ota-bd331.bj.idc.xiaomi.com) (clang version 10.0.7 for Android NDK) #1 SMP PREEMPT Tue Feb 8 18:34:58 CST 2022 %s version %s (builder@m1-xm-ota-bd331.b... | Turns out it comes from Snapdragon's LLVM compiler https://developer.qualcomm.com/software/snapdragon-llvm-compiler-android
but the version 10.0.7 is not downloadable directly, it looks like you need to use the Qualcomm Package Manager, but it won't install on my ubuntu
|
71,454,585 | 71,454,637 | C++ [heap-use-after-free error] with referencing and push_back to vector | Below is my code and the execution result.
#include<vector>
#include<algorithm>
typedef struct Block {
int value;
Block(int value): value(value) {}
} Block;
int main() {
std::vector<Block> blocks;
blocks.emplace_back(1);
Block& block = blocks[0];
blocks.emplace_back(2);
std::max(1, block.v... | because after emplace new element to blocks, may element's address have change (internal vector expanding operation )-> you save previous address is incorrect. to fix it you just change order of commands.
std::vector<Block> blocks;
blocks.emplace_back(1);
blocks.emplace_back(2);
Block &block = blocks[0];
std::max(1, b... |
71,454,588 | 71,454,718 | MINSIGSTKSZ error after update in my manjaro linux | After I update my system with
sudo pacman -Syu
I can’t run my college coursework and get this error
> make
g++ -c -Wall -Wpedantic -Werror -Wextra -std=c++14 main_test.cpp
In file included from /usr/include/signal.h:328,
... | Suprisingly https://sourceware.org/git/?p=glibc.git;a=blob;f=NEWS;h=85e84fe53699fe9e392edffa993612ce08b2954a;hb=HEAD :
When _SC_SIGSTKSZ_SOURCE or _GNU_SOURCE are defined, MINSIGSTKSZ and SIGSTKSZ are no longer constant on Linux.
I fear this change will bite many programs. This is odd, because in POSIX MINSIGSTKSZ is... |
71,454,904 | 71,479,615 | Is there possible ways to print a returning stack from a fuction? | I try to use stack function to convert decimal number to binary number and return the stack function value to main function but I am not able to output the correct result to the screen.(sorry for my English)
#include<iostream>
#include<stack>
using namespace std;
stack<int> BinaryNum(int k, stack<int> st){
if(k >= ... | You discard the result of BinaryNum in main, and are passing copies of your stack around.
Either use the result
int main(){
int k;
cin >> k;
stack<int> st;
st = BinaryNum(k,st);
while(!st.empty()){
cout << st.top();
st.pop();
}
}
or take st by reference in BinaryNum
stack<int> B... |
71,455,206 | 71,455,269 | Why does shared_ptr<int> p; p=nullptr; compile? | Since the constructor of std::shared_ptr is marked as explicit one, so expressions like auto p = std::make_shared<int>(1); p = new int(6); is wrong.
My question is why does std::make_shared<int>(1); p = nullptr; compile?
Here is the aforementioned code snippet:
#include <memory>
#include <iostream>
int main()
{
au... | The raw pointer constructor is explicit to prevent you accidentally taking ownership of a pointer. As there is no concern taking ownership of nullptr the constructor taking std::nullptr_t is not marked explicit.
Note that this only applies to nullptr these other assignments of a null pointer might not work (depending o... |
71,455,365 | 71,455,384 | CPP: Capturing returned reference by value (i.e; in an lvalue of the referred type) | I tried this code to test how the returned reference gets propagated if captured by value:
int& give_rint()
{
std::unique_ptr<int> x(new int(32));
return *x;
}
int main()
{
int b = give_rint();
std::cout << b << std::endl; // prints 0
return 0;
}
I expected this to print 32, assuming that b wo... |
I expected this to print 32
When the function returns, unique pointer is destroyed, and the allocated memory is deallocated. The returned reference is always invalid.
When you indirect through the invalid reference by using it to initialise b, the behaviour of the program is undefined.
can I somehow emulate the same... |
71,455,960 | 71,456,095 | Why program stops after constructor? | I am learning operator overloading and I read somewhere that when you assign a r-value to object then it creates a temporary object but this program stops after calling constructor for r-value.
Class.h
class Foo{
int *num;
public :
Foo(int x);
Foo& operator=(Foo &&rhs);
Foo& operator=(const Foo &r... | Your problem is in the destructor. It tries to access *num, but move assignment operator sets num to nullptr.
Either guard logging against nullptr (there is no need to guard delete, as it is guaranteed to work properly on null pointers):
Foo::~Foo(){
if (num) {
std::cout << "Destructor for " << *num << std:... |
71,456,594 | 71,476,129 | Is there an efficient algorithm to redistribute a vector over processes based on how many elements each process has to give up or recieve? | I'm trying to redistribute an array (mesh-like) over a set of processes for load-balancing needs. My special requirement is that array elements should only be moved to the spatially adjacent processes as only the elements near the front between elements can be moved easily.
In the above example setup, all first three ... | I'll generalize your question: you are looking for an algorithm for load balancing where processes are connected through a graph, and can only move load to graph-connected processes. This algorithm exists: it's known as "diffusion based load balancing" and it was originally proposed by Cybenko. A simple web search will... |
71,457,335 | 71,460,305 | Where is a ordinary variable defined inside a __device__ function placed? | In CUDA, I understand that the variable would be placed in shared memory if it was defined as __ shared __ and one would be placed in constant memory if it was defined as __ constant __.Also, those being allocated memory using cudamalloc() are put in GPU global memory. But
where are those variable without prefixs like ... | Automatic variables, i.e. variables without memory space specification within the scope of functions, are placed in one of the following locations:
When optimized away:
1.1 Nowhere - if the variable isn't actually necessary. This actually happens a lot, since CUDA functions are often inlined, with some variables becom... |
71,457,376 | 71,463,556 | How to specify style sheets for my classes in QT | I have a class that inherits from qframe, the "darksheetstyle" qss file is:
/* (dot) .QFrame fix #141, #126, #123 */
.QFrame {
border-radius: 4px;
border: 1px solid #455364;
/* No frame */
/* HLine */
/* HLine */
}
.QFrame[frameShape="0"] {
border-radius: 4px;
border: 1px transparent #455364;
}
.QF... | This works as expected for me:
#include <QtWidgets>
class BorderedFrame : public QFrame
{
Q_OBJECT
public:
using QFrame::QFrame;
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
app.setStyleSheet("BorderedFrame { border-radius: 4px; border: 2px solid #ff0000; }");
BorderedFrame w;
w.sh... |
71,457,810 | 71,457,869 | Can we have an out of class definition for a class template that is a member of a class template | I know that the following snippet is valid:
template<typename T>
struct Custom
{
template<typename V> void func();
};
//valid
template<typename T>
template<typename V>
void Custom<T>::func()
{
}
But can we do the same for a class template instead of a member function template. Take for example,
template<ty... | Yes, you can make an out of class definition for InnerCustom:
template <typename T>
template <typename V>
struct Custom<T>::InnerCustom { // note: `struct` added
// ...
};
|
71,457,938 | 71,458,628 | User input used as a parameter in a function c++ | While I understand why my code is wrong as well as brute-forcing my way around it, I'm wondering if there is way to do it the way I imagined it, so:
(just for context I'm making a simple game called Tower of Hanoi and this is the function I made that works when I manually input my stack as parameters)
void putOn(std::... | Try this:
std::map<char, std::stack<int>*> m = {{'x', &x}, {'y', &y}, {'z', &z}};
//...
putOn(*m[a], *m[b]);
|
71,458,228 | 71,459,364 | C++ : Calling a constructor from a class inside another class | I am working on a code which contains three classes: date, note, and student.
Date is made up of: int, int, int
Note is made up of: string, double, int
In ex3.h:
class student;
class date {
private:
//---------declaration of attributes-----
int j ; // day
int m ; // month
int a... | When you create an object of student type, the members of it are created with default constructors before the constructor of the student starts execution. So, the compiler tries to call the default constructor of the date type object, and then in the body of the student's constructor, it makes a call to the copy assign... |
71,458,432 | 71,458,494 | Disambiguate template function specializations - value vs. reference | This question requires a bit of context - if you're feeling impatient, skip past the line break... I have a Vector-3,4 and Matrix-3,4 library defined in terms of template specializations; i.e., Vector<n> and Matrix<n> are defined in Matrix.hh, while non-trivial implementations (e.g., matrix multiplication, matrix inver... | You named robust_multiply wrong.
*= and * are fundamentally different operations. They are related, but not the same operation - different verbs.
Overloading should be used when you are doing the same operation on different nouns.
If you do that, then your problems almost certainly evaporate. Sensible overloads are ea... |
71,458,568 | 71,465,607 | Turn relay on from Bluetooth for certain amount of seconds | I am working on two way communication between arduino and android phone. Currently everything is working, however I have couple of issues I have been trying to solve recently.
How I can ignite ignition for 5 seconds? I mean if IgnitionPin is on HIGH, run it for 5 seconds then automatically turn off? There is an easy w... | #1
Use the TimerOne library or setup an ISR.
Run the ISR at, 5 times per second.
uint32_t timeout = 5 * 60;
uint8_t flag = 1;
digitalWrite (myPin, HIGH);
if (timeout && flag) {
timeout--;
} else {
digitalWrite (myPin, LOW);
flag = 0;
}
OR
by checking time elapsed since some specific point in time.
unsigne... |
71,458,630 | 71,458,863 | GetSystemMetrics(SM_CYSCREEN); | Gives wrong value| but GetSystemMetrics(SM_CXSCREEN); gives correct value | I have a problem with GetSystemMetrics(SM_CYSCREEN); – the height this function returns is random each time I run the program but the width function, GetSystemMetrics(SM_CXSCREEN); gives the correct value.
Here is my code:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
int MessageBoxPrintf(const wcha... | The code you have posted shows (almost certainly) undefined behaviour, because of the incorrect way you handle the variadic argument list in your MessageBoxPrintf function.
In the wchar_t* c = va_arg(v1, wchar_t*); line, you are 'assuming' a single wchar_t argument – but, in your main function, you are passing two int ... |
71,458,888 | 71,459,130 | how to split a string_view into multiple string_view objects without any dynamic allocations | The snippet below comes from this answer.
#include <string>
#include <vector>
void tokenize(std::string str, std::vector<string> &token_v){
size_t start = str.find_first_not_of(DELIMITER), end=start;
while (start != std::string::npos){
// Find next occurence of delimiter
end = str.find(DELIMIT... |
I tried to write one myself but it didn't work as expected (didn't
support the tab).
If you want to support splitting with spaces and tabs, then you can use another overload of find_first_not_of:
size_type find_first_not_of(const CharT* s, size_type pos = 0) const;
which will finds the first character equal to none ... |
71,459,523 | 71,459,649 | Does mulithreaded http processing with boost asio require strands? | In the boost asio documentation for strands it says:
Strands may be either implicit or explicit, as illustrated by the following alternative approaches:
...
Where there is a single chain of asynchronous operations associated with a connection (e.g. in a half duplex protocol implementation like HTTP) there is no possi... | If the async chain of operations creates a logical strand, then often you don't need explicit strands.
Also, if the execution context is only ever run/polled from a single thread then all async operations will effective be on that implicit strand.
The examples serve more than one purpose.
On the one hand. they're obvi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.