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 |
|---|---|---|---|---|
74,331,990 | 74,332,143 | check and protect a thread in c++ | Currently, I created a simple thread to clear memory:
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
CreateThread(0, 0, test, 0, 0, 0);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:... |
prevent thread from being paused with some external program (such as Process Hacker 2)?
Instead of creating a new thread to run your code periodically, create a waitable timer with CreateWaitableTimer and schedule it with SetWaitableTimer. The timer runs the callback in the thread that called SetWaitableTimer, so tha... |
74,332,135 | 74,332,239 | How to read a file in Python written out by C++ | I have one program written in C++ that outputs the data from several different types of arrays. For simplicity, I'm using ints and just writing them out one at a time to figure this out.
I need to be able to read the file in on Python, but clearly am missing something. I'm having trouble translating the concepts from C... | In the simple case you have provided, it is easy to write the Python code to read out 1234 and 5678 (assuming sizeof(int) is 4 bytes) by using int.from_bytes.
And you should open the file in binary mode.
import sys
with open("out.txt", "rb") as f:
while (byte := f.read(4)):
print(int.from_bytes(byte, sys.b... |
74,332,440 | 74,332,699 | How to use "type ... pack-name" parameter pack in C++? | The cppreference page on parameter pack states there is a parameter pack like this:
type ... pack-name(optional) (1)
But how do you use it?
This doesn't work and the error is syntactical:
template<int... Ints>
int sum_2_int(Ints... args)
{
return (int)(args + ...);
}
I can't figure out how to use this thing fr... | So, what I've learned about type (1) parameter pack:
It is INCORRECT to use as a parameter in the function definition, since template<int... Ints> int foo(...) {...} just means that you should later use your function as int i = foo<1,2,3,4,...>(...);
It can be used as an argument to some function after the expansion h... |
74,332,629 | 74,332,715 | Realloc throws stack overflow sporadically in program that calculates large integers | void inf_int::Sub(const char num, const unsigned int index)
{
if (this->length < index) {
char* tmp = (char*)realloc(this->digits, index + 1);
if (tmp == NULL) {
cout << "Memory reallocation failed, the program will terminate." << endl;
free(this->digits);// provided that th... | this->digits = new char[2];
This class member is initially allocated using new.
char* tmp = (char*)realloc(this->digits, index + 1);
This is undefined behavior. realloc is for C code that used malloc to allocate memory. A realloc of something that was originally newed always ends in tears. Everything that follows fr... |
74,332,725 | 74,333,952 | How to summing element in array using taskloop on OMP | I was trying to using taskloop to finding sum of element in array.
#include <iostream>
#include <omp.h>
using namespace std;
#define NUMTHREAD 6
#define SIZE 100
int main() {
int* n = new int [SIZE];
for (int i = 0; i < SIZE; ++i) {
n[i] = 1;
}
long sum =0;
#pragma omp parallel num_threads(NUMT... |
The taskloop construct is a task-generating construct, not a worksharing-loop construct. You can read the following in OpenMP specification:
The taskloop construct is a task generating construct. When a thread
encounters a taskloop construct, the construct partitions the
iterations of the associated loops into exp... |
74,332,999 | 74,333,188 | Why does this freestanding program segfault? | I've found an interesting behavior that I cannot explain. I wrote this very simple program that segfaults without apparent reason. Please, can someone explain what is happening here?
The program is run in Ubuntu (I don't know if that matters).
No includes, no libraries, no link to stdlib. No dependencies whatsoever.
... | Check your stack alignment.
For the SysV ABI, rsp is guaranteed to be 16-bytes aligned at program entry. However, a normal function expect rsp to be 16-bytes+8 aligned, because of the address pushed by call.
Clang uses SSE aligned instructions which will crash, GCC doesn't.
|
74,333,029 | 74,333,106 | How to make increment/decrement static variable for an API? | #include <iostream>
class Test {
public:
static int numelem;
Test() {}
~Test() {}
int increment();
};
int Test::numelem = 0;
int Test::increment()
{
return ++Test::numelem;
}
So I want to make a counter for my Stacks data structure.
Whenever I push, it increments and when popped it decrements.
My ... |
but int Test::numelem = 0; is a global variable.
Technically, it is not a global variable but a class static member. Functionally they behave very similarly.
Is there an alternative way I can put int Test::numelem = 0; inside the class without getting any error? unfortunately I have C++14.
With C++14 the out-of-cl... |
74,333,276 | 74,333,326 | Get vertex buffer bound to vertex array | I'm writing an OpenGL application, and the problem I'm facing now is as follows:
Let us say I have a Vertex Array, with its ID. However, I do not have its bound vertex buffer ID at hand. I am in need of the Buffer ID for an operation. SO, is it possible to retrieve current buffer binding from vertex array?
Note that I ... |
Let us say I have a Vertex Array, with its ID. However, I do not have its bound vertex buffer ID at hand.
In a well-behaved application, that should not be possible. It was your application that put that buffer into that VAO. Therefore, you should already know what buffer is attached to it. It's a question you don't ... |
74,333,483 | 74,333,778 | How to Read in a String With Spaces into a Linked List? | So essentially I am reading data into this linked list, then after each node is inserted (front or back) I display the nodes. When I do this, everything works fine with names without spaces, but if I use first and last with a space it does not function properly and will separate the string(s) with spaces into 2 differe... | Assuming the node definition needs to be the same and input is through stdin and all one one line for the following answer. Due to use of char [20] input from stdin is truncated to prevent overflow or segfault.
Given the following node (preserving OP's node definition):
struct node {
char string_val[20];
struc... |
74,333,889 | 74,333,943 | An alias for a function pointer declared by "using" | I have declared an alias for a function pointer with "using" keyword, but I don't know how to use the alias.
In UpdateState function of Person class, I want to substitude m_state for the return value of the function corresponding to the current state and the one you want to transition to next. However, the error below ... | To get a pointer to a non-static member the syntax is &ClassName::membername.
Additionally, a call using the pointer to member function is made using either .* or ->*.
Below is the modified working example where I've added comments to show the changes i've made:
void Person::UpdateState()
{
char inputArray[] = { 'a... |
74,334,362 | 74,334,405 | What's the difference b/w map[key] vs map.count(key) ? (particularly in this code) | So I was Solving a leetcode Problem and one dumb mistake made in debugg for more than an hour.
Leetcode Question
Answers(both working and not working)
Working code:
`
class Solution {
public:
int longestPalindrome(vector<string>& words) {
unordered_map<string,int> map;
for(string s:words){
... | std::map.count() will check, if an element with a given key exists. It will not modify the container. Please see here. It is even defined as constto indicate that fact.
The std::maps index operator is different. It
returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if s... |
74,335,759 | 74,335,815 | How do I use member functions to a standard library ranges operation | I need to find all regular files in a directory, and would like to use the C++20 ranges (not Eric Niebler's range-v3) library. I came up with the following code:
namespace fs = std::filesystem;
std::vector<fs::directory_entry> entries{ fs::directory_iterator("D:\\Path"), fs::directory_iterator() };
std::vector<fs::pa... | Just &fs::directory_entry::is_regular_file as argument is in principle correct, assuming that there is only one non-template overload for the function. Pointers can only point to one function (or function template specialization), not to an overload set.
However per standard there are two overloads for directory_entry:... |
74,336,301 | 74,336,780 | Efficient way to generate random numbers with weights | I need to frequently generate a large number of random numbers in my project, so I am seeking an efficient way to do this. I have tried two ways: (i) using random() and srand(); (ii) using C++ random library.
I tried on the following example: I need to generate 100000000 numbers, from {0, 1, 2, 3}, with weights {0.1, 0... | Use the random library correctly. In the C version, you put the call to srand outside of the loop, so do the same in the C++ version for the engine and the distribution.
std::vector<int> res(100000000);
std::vector<double> weights{0.1, 0.2, 0.3, 0.4};
std::default_random_engine randGen(seed);
std::discrete_distribution... |
74,336,341 | 74,336,468 | Is std::span constructor missing noexcept? | According to cppreference constructor (2) of std::span is defined as
template< class It >
explicit(extent != std::dynamic_extent)
constexpr span( It first, size_type count );
with its exceptions listed as 2) Throws nothing.
If this constructor "throws nothing" then why is it even listed under exceptions and why is the... | That's because this constructor has preconditions. From the standard:
template<class It>
constexpr explicit(extent != dynamic_extent) span(It first, size_type count);
Constraints: Let U be remove_reference_t<iter_reference_t>.
It satisfies contiguous_iterator.
is_convertible_v<U()[], element_type()[]> is tr... |
74,336,813 | 74,403,298 | In vscode tasks.json how to use the g++ to compile-only multiple files and apply the output to make an executable? | What I do want to achieve is separate the compilation and linking steps for multiple .cpp and .h files. Like this: g++ -c *.cpp && g++ -o main *.o. But I would like to do that inside the vscode tasks.json. I tried the following code:
Tasks.json
{
"tasks": [
{
"type": "cppbuild",
"lab... | Following the comments suggestion and vscode compound tasks doc. Found a way to compile and produce a executable with the code below:
{
"tasks": [
{
"type": "cppbuild",
"label": "c++",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=a... |
74,336,832 | 74,388,714 | authenticate ftp users from sql database in c++ | i have a messaging app written in c++ (qt) and now i want to add a library to move heavy media via ftp to a ftp server and give the link to other user to download it.
the problem is there are to many users to create separate ftp accounts for all of them manually and using one account for all of them isn't safe.i want t... | i found a way.pureFTPD is a ftp daemon that lets u use a sql database to validate ftp users and limit their access.
|
74,336,847 | 74,336,923 | Error in the example code of A Tour of C++ | I'm going through Mr. Stroustrup's "A Tour of C++" book. In section 9.3 String Views, the author gives the following example:
string cat(string_view sv1, string_view sv2)
{
string res(sv1.length()+sv2.length());
char *p = &res[0];
for (char c : sv1) // one way to copy
*p++ = c;
copy(sv2.begin(),... |
Is this a bug in the example provide or else I'm missing something else?
Yes this is an erratum in the book as std::string doesn't have a constructor that has only one parameter of type int(or convertible to int).
Instead it has a constructor std::string::string(size_type, char) that can take a char as the second arg... |
74,337,500 | 74,337,552 | is there any way to read one number from the anonymous pipe in two different processes? | I have one anonymous pipe and two child processes. I write one number in the pipe and now i have to read it in both processes. is there any way?
I tried to GetStdHandle(STD_INPUT_HANDLE), also I tried to use cin.peek but it doesn't work for me.
| You don't tell us which kind of anonymous pipes you're dealing with. However, since pipe is a UNIX concept in its core, I'll assume you're referring to POSIX pipes.
These don't support multi-reader access. A read access necessarily consumes the read bytes from the underlying buffer.
So what you want is impossible, kind... |
74,337,532 | 74,337,695 | std::visit does not accept a callable that is a derived class object | I am trying to use std::visit to inspect an std::variant.
First I declare the variant and a base (callable) visitor class for the variant:
#include <iostream>
#include <string>
#include <variant>
using Amalgamation = std::variant<int, bool, std::string>;
class BaseVisitor {
public:
virtual void operator()(int) {... | Function overloading (multiple functions of the same name in the same scope) and function overriding (a function in a derived class that provides a different implementation from a virtual base class version) interact in unpleasant ways.
If a base class defines a function with some name, and a derived class defines a fu... |
74,337,618 | 74,337,669 | sort vector by using lambda with && | I am trying to sort a vector elements by using lambda but I have a question. I am trying to sort it base on 2 values from a struct but lambda does not allow me to do it like that.
Here is what i am trying to do:
struct Test
{ int Current;
int Max;
};
std::vector<Test*> VectorA
std::sort(VectorA.begin(), VectorA... | Your std::vector contains elements of type Test*, not Test.
Therefore your lambda should accept references to Test* objects, and derefernce the pointers with operator->.
Since you do not need to modify these objects, it is better for your lambda to accept the arguments by a const reference.
A complete example:
#include... |
74,337,633 | 74,337,694 | C++ string modification, no pass by reference? | I am a beginner studying C++. Currently I am studying functions, C strings, and pass by reference.
The program below is meant to take a string from input, replace any spaces with hyphens, and any exclamation marks with question marks.
If the function below, StrSpaceToHyphen() is of return type void, wouldn't the functi... | This declaration of the parameter
void StrSpaceToHyphen(char & modString[]) {
declares an array of references. You may not declare arrays of references.
As for your initial declaration
void StrSpaceToHyphen(char modString[]) {
then the compiler adjusts the parameter having the array type to pointer to the array eleme... |
74,337,792 | 74,338,338 | typedef declaration contains #define directive alias | I use two libraries in my project; let's say A and B for the sake of this question. Unfortunately, I ended up in the following situation:
In A.h:
#define ssize_t long
In B.h:
typedef long long ssize_t;
This leads to the following error, if A.h is included (i.e., processed) prior to B.h:
E0084 invalid combination of ... | In a pinch, edit both headers, remove configuration logic around the problematic typedef/#define, and insert a simple typedef wrapped in #ifndef in both:
#ifndef my_size_t_defined
#define my_size_t_defined
typedef long long ssize_t;
#endif
If you are not afraid, you can try creating sys/types.h with these lines in you... |
74,338,102 | 74,338,163 | Class variable gets updated only once in gameloop | I have a problem with updating the value of a class variable on each frame of gameloop.
I am using wxWidgets for creating a cross-platform window and for graphics as well as gameloop. This is my main Window class which implements rendering and the gameloop.
#include <wx/wx.h>
#include "window.h"
#include "../entity/ent... | When you loop over your entities like this (in Window::Render, Window::Update):
for (Entity entity : entities) {
in each iteration entity will get a copy of the element in entities.
In order to operate on your actual entities via a reference you need to change it to:
//----------v---------------------
for (Entity & en... |
74,340,185 | 74,340,222 | For loop inside for loop execute only one time | I'm using while loop inside for loop to repeat for loop, but it only execute one time.
I did this code:
#include<iostream>
using namespace std;
int h, rep = 0;
int main() {
cout << "Please enter pyramid's height: ";
cin >> h;
cout << "Please enter Repetition Number: ";
cin >> rep;
for(int i = 0; i ... | while(0<rep){
--rep;
}
At the conclusion of this while loop rep is 0. This is what the shown code tells your computer to do, so that's what your computer does. Your computer does this because of the Golden Rule Of Computer Programming: "Your computer always does exactly what you tell it to do instead of what you w... |
74,340,375 | 74,340,530 | Why does C++ template argument deduction fail to deduce the elements of a std::array? | The Problem
Considering the following (C++20) code
#include <array>
// class template depends on array of ints
template<std::size_t N, std::array<int, N> arr>
struct S {};
// fix array length (for convenience)
template<int x>
using U = S<1, std::array{x}>;
// function template depends on array element only
template<... | A non-type template argument containing a template parameter in a subexpression (rather than as the full argument) is a non-deduced context. (See [temp.deduct.type]/5.3.)
In other words when deducing the function argument of type S<1, std::array{2}> against the function parameter type S<1, std::array{x}>, then std::arr... |
74,340,524 | 74,340,934 | How to read the VAO from the GLSL shader, or pass an Array of indefinite size to the shader? | I partially managed to implement rendering by individual indexes - by loading the indexes into VAO, setting their layout, and passing them using glDrawArrays
but now another problem - for test i created arrays in shader itself -
`
#version 330 core
// Positions/Coordinates
layout (location = 0) in int V_Indices;
// Co... | The best fit for this task would be a Shader Storage Buffer Object:
layout(std430, binding=0) buffer VertexBuffer { vec3 Vertices[]; };
layout(std430, binding=1) buffer TexcoordBuffer { vec2 Texcoords[]; };
layout(std430, binding=2) buffer NormalBuffer { vec3 Normals[]; };
...
void main() {
gl_Position = camMatrix ... |
74,340,726 | 74,340,741 | Why does my deposit feature only let me deposit 10,000 or less? | I created a bank app, and when I try to deposit money that is over 10,000, my error message that I set up displays, but any number under works.. I assume this has something to do with value types. I used int, however I tried double but can't figure that out too.
/* FUNCTION DEFINITION */
void DepositMoney(int initialba... | When you call DepositMoney(), you have this check: if (initialbalance < deposit). At this point, initialbalance is 10000, so if the amount is greater, then you cannot deposit it. Based on the logic, you likely wanted a check like that in withdrawMoney(), not in DepositMoney().
|
74,340,753 | 74,340,921 | getting '0b' in memory when trying to serialize object in c++ | I am trying to serialize an object for sending in a socket, but for some reason, when i add to the string stream using <<, I'm also adding '0b' after it, i've tried looking for something that may cause this (such as a fault data type) but so far i came up with nothing.
this is my object before in memory before the seri... | Your bug is in this line:
os << H.CID;
It calls the unsigned char overload of (2) here: https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2, which means it just writes the memory of your Header object until the first null byte.
To achieve what you actually wanted, you can do something like
os.write(reint... |
74,340,846 | 74,340,868 | What does it mean by member initialization list initializing an attribute of a class | If I have a class like the below one:
class foo {
private:
int a;
public:
foo (int arg1) : a(arg1) {}
};
The attribute a will be default-initialized in the line it got declared.
Now, when the parameterized constructor is called, it gets re-initialized to the value arg1 in the member-initialization list.
I... | No, a won't be "re-initialized", i.e. initialized twice. When the parameterized constructor is used a will only be direct-initialized from the constructor parameter arg1, no default-initialization happens.
If foo has another constructor which doesn't initialize a in member-init-list, then it'll be default-initialized. ... |
74,341,308 | 74,350,257 | How do I write a function signature such that it will take in a container or a range? | I was trying to make a single function that takes in a container and implicitly have it convert to a boost::iterator_range as I thought that was it's purpose, but it seems that I'm missing something.
Here's an example of what I was thinking:
#include <boost/range/iterator_range.hpp>
#include <vector>
template<typename... | The "obvious" answer is to be less specific: Live On Coliru
#include <boost/range/iterator_range.hpp>
#include <iostream>
#include <numeric>
#include <vector>
template <typename Range> auto fn_x(Range&& r) {
using std::begin;
using std::end;
return accumulate(begin(r), end(r), 0.0);
}
int main() {
std... |
74,341,356 | 74,341,416 | I can't select a different option in my program | I was writing a program inspired by one of my favorite books Diary of a wimpy kid. You play as Greg's dad and you have 3 options with what to do with him. When i ran the program I first selected the first option which printed the first one. I tried it again with the third option as well with the same result.
#include <... |
you have to use a double = because you want to compare the values in the if statement. You dont want to set the left variable equal to the right value.
2.because youre passing a int value into the function, the program will not return true because a int is not equal to a string. So you dont have to use these '' aroun... |
74,341,491 | 74,341,956 | Rust: Default structure member initialization for static structures? | I'm evaluating Rust as a possible replacement for C/C++ in a new iteration of embedded FW. As I create simple projects, potential inconveniences come up. It's important for this application that migration be relatively painless, meaning that the most idiomatic Rust approach to a design pattern may not be possible. But ... | The sticking point that you've hit is that static intializers must be const expressions but traits (like Default) do not have const support (yet). You'll need to implement a const function to construct your MyStruct without using Default:
impl MyStruct {
pub const fn new() -> MyStruct {
MyStruct {
... |
74,341,693 | 74,342,421 | set::set from variadic template arguments | How do I create a set from arguments of variadic templated function?
template<class T>
concept Int = std::same_as<T, int>;
template<Int... Ints>
std::set<int> fun (Ints... ints)
{
// create and return a set containing arguments to this function
}
| You can expand the pack using pack expansion as shown below:
template<Int... Ints>
std::set<int> fun (Ints... ints)
{
return {ints...}; //use unary right fold
}
int main()
{
std::set<int> myset = fun(1,2,3);
}
Demo
|
74,342,032 | 74,342,494 | C++ Cannot list files of dir C:\Users\User\Recent\ | I'm trying to create an application that will delete specific files from C:\Users\User\Recent. For this I want to go through all the files first and see if the file should be deleted.
I've tried many things, for example:
const char* path2 = "C:\\Users\\User\\Recent\\";
for (const auto& dirEntry : std::filesystem::recur... | Call SHGetFolderPath to get the correct location of the Recent folder. It is usually somewhere inside %AppData%.
If you wish to "clean" this folder correctly, accessing it directly from the file system is not ideal because there is mirrored information stored in the registry (HKEY_CURRENT_USER\Software\Microsoft\Window... |
74,342,218 | 74,356,014 | Will std::make_unique<alignas(32) std::byte[]> allocate aligned memory? | I'm wondering if I can replace code like
std::unique_ptr<std::byte[]> p { new (std::align_val_t{32}) std::byte[size]{} };
with
auto p = std::make_unique<alignas(32) std::byte[]>(size);
| Well, the first problem is that there is no such type as alignas(32) std::byte[]. It is not a valid type-id. You can see the grammar for type-id here.
To make alignas(32) apply to std::byte[], you would have to put it at the end: std::byte[] alignas(32). This is grammatically correct, but it has no effect. In other wor... |
74,343,214 | 74,343,533 | Big O notation of Formula - P *R Squared | I want to calcuate the Big O notation for an area of circle.I wonder what is the time complexity of Pi *r^2? is it O(n) or O(n^2)? Please also check if my way of doing is correct.
Algorithm
Step 1: Start // f(n)=O(1) ( Executes 1 time)
Step 2: Get an integer input from user for AREA and RADIUS//. f(n)=O(n)=O(1... | This depends on your model of computation.
For most practical purposes its O(1), because the runtime does not depend on your input r. This assumes implicitly that your input is bounded, for example fits into a 32-bit integer.
More theoretical you can think about arbitrary big r. The N in the big O notation then is norm... |
74,343,255 | 74,343,891 | How to efficiently perform a list of transformations in place on an object in C++? | I'm new to C++ and am a bit confused by how references, values, and move semantics work. I want to implement a function that can take an event, apply a list of transforms, and output the transformed event.
Here's a code snippet:
std::vector<Event (*)(Event)> transforms = ...;
Event process(Event baseEvent) {
Even... | Your transformation function takes an Event and returns a new Event. It is literally impossible to build a "should modify in place" function on top of that.
So your function is already pretty much as close as you can get to what you want, except for the rvalue reference thing. There's no point in doing that. You want t... |
74,343,922 | 74,343,997 | E0298 inherited member is not allowed | I am trying to program chess. I want create is virtual parent class Tool, and child classes for each peace type. Here is my 4 files I writed:
Tool.h
#pragma once
#include <iostream>
using namespace std;
class Tool
{
protected:
string type;
int row;
int colum;
int player;
public:
Tool(int row, int c... | The problem is that in order to provide an out of class definition for a member function of a class, a declaration for that member function must be present inside the class. And since there is no such declaration inside the derived class King, we can't define it that way you did.
Thus to solve this add a declaration fo... |
74,344,328 | 74,344,970 | How to check if a key is empty in map<int,pair<int,int>> - C++ STL | I have a
unordered_map<int, vector<pair<int, int> > > revert;
How do I check if some key is not present in the map
If I apply
revert[id].size()==0
condition , its be default size is some big number 107374182.
How do I check if its empty??
I tried to add breakpoint and debug , and that is where I found that its defaul... | revert[id].size()==0 will access the size() function a newly created std::vector if nothing was inserted with key id before. I'm not sure why the size is this big random number here and I have no way to check without a full example.
To correctly check if an entry with key id exists in revert you can use revert.conains(... |
74,344,350 | 74,348,380 | char8_t and utf8everywhere: How to convert to const char* APIs without invoking undefined behaviour? | As this question is some years old
Is C++20 'char8_t' the same as our old 'char'?
I would like to know, what is the recommended way to handle the char8_t and char conversion right now? boost::nowide (1.80.0) doesn´t not yet understand char8_t nor (AFAIK) boost::locale.
As Tom Honermann noted that
reinterpret_cast<const... |
This would invoke the same UB that Tom Honermann mentioned.
As pointed out in the post you referred to, UB only happens when you cast from a char* to a char8_t*. The other direction is fine.
If you are given a char* which is encoded in UTF-8 (and you care to avoid the UB of just doing the cast for some reason), you c... |
74,344,876 | 74,345,197 | C++ SIGABRT on new thread | I'm trying to parallelize a method inside a Parser class. Since this method requires shared mutex I wasn't able to use OpenMP, and therefore had to go with the standard libraries.
I'm currently working with C++ 17, and here's the main code that's not working:
auto p = Parser(.7);
int tMax = thread::hardware_concurrency... | You're creating a vector of threads and then immediately exit main without waiting for any of them to finish execution. This will cause them to crash.
Adding for(auto& t : threads) t.join(); to the end of main to wait on all the threads works in my test.
|
74,345,380 | 74,345,470 | c++ Friend function not recognised as friend with template specialisation | I am trying to declare a function as friend to a class template with a protected member. Below is a minimal example.
template<int N> class myClass{
public:
friend void f(const myClass& c);
protected:
int a;
};
If I now define the function as
template<int N> void f(const myClass<N>& c){
std::cout << c.a;
};... | The problem is that the friend declaration friend void f(const myClass& c); is a nontemplate friend declaration. That is, you're actually befriending a nontemplae free function. This is exactly what the warning tells you:
warning: friend declaration 'void f(const myClass<N>&)' declares a non-template function [-Wnon-t... |
74,345,808 | 74,345,895 | How to print the current filename with a function defined in another file without using macros? | Is it possible to print the caller source file name calling a function defined in another file, without passing __FILE__ explicitly and without using preprocessor tricks?
// Header.h
#include <iostream>
#include <string>
using namespace std;
void Log1(string msg) {
cout << __FILE__ << msg << endl; // this prints... | You could use std::source_location:
// library.h
#pragma once
#include <source_location>
#include <string>
void Log(std::string msg, const std::source_location loc =
std::source_location::current());
// library.cpp
#include "library.h"
#include <iostream>
void Log(std::string msg, con... |
74,346,000 | 74,346,788 | C++ prevent ambiguous parameter int vs int& | I specalized QApplication as MyApplication taking an int parameter for construction.
class MyApplication : public QApplication
{
public:
Foo( int argc, char **argv ) : QApplication( argc, argv )
{
...
}
};
This class is again specialized in many places in my code.
Unfortunately, I used int, while I... | One approach is to wrap the parameters in your own structure and pass that. This forces subclass construction to use that signature.
It also allows more flexibility if for whatever reason you ever want to add additional stuff to the constructor without going and modifying everything. This technique is used in some APIs... |
74,346,252 | 74,564,620 | How to setup {fmt} library for Unreal Engine project? | I'm trying to setup fmt for UE4 project, but still getting compiler errors.
Used toolchain: MSVC\14.16.27023
fmt lib is build from source.
I googled this issue and undefined check macro.
#undef check
#include <fmt/format.h>
void test()
{
auto test = fmt::format("Number is {}", 42);
}
Getting this compiler errors... | There is two main problem with integrating {fmt} library in Unreal Engine.
global define for check macro. Some variables/function inside fmt implementation named "check". So there is a conflict.
Warning as errors enabled by default. So you have either disable this, or suppress specific warnings.
I ended up with this ... |
74,346,596 | 74,346,619 | How do i solve this "chicken vs egg" declaration issue? | New with C++ but been coding a lot of ObjC back in the day. So i thought i was smart trying to solve a cross reference issue with the old delegate pattern used widely in ObjC but only managed to move the issue it to another file .
Im trying to reach the invoker of the file by passing it as a reference, conforming to a ... | You can predeclare PeripheralViewController and then you can use a pointer to it:
class PeripheralViewController;
|
74,346,902 | 74,347,083 | Enter an If Statement Using Probabilities | I have the function mutateSequence that takes in three parameters. The parameter p is a value between 0 and 1, inclusive. I need two if statements, one that is entered with probability 4p/5 and another that is entered with probability p/5. How do I write the logic to make this happen?
Code:
void mutateSequence(vector<p... | There's a very straightforward way to do this in modern C++. First we set it up:
#include <random>
std::random_device rd;
std::mt19937 gen(rd());
// p entered by user elsewhere
// give "true" 4p/5 of the time
std::bernoulli_distribution d1(4.0*p/5.0);
// give "true" 1p/5 of the time
std::bernoulli_distribution d2(1.0*... |
74,347,061 | 74,347,269 | C++ read multiple optional inputs from std::cin | While trying to generate a simpleVM for learning C++, I faced following Problem:
So lets assume I want and Input of 10 C 222, where 10 would be the opcode (movi in this case), C a register and 222 a value. Thus 10 C 222 would store 222 into register C.
To get some Input, I am currently using
int runVM(){
int i, v; //... | One choice is to read the opcode and then decide what else needs to be done. This looks like
int runVM(){
int i, v; //opcode i, Value v
char n; //Register
int C = 1; // undefined in OP
while (true) {
std::cin >> i;
switch (i) {
case 0:
return C;
case 10:
std::cin >> n >> v;... |
74,347,125 | 74,347,201 | operator overloading() for a user-defined type in unordered_map | I was looking at this post C++ unordered_map using a custom class type as the key
I understand that we need to redefine equality and hash code for a custom type key.
I know how the operator overloading works in general.
However, what does operator() have to do with the hash code?
Does unordered_map internally evaluat... | The std::unordered_map uses an std::hash object to calculate the hash-values.
It will use the hash-object like a function, calling the operator() to do the calculation.
As a simple example, for an int key, it will be something like this:
int key = 123; // Or whatever value...
std::hash<int> hash_object;
auto hash_val... |
74,347,904 | 74,348,013 | How to get compiler to deduce parameters for function with `concept auto...` given initializer lists | I am trying to get the hang of C++20 concepts. I want to define a function taking an arbitrary number of Foo instances and have the compiler implicitly convert input arguments to Foo instances. The problem is that the implicit conversion does not seem to work if I use initializer_lists. The last line in the following c... | {..} has no types, and can only be deduced as std::ininitilizer_list<T> or T[N].
As alternative, you might use
void foos(std::initializer_list<Foo> foos){/**/}
with call similar to:
foos({42, {42, 42}, {}});
|
74,348,000 | 74,348,127 | cannot bind non-const lvalue reference of type 'int*&' to an rvalue of type 'int*' | I am aware that there are some questions similar to this one but I am a beginner in c++ and those examples were a bit difficult to comprehend for me. In my problem, I have a function called void selectNegatives(int*&,int&,int*&,int&). What this function does is it iterates over an input array, removes negative ints fro... | Case 1
Here we consider the case when int arr[] = {-45, 11, 6, 38, -12, 0};.
Here when passing arr as argument it decays(from int[6] to int*] due type decay but the problem is that this resulting expression is an rvalue(prvalue in particular) and since we can't bind an rvalue to a nonconst lvalue reference we get the m... |
74,348,362 | 74,348,420 | How to use smart pointers to store an | I have two classes. One class(Person) has a vector collection composed of pointers of the other class(Student). At run time, the Person class will call a method which will store a pointer to a Student class in the vector. I have been trying to do this with smart pointers to avoid Memory leak issues that can arise but I... | You don't need to use smart pointers here. Place the objects directly into the vector and their lifetime is managed by the vector:
std::vector<Student> collection;
collection.emplace_back(name);
|
74,348,398 | 74,349,366 | Makefile deferred compilation | I have a simple makefile with a variable for the compiler flags, it also contains some targets that modify that variable and append some flags.
My point with it is to be able to run, for example:
make debug perf
that would in turn add to the variable the flags required to build under that configuration. The problem is... | One approach is to have different executable files for different flag combinations, ie
executable # default to release build
executable.dbg # with -g
executable.perf # with -D__PERF__
executable.dbgperf # with both
The two advantages are
you're never unsure how some executable file was built, and you n... |
74,348,765 | 74,349,126 | Make alias to C types in C++ namespace | I have a DLL in pure C code. I would like to find a way to remove the library name prefix from the functions, classes, and structs; EX:
// lib.h
void foobar();
// lib.hpp
namespace foo {
bar();
}
I would like to avoid simply writing a wrapper for every function, since I'd have to write it for every time I want to... | Unless you are worried about name conflicts between existing C++ function names and the C library, how about just using extern "C" (in your C++ code) and call it (from your C or C++ code). For example:
extern "C" void f(int); // apply to a single function
extern "C" { // or apply to a block of functions
int g(do... |
74,348,968 | 74,349,113 | Can I obtain different results from iterative and recurive functions? | My code is supposed to calculate the 100th element of the sequence $x_0=1 ; x_i=\dfrac{x_{i-1}+1}{x_{i-1}+2}, i=1,2, \ldots$
I wrote iterative and recursive functions, but the results are not equal. Is it due to the lost of decimals?
Here is my driver code. The data from the file is i=100.
int main()
{
int i;
... | I the recursive function you do
(r(x-1) + 1) / (r(x-1) + 2)
With x == 1.0 that's equal to
(r(1-1) + 1) / (r(1-1) + 2)
That's of course equal to
(r(0) + 1) / (r(0) + 2)
And since r(0) will return 1 that equation is
(1.0 + 1) / (1.0 + 2)
There's no further recursion. The result is 2.0 / 3.0 which is 0.66667.
The iter... |
74,349,144 | 74,349,200 | How to re-throw an abstract class error from a catch block | I need to perform some action inside a catch block then throw the same exception I got:
#include <string>
#include <iostream>
class AbstractError {
public:
virtual std::string toString() const = 0;
};
class SomeConcreteError : public AbstractError { public:
std::string toString() const { return "division bt 0"... | This would throw a copy of e:
throw e;
but it's abstract so that can't be done. You need to rethrow the same exception:
throw;
|
74,349,658 | 74,351,903 | Parse a String in C++ and connect input-arguments to existing variables | I want to read an input string and connect their values to variables in my class.
Some example Inputs might be:
78 C 15.48
3 B
87 P 15
0
..
The first argument is an int from 0-100, second a char and third int or float. A String can consist of one, two or three arguments which are separated by space. After reading a li... | As Some programmer dude mentioned it is a good idea to use std::istringstream to convert values from string to other data types. It allows you to treat input string the same way as you treat std::cin. Here is a code snippet that you can use in your case:
#include <string>
#include <iostream>
#include <algorithm>
#inclu... |
74,349,900 | 74,353,445 | What is the role of struct data member aeron_udp_channel_transport_stct::bindings_clientd in Aeron C++ code? | The aeron_udp_channel_transport_stct::bindings_clientd is only found be used in aeron_udp_channel_transport_init function which set the bindings_clientd to NULL without further operations. Except some modification and assert in test cases.
In the test case, it is assigned as struct aeron_test_udp_bindings_state_stct, ... | TL;DR unless you are writing a custom network binding don't concern yourself with this field.
The Aeron C driver has support for adding different network bindings implementations (see aeron_udp_channel_transport_bindings_stct). In the OSS repo there is only support for traditional OS (Linux, Mac, Windows) networking. ... |
74,350,258 | 74,350,913 | using uninitialized memory warning and else in cpp | there is warnings in c++ i can't solve it
i have Visual Studio 2019
first i got error with #include "pch.h"
and 3 warnings
-using uninitialized memory : in processesSnapshot
`
while (Process32Next(processesSnapshot, &processInfo))
`
-argument conversion from 'unsigned __int64' to 'unsigned long', possible loss of d... | Your code has a number of problems. I'm going to look at one small section, and point out what look to me like obvious problems. Not sure if they're the source of the symptoms you're seeing, but ...
Process32First(processesSnapshot, &processInfo);
if (!strcmp(processInfo.szExeFile, ProcessName))
{
C... |
74,350,795 | 74,353,209 | How to store and process possibly duplicate distributed class coupling information in C++? | I'm writing a template<class ...Ts> class SortedTypeHolder. During compile time instantiation SortedTypeHolder must collect distributed information about all provided ...Ts from their headers for future sorting. The gathered information describes which classes depend on others in a form of template<typename A, typename... | Just use function declarations. You don't need to define them, can easily extract the parameter types, can have duplicate forward declarations with no problem, and get ADL for free.
void dependency(A, B, C, D); // A depends on B, C, D
or, if it's easier to use
std::tuple<B, C, D> dependency(A);
You'll need to either ... |
74,351,076 | 74,351,185 | How to initialize array elements with their indices | I would like to find an elegant way of initializing C++ array elements with their indices. I have a lot of code that looks like this:
static constexpr size_t ELEMENT_COUNT = 8;
MyObject x[ELEMENT_COUNT] = {{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}};
Where MyObject is effectively,
struct MyObject {
size_t mMyIndex;
... | It is impossible to intialize a built-in array like this. Arrays can only be default-initialized, value-initialized or aggregate-initialized (with exception for string literals). The only one of these allowing to specify different values for the elements is aggregate initialization and that requires explicitly listing ... |
74,351,419 | 74,351,621 | Should using the "new" keyword in the factories be avoided? | As I went through our codebase, I saw using the new keyword for memory allocation in almost every factory. It makes perfect sense, and is OK until the users are disciplined and assigning created instances to the smart pointers (that are forced by our CS, or at last do proper memory management).
But digging deeper, I fo... | The textbook solution is, of course, as πάντα ῥεῖ wrote: use a T::create() member function that returns either std::unique_ptr<T> or std::shared_ptr<T>, plus make ctors private; and that should work in most cases.
However, as you wrote, there are cases where you need an instance 'on the spot'. In such cases, the overhe... |
74,351,800 | 74,355,835 | Analyze the run time of the function below and assume worst case scenario (in terms of n) |
i think that the loops runs o(N) times and wanted to confirmed that and even to expanding knowledge over the steps.
Can anyone explain this?
| Let k be the least positive number such that 2^k > n.
Observe that your first iteration runs no more than 2^k times.
since, n < 2^k, n/2 < 2^{k-1}, hence your second loop runs no more than 2^{k-1} times,
third loop runs 2^{k-2} time, so on and so forth.
Total number of iterations can be upper bounded by 2^k + 2^{k-1} .... |
74,352,530 | 74,352,956 | Iterating over Variadic arguments | I'm sure this question has been asked before, but I can't seem to find something as simple as what I'm trying to do. Essentially, I just want to make sure the code triggers each parameter, calling any functions that may be sent as inputs. My biggest worry here is that optimizations may remove some of the calls, changin... | When you write
void AddObject(T);
template <typename... PARMS> AddObjects(PARMS&& ... parms)
{
PARAMS_EXPAND( AddObject(parms)... );
}
you're making a single top-level function call to PARAMS_EXPAND with sizeof...(PARMS) arguments.
What happens inside PARAMS_EXPAND is essentially irrelevant because, like every ot... |
74,352,686 | 74,357,587 | Conan import error in gitlab pipeline - Cannot load recipe | Here is the error getting during build-job in gitlab pipeline. This was initially working for days in the pipeline build and without any update in the code repository, import error started to happen. It would be nice if anyone can shed some light on it.
Conan version in the pipeline runner image is Conan version 1.51.3... | The export_conandata_patches is available since Conan 1.52.0.
You need to update your Conan client version:
pip install -U conan
Since Conan 1.52.0, required_conan_version is validated before parsing those imported modules, so it fail soon and validate your Conan client version first.
|
74,352,886 | 74,353,117 | PInvoke C++ dll from C# throws Exception | The project I am working on has a case where I have to read and display hardware info, for which they have a function written in a C++ DLL, and I am writing a C# stub to PInvoke it. I am fairly new to PInvoke, and hold beginner status in C# and C++ in general, as I mostly work in the Java space.
The issue here is that ... | Without concise details about which C++ compiler was used to make the DLL, what size its long data type is (may be 32bit or 64bit), what alignment settings are used, if any structure padding is present, etc, then a translation to C# is difficult. However, your C# code should probably look something more like the follo... |
74,353,155 | 74,353,258 | Side effect of volatile read/write of nullptr | I was watching this c++ lection (it's in russian).
At around 16:10 the lector asked an open question:
Having this code:
int* foo()
{
volatile auto a = nullptr;
int* b = a;
return b;
}
int main()
{}
Clang generates the following assembly for foo (-Ofast)
mov qword ptr [rsp - 8], 0 # volatile auto a... | The type of a will be volatile std::nullptr_t.
std::nullptr_t isn't really required to have any internal state, although it is specified to have the same size as void*. Only the conversion behavior is specified for this type.
There is no need for std::nullptr_t to store a value in the memory it occupies. All conversion... |
74,353,565 | 74,353,684 | Copy char to a array with a function - C++ | Function.h
void copyArray(char, char);
Main.cpp
void copyArray(char word[], char temp[]) {
for (int i = 0; i < 50; i++) temp[i] = word[i];
}
auther.cpp
copyArray("CHAMPAGNE", char myArray[50]);
Output
C2664 'void copyArray(char,char)': cannot convert argument 1 from 'const char [10]' to 'char'
already googled... | First: The declaration and definition don't match since the declaration specifies that the function takes two chars while the definition specifies that the function takes two char*:
void copyArray(char, char); // declaration
void copyArray(char word[], char temp[]) { // definition
for (int i = 0; i < 50; i++) temp... |
74,353,628 | 74,353,675 | Initialize const struct members from a static member function when class is initialized | I am experimenting with the const and static keywords and am getting stuck with my class design.
The class FileReader contains a struct Params with its own default constructor and a static method to initialize the member variables of the struct. The parameters in Params struct need to be initialized only once when the ... | You are doing the initialization in the wrong place. Once you've enter the body of the constructor all class members have already been initialized. What you need to do is initializer params in the class member initialization list like
FileReader::FileReader(const std::string& iniFilePath) :
params(Params::create... |
74,354,585 | 74,397,484 | How to avoid deprecated-copy warnings? | Here is some simplified code. It's not mine, but I'm adapting it for a project of mine. It's part of a sizeable codebase I'm importing, and which I don't want to change more than absolutely necessary.
void function (object& out_thing)
{
object thing;
#pragma omp nowait
for (int k = 0 ; k < 5 ; k++) {
object* things... | The warning -Wdeprecated-copy warns about a missing/deleted user-declared copy assignment operator, when there is the user-declared destructor ~object. If there is a user-declared destructor, missing a copy constructor or a copy assignment operator is likely the error in the code. You should add a custom copy assignmen... |
74,354,601 | 74,372,027 | Handing custom HINSTANCE to MFC Dialog | I am porting the GUI of a very old plugin from win32 to MFC. The dialog used to be started by invoking something like:
DialogBoxParam( GetDLLInstance(), ..., GetHWND(), ..., ... )
When trying to debug why my MFC solution doesn't work, I found, that above code would fail if I replace GetDLLInstance() by nullptr. So, fo... | AfxSetResourceHandle sets the HINSTANCE handle that determines where the default resources of the application are loaded.
As @RbMm said, you need to set before rundialog and restore instantly.
For Modeless Dialog Box,
HMODULE hPrevious = AfxGetResourceHandle();
AfxSetResourceHandle(hMod);
CMyDialog *pDlg = new CMyDialo... |
74,354,869 | 74,359,969 | Is asio::serial_port able to check physical disconnection? | I'm working with boost::asio library for serial communications, and got some problems using it. Below is my code with the problem.
std::unique_ptr<asio::serial_port> port_;
asio::io_service io_;
// Connect serial port 'COM8'
port_ = std::make_unique<asio::serial_port>(asio::serial_port(io_, "COM8"));
std::cout << port... | You can detect it when attempting a read/write operation:
E.g. from the exception overload of write_some:
boost::system::system_error
Thrown on failure. An error code of boost::asio::error::eof indicates
that the connection was closed by the peer.
|
74,355,562 | 74,355,579 | Why Obj.*A is out of scope? | Here is part of my class assign_obj, constructor and operator that I want to print the object.
When trying to compile operator I am getting error :
error: 'A' was not declared in this scope for(assign_obj::item anItem : obj.*A){
Why is that?
If I try obj.A instead, I get error for the forloop as C++ can not loop a poi... | You can't use a for loop that way for a dynamically allocated array. You can use a plain old for loop for your plain old array.
std::ostream& operator<<(std::ostream & out, assign_obj & obj){
out <<"[ ";
for (size_t i = 0; i < obj.size; i++) {
out << obj.A[i].value << ":"
<< obj.A[i].count <... |
74,355,714 | 74,355,874 | Correctness of multiplication with overflow detection | The following C++ template detects overflows from multiplying two unsigned integers.
template<typename UInt> UInt safe_multiply(UInt a, UInt b) {
UInt x = a * b; // x := ab mod n, for n := 2^#bits > 0
if (a != 0 && x / a != b)
cerr << "Overflow for " << a << " * " << b << "." << endl;
return x;
}
C... | To be clear, I'll use the multiplication and division symbols (*, /) mathematically.
Also, for convenience let's name the set N = {0, 1, ..., n - 1}.
Let's clear up what unsigned multiplication is:
Unsigned multiplication for some magnitude, n, is a modular n operation on unsigned-n inputs (inputs that are in N) that r... |
74,356,070 | 74,356,191 | C++ create an array with type of template base class without specifying the template argument | For example I have some base type Any
template<typename T>
class Any
{
public:
T data;
Any(T data) { this->data = data; }
// some other function signatures using data
};
class Number : public Any<int>
{
// functions defining all functions like substracting etc.
};
And more classes deriving Any
Now in ... | Let's say you have:
class A : public Any<int> { };
class B : public Any<std::string> { };
class C : public Any<double> { };
Objects of type A, B, and C are not subclasses of Any because Any is a template. Rather they are subclasses of Any<int>, Any<std::string> and Any<double>, respectively and as such do not share ... |
74,356,220 | 74,356,260 | Why is class with std::function argument in constructor not implicitly convertible to callable | Here is a simplified class I have:
class Event {
private:
std::function<void()> m_func;
public:
Event(std::function<void()> func)
: m_func(func)
{}
};
I cannot do implicit conversions on it:
void foo() {}
int main() {
Event evt = foo; //error
evt = []() {}; //error
}
Why is this? std::fun... | Because only one user-defined implicit conversion is allowed in one conversion sequence.
For Event evt = foo;, two user-defined conversions are required. One is from function pointer to std::function, one is from std::function to Event.
Similarly for evt = []() {};, one user-defined conversion is from lambda to std::fu... |
74,356,368 | 74,356,489 | C++ Reuse Lambda as Compare function in `std::priority_queue` | When working with std::priority_queue, I tried to clear the contents of the priority queue like this:
#include <iostream>
#include <queue>
#include <vector>
using std::cout;
using std::priority_queue;
using std::vector;
int main() {
const auto comp = [](int a, int b) {
return a > b;
};
auto a = ... | decltype(comp) is a const type, const auto comp, that makes the priority_queue member variable storing comp to be constant, thus can't be re-assigned.
You might want
priority_queue<int, vector<int>, remove_cv_t<decltype(comp)>>(comp);
Or
auto comp = [](int a, int b) {
return a > b;
};
The copy assignment operator... |
74,356,948 | 74,357,140 | How do I assign an object to passed nullptr? | Consider the following code:
struct MyObject {
std::string name;
};
void getOrCreateMyObject(std::shared_ptr<MyObject> myObj) {
if (myObj == nullptr) {
myObj = std::make_shared<MyObject>();
myObj->name = "Created Automatically";
}
std::cout << myObj->name << std::endl;
}
int main() {
std::shared_ptr... | Referring to this source:
There are two parameter-passing modes in C++: by value,and by reference.
When a parameter is passed by value, the changes made to the parameter within the function do not affect the value of the actual argument used in the function call.
When a parameter is passed by reference, changes made ... |
74,357,742 | 74,358,073 | Different results of std::isinf for different types and different compilers | Compiling with MSVC(v19.33), this does not compile (C2668 ambiguous call to overloaded function):
std::cout << std::isinf(0) << std::endl;
But this compiles:
std::cout << std::isinf(0.0) << std::endl;
However, in cppreference.com, it says:
A set of overloads or a function template accepting the arg argument of any ... | In the Microsoft's implementation, the definition of the isinf is as follows (copied from here):
template <class _Ty>
_Check_return_ inline bool isinf(_In_ _Ty _X) throw()
{
return fpclassify(_X) == FP_INFINITE;
}
The problem with Microsoft's fpclassify is the missing overload for integral types. For more details,... |
74,357,954 | 74,409,452 | Is there documentation for TfLiteTensor available | In the official documentation of tflite API for C++, many methods have TfLiteTensor or a pointer to such type as return value (e.g., input_tensor() method.. Is there any reference to which attributes and methods are available for TfLiteTensor class?
I looked in the official Tflite documentation, googled around and went... | TfLiteTensor is part of the TensorFlow Lite C API project and is a C struct (not a c++ class). I'm not seeing any way to generate documentation for it explicitly, nor do I see anything on line. The code API read me is located here:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/c/README.md
the TfL... |
74,358,078 | 74,416,017 | Missing binary operator before token "long" | I'm trying to implement FreeRTOS on my Arduino Mega 2560, and during this process, I came across 2 errors that I don't understand. And don't know how to fix. hopefully someone here does. the first error is missing binary operator before token "long".
The error points to the following line in FreeRTOSConfig.h:
#define c... |
missing binary operator before token "long"
This error occurs when you try to use the macro in a pre-processor directive. For example, compile the following C++ code:
#define configCPU_CLOCK_HZ ((unsigned long) 16000000)
#if configCPU_CLOCK_HZ > 0x1000
#endif
avr-g++ will complain:
*.cpp:1:39: error: missing binar... |
74,358,535 | 74,358,593 | Sorting strings from file to new file | This is my function to get lines from file to strings
void getStringsFromFile() {
ifstream database;
database.open("Database.txt", ios::app | ios::in | ios::binary);
if (!database) {
cout << "Kunne ikke indlaese filen..." << endl;
}
int count = 0, c = 0;
string getString, tmp, str[256];... | The getStringsFromFile function will read all lines from the file, and put them all into str[0]. Then the sortStrings function will attempt to sort a single string. There are other things that looks weird as well.
What I recommend you to do, is to create a vector of strings, read lines in a loop (the while (getline(...... |
74,358,789 | 74,360,530 | Section attribute within template | I'd like to ask why this doesn't relocate the data into the desired section,
template <typename T>
struct Retram {
static T data;
inline auto operator=(const T& other) {
data = other;
return *this;
}
operator auto &() const {
return data;
}
operator auto *() const {
return &data;
}
};
... | Gcc ignores attributes in templates generally. This is a know bug for many years now. There are more than 10 open bug reports related to this issue. See bugzilla. The problem affects not only member functions but also variable templates and free template functions.
Someone has started to work on it but after running in... |
74,359,033 | 74,359,322 | Does a object stores lambda function have it's own address? | Based on the result of this topic
A lambda which captures no variables (nothing inside the []'s) can be converted into a function pointer
I have written a program like
void test1(){}
int main() {
auto test2 = [](){};
printf("%p\n%p\n", test1, &test1);
printf("%p\n%p", test2, &test2);
return 0;
}
the r... |
Does a object stores lambda function have it's own address?
Yes, like all objects in C++ the variable test2 also has a unique address. You can see this by printing &test uisng cout as shown below:
int main() {
auto test2 = [](){};
std::cout << &test2; //prints address of test2
return 0;
}
Demo
The... |
74,360,237 | 74,360,656 | Does pthread mutex objects has to be volatile? | I'm learning pthreads after learning about regular threads. Normally when we use a boolean thread object we declare it as a volatile object like this: volatile bool thread_lock;. Do we need to do this on pthread objects as well, specifically on pthread_mutex_t when needed or does it handle it itself?
I've looked up int... |
Normally when we use a boolean thread object we declare it as a volatile object like this: volatile bool thread_lock;
This use of volatile has never been standard. Some platforms added these semantics to volatile as a regrettable and confusing extension.
More tedious details in another answer, but the short version i... |
74,361,182 | 74,361,210 | CMake - No rule exists to target | In Ubuntu, I have downloaded a third-party shared library (liba1.so), placed in /lib/extern/lib . The associated header files I placed in /lib/extern/include. My own header files are placed in /include/public/ and /include/private/ . And now (to test mylib) I want to link this in my main.cpp code, using CMake.
My struc... | Your imported files are relative to the source directory, not the build directory. You need to use CMAKE_CURRENT_SOURCE_DIR instead of CMAKE_CURRENT_BINARY_DIR when setting IMPORTED_LOCATION.
|
74,361,445 | 74,368,764 | Construct a std::variant out of a boost::variant | I'm trying to construct a std::variant out of a boost::variant. In practice, I'm trying to define a function with the following signature:
template <typename... Types>
std::variant<Types...>
boostvar2stdvar(boost::variant<Types...> input);
I've seen the answer to this question, but in that case it's converting a tuple... | As others have pointed out, you can visit all elements types and return the desired variant from there:
template <typename... Types> auto b2std(boost::variant<Types...> const& input) {
return boost::apply_visitor(
[](auto const& v) -> std::variant<Types...> { return v; }, input);
}
When used like this
auto... |
74,361,632 | 74,361,688 | error : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc; | Why does my code give this bad_alloc error, even though I have allocated enough memory? I'm not able to figure it out.
this is the problem link
Passing by reference did not resolve the error.
#include <bits/stdc++.h>
using namespace std;
#define ll long long
void dfs(ll root , vector<vector<ll>> &graph , vector<ll> &w... | dfs takes a copy of the vectors graph and a every time it is called recursively, and this probably exhausts your memory.
Pass references instead:
void dfs(ll root , vector<vector<ll>> const &graph , vector<ll> const &a , ll wt , ll &ans)
As a side note: is there a reason you return the result in a reference paramete... |
74,361,724 | 74,361,799 | Append a null terminator to a C++ string | In order to implement a client to some protocol that expects null-byte padding to a specific string, I implemented a functions that pads a string with a specific amount of null bytes:
string padToFill(string s, int fill){
int len = s.length();
if (len < fill){
for (int i = 0; i < fill - len; i++){
... | The append overload you're using accepts a C string, which is null-terminated (that is: the first null-byte marks its end).
The easiest way here is probably to use a different overload of append:
s.append(fill - len, '\0');
Note that this requires C++20. For older C++ standards, there's
s.resize(fill, '\0');
or ... |
74,362,449 | 74,362,914 | How to use MPI_Allgatherv on an std::vector of std::vector's? | I have a situation where every MPI process has a nested std::vector that needs to be shared among all other processes with MPI_Allgatherv. Here is a minimal example, where I define a 3x2 nested vector with simple entries (in this case the mpi rank).
#include <mpi.h>
#include <iostream>
#include <vector>
int main ()
{
... | Do you really need all the data gathered together? If so, a vector<vector<>> is usually not a good idea. Instead, wrap the data in a class where you store a single vector, with a 2D indexing function. Or you can use the C++23 mdspan.
If you absolutely absolute want that exact structure, you can use MPI_Type_create_hind... |
74,363,454 | 74,363,614 | How to minimize protocol buffer memory allocations for large # of messages? | My application uses protocol buffers and has a large number (100 million) of simple messages. Based on callgrind analysis, a memory allocation & deallocation is being made for each instance.
Consider the following representative example:
// .proto
syntax = "proto2";
package testpb;
message Top {
message Nested {
... | I would suggest using Arena allocations which were designed for exactly this purpose.
https://developers.google.com/protocol-buffers/docs/reference/arenas
Memory allocation and deallocation constitutes a significant fraction of CPU time spent in protocol buffers code. By default, protocol buffers performs heap allocat... |
74,363,513 | 74,369,217 | Changing utf encoding in visual studio (C++) | I am making a C++ console program that I would like be able to use some characters from my native language (like š, č, ž, ų, etc.). They all exist in UTF-16 encoding.
Is it safe to change my visual studio utf encoding to mentioned UTF-16 and how do I do it properly?
| I suggest you to use the following code, it can achieve your needs
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
int main() {
_setmode(_fileno(stdout), _O_WTEXT);
wprintf(L"ščžų");
}
|
74,364,396 | 74,364,632 | Get vector<Point2f> from cv::Mat | I am getting an input of vector of 2d points, make transformation on them and then output transformed vector of 2d points. My code needs to run fast so I want to optimize memory access time, is there a way to cast rotated_points to vector without copying the data?
std::vector<cv::Point2f> points =
std::vect... | std::vector<cv::Point2f> res_vec(points.size());
cv::Mat rotated_points(res_vec);
cv::transform(points_mat, rotated_points, rotation_matrix);
Create vector and pass it as argument to cv::Mat instance with copyData flag set to false (by default it is false cv::Mat ctor). cv::Mat
will just refer to vector data as underl... |
74,364,607 | 74,396,151 | Qt application hangs on process.start() function. Happens only when function is being called from QML script | I have Embedded Qt applicaiton runing on my HMI screen.
I am trying to execute some commands to execute in cmd.
I am calling this c++ function simply from QML.
Everytime I call it it hangs on process.start().
Do anyone have any experience for such issue? please help.
I have ceated a simple function to print out date an... | What I found on my side is, the issue was debug mode. If I create release and press the run button (Ctlr + R) then it is absolutely fine (Not the debug button but Run button on QtCreator). Without any changes to my code. I have no idea what that would make the difference on application though.
|
74,364,674 | 74,365,865 | Make a class befriend a family of functions | I have a class template
template <class Key, class T, class Hash, template <class> class Allocator>
class Table;
and a function template
template <class Key, class T, class DevHash, template <class> class DevAllocator, class HostHash, template <class> class HostAllocator>
void copyTableToHost(const Table<Key, T, DevH... | If you want it as a free friend function template, one option could be to befriend all instances of it:
template <class Key, class T, class Hash, template <class> class Allocator>
class Table {
template <class K, class Ty,
class Hash1, template <class> class Allocator1,
class Hash2, tem... |
74,364,825 | 74,386,653 | UDP port is not free after closesocket call (Windows) | I have two listening sockets (created by calls to socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)), at this moment they are maintained from one thread.
After creating, they have to be closed (closesocket(...)) and reopened again on the same ports. But bind(...) call returns error 10048 WSAEADDRINUSE on one of these sockets (... | I have found what caused this problem. The thing I have programmed is the DLL. I have discovered, that another DLL from this app is using QProcess class of Qt library version 5.7.1. I have checked sources of Qt and discovered that this class actually starts process with bInheritHandles set to TRUE. When I manually have... |
74,365,968 | 74,366,031 | How to return array of arrays, with different sizes form function | I'm trying to create array of arrays with different sizes and return it, so I can work with it later. Is it even possible? I was trying to do something like this:
#include <iostream>
int* fun(){
int a[] = {3, 2, 1};
int b[] = {5, 4};
int *arr[] = {a, b};
return *arr;
}
int main() {
int *array = f... | I would refactor to use std::vector instead of c-style arrays
#include <iostream>
#include <vector>
std::vector<std::vector<int>> fun(){
std::vector<int> a{3, 2, 1};
std::vector<int> b{5, 4};
return {a, b};
}
int main() {
std::vector<std::vector<int>> values = fun();
printf("\n%d, %d, %d", values[... |
74,366,093 | 74,366,268 | How to declare simple conversion operator T() in templated base class | I've been working on some class hierarchy with a goal to have a collection of classes that encapsulate primitive types (AdvancedInt, AdvanceDouble, etc.) and give them some additional behavior when accessing their underlaying values, through conversion operator and assignment operator. I can't do this with getters and ... | With adv = calc we look for operator= from AdvancedInt and found (implicit):
AdvancedInt& operator=(const AdvancedInt&);
AdvancedInt& operator=(AdvancedInt&&);
and look-up stops there.
Adding:
using Serializable<int, AdvancedInt>::operator=;
would allow to consider also that overload.
And that fixes your issue.
Demo... |
74,366,357 | 74,400,482 | Updating to Visual Studio 17.4.0 Yields linker errors related to TLS | I just updated my Visual Studio instance from 17.3.6 to 17.4.0. Then I tried a clean build of my solution. Suddenly one of my projects gives me linker errors
8>pch.obj : error LNK2001: unresolved external symbol __imp___tls_index_?init@?1??lazy_init_num_threads@internal@at@@YAXXZ@4_NA
8>pch.obj : error LNK2001: unre... | The name mangling appears to point to at::internal::lazy_init_num_threads, which is a PyTorch function (a bit weird, but it might very well use thread-local storage). You may need to rebuild PyTorch with the same toolchain
|
74,366,438 | 74,366,598 | c++ function that accepts ostringstream like arguments? | Is there a way in C++ to define a function so that I could do things like this:
foo( "Error on line " << iLineNumber );
foo( "name " << strName << " is Invalid" );
as it is now, I'm having to declare an ostringstream object before I call the foo function like this:
std::ostringstream strStream1;
ostringstream1 << "Err... | The compiler is not able to deduce that you want your expression to be converted to std::ostringstream. You can get around this by explicitly providing one to the arguments, which you can do inline with the function :
#include <sstream>
#include <string>
void foo(std::ostringstream osstr)
{
// Use the stream
}
in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.