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 |
|---|---|---|---|---|
63,058,351 | 63,059,750 | Problem with counting total items in array | I wanted to get a count of total items in the array. So, here's what I made.
#include <iostream>
using namespace std;
int countIt(string arr[]){ //function which counts array and returns count
int count = 0;
while(arr[count] != "\0"){
count++;
};
return count;
};
int main() {
string vehicle[... | I will recommend you to use vectors
vector<string> arr;
arr.push_back("volvo");
arr.push_back("car");
cout<<arr.size();
expected output is 2
But in your question the expected output was 1 i assuming {car , volve} is one element for that you can use
vector<string,string> arr;
arr.push_back(std::make_pair("volvo","car... |
63,058,494 | 63,061,689 | How can an Admin User save a file as a Standard User | So I have a program that saves a text file to the C:\ProgramData\MED folder
std::filesystem::path fileName("C:\\ProgramData\\MED\\Data.txt");
int ret(0);
FILE *fp;
ret = _tfopen_s(&fp, fileName.c_str(), _T("w"));
if (ERROR_SUCCESS == ret)
{
_ftprintf_s(fp, _T("1 = Type\n"));
_ftprintf_s(fp, _T("MED = Name\... | Remy you are my hero. It was very easy to modify the SECURITY_DESCRIPTOR. I added just one line of code:
std::filesystem::path fileName("C:\\ProgramData\\MED\\Data.txt");
int ret(0);
FILE *fp;
ret = _tfopen_s(&fp, fileName.c_str(), _T("w"));
if (ERROR_SUCCESS == ret)
{
_ftprintf_s(fp, _T("1 = Type\n"));
_ftprint... |
63,058,583 | 63,058,763 | Class inside namespace and set function outside in C++ | In this task i need to set and get number of soldiers outside of class and namespace (and call it in main properly)
namespace GeneralStaff
{
class Troops
{
private:
int nSoldiers;
public:
string name;
string rank;
Troops(string _name, string _rank, )
{
name= "Unknown";
rank= "... | To define a method of the class outside the class, just use the scope resolution(::) operator. But for defining a function outside the class, you need to declare it in the class itself, which you have not done. Check the following code, it should work:
namespace GeneralStaff
{
class Troops{
private:
... |
63,058,664 | 63,058,703 | incomplete type not allowed, function dec/def and no classes | So i keep getting an "incomplete type not allowed error" on the emphasized call of function "out" on this and ive switched the function decs around, and i decided to not move on until i have this figured out because i can't find any non-class examples that aren't completely analogically opaque. Noob question but any he... | This:
int main(){
void out( fib( input() ) ); // error here
}
is interpreted to something like an instantiation of a variable of type void calling the constructor that accepts a int as first parameter,
instead you probably want this:
int main(){
out( fib( input() ) );
}
that is just a functio... |
63,058,704 | 63,107,787 | Childwindow inside MainWindow shows for a second then disappears | I have MainWindow instance and inside I want to create a bunch of child windows which are the instance of GemWindow Class I do so by
for (unsigned int i = 0; i < win.GetcGem(); i++)
{
for (unsigned int j = 0; j < win.GetcGem(); j++)
{
if (!win.Gems[i][j].Create(L"gem", WS_CHILDWINDOW... | You can modify the background color through the SetClassLong function without processing the WM_PAINT message.
Only need to modify the code as:
for (unsigned int i = 0; i < GetcGem(); i++)
{
for (unsigned int j = 0; j < GetcGem(); j++)
{
if (Gems[i][j].Create(L"gem", WS_CHILD | WS_VISIBLE, NULL, 5 + i *... |
63,059,516 | 63,059,790 | Is default initializing class members always advisable? | It's general advice to avoid getting uninitialized members in a class/struct. Consider the following example.
struct Foo
{
Foo(){}
int bar;
}
To follow the advice, I have to explicitly initialize bar (e.g. int bar{};).
But what if I always initialize the member by assigning a value to it right after constructi... | Initializing member variables leads to more stable and predictable class operation; there's no possibility of having the object in an unknown or inconsistent state. On the other hand, certain operations can be relatively slow, and if you know your program logic won't leave the members uninitialized for long you can ce... |
63,059,930 | 63,062,259 | Runtime error - Heap use after free on address | I am stuck on a question and cannot figure out why i am getting runtime error heap use after free.I read about it that when we free some memory then acess it with the pointer this error may arise but here in my code i am not freeing anything so why does this error arise.
Let me explain i have a linked list of 3 nodes 0... | After a long chat, we found that he was changing and breaking the links in the original linked list causing the free code to fail after completing. I advised him to be sure to either return data to original form or at least make it so that every node in the list could be visited when complete.
|
63,060,211 | 63,062,997 | attempted relative import beyond top-level package with boost/Python | I've tried multiple ways to import a module in a post here, but I decided to post a new question since that post was about boost not being able to find the module. Here's the structure of the folder:
project
|__ utilities
| |__ foo.py
|
|__ boost_extensions
| |__ myclass.cpp
| |__ mycla... | I posted a similar question and the solution for that works here too (it was about trying to import a python module in C++ by using a relative path, I made a different post about it because it gave a completely different error). Basically I loaded the module in python and passed it as an argument to C++.
|
63,061,188 | 63,061,627 | What are the rules for standard library containers and incomplete types? | Given an incomplete type:
struct S;
Then the following declarations are:
S *p; // ok, pointer to incomplete types is allowed
std::deque<S> l; // error, instantiating std::deque with incomplete type is UB
But what about the following declarations?
std::deque<S> *p; // seems to be UB like the previous c... |
std::deque<S> *p; // seems to be UB like the previous case,
// but is it ok if p is not used till S is defined?
That's actually the interesting bit here. Yes, instantiating that container with an incomplete type is not allowed, there is no provision for it. But the question becomes whether or n... |
63,062,118 | 63,062,349 | C++ Error: Expression Must Have Bool Type | First off, I want to say that I know this issue has come up before on StackOverflow. However, I am still having an issue with my code.
Roster* classRoster = new Roster(numStudents);
cout << "Parsing data and adding students" << endl;
for (int i = 0; i < numStudents; i++){
classRoster->parseAdd(allStudentData[i]); ... | Make your remove member function return a bool value. Let it be 'bool remove(string)' instead of void.
Right now 'classRoster->remove("A3")' dosent return any value. Make it return something and you will fine.
|
63,062,183 | 63,063,176 | How can one simply handle a table in C++? | I want to be able to handle something like a table in C++. I mean table as in "excel spreadsheet" or "R dataFrame". My solution need not be that powerful, however. I do not need to add columns at runtime, but I will be adding rows to create averages. I am building this table from individual data points, and this table ... |
My solution need not be that powerful
You can save the same data in multiple data structures, it's surely not the most efficient approach but if you have enough space and accessing the data is more critical - it's worth considering.
It is important that I be able to access the data based on any property so that I ca... |
63,062,341 | 63,062,643 | User defined conversion and template member question | I'm using the following example from Stroustrup C++ 4th Ed Page 764-765. I'm a bit confused on it's behavior and looking for guidance.
First, why doesn't Ptr<X> xp2 = py; compile, when there is a user defined conversion template function? FYI, I added this to the example.
Second, why does Ptr<X> xp{py}; invoke the us... |
First, why doesn't Ptr<X> xp2 = py; compile, when there is a user defined conversion template function? FYI, I added this to the example.
This requests implicit conversion to Ptr<X> but there is no implicit conversion operator. The conversion operator is declared explicit so it is not a candidate.
Second, why does P... |
63,062,379 | 63,062,401 | How can ignore some elements of tuple? | I have a tuple with some elements, and I want to assign some elements of tuple to variables, and ignore some of them.
auto tuple1 = std::make_tuple(1,2,3,4);
// variable a should be placeholder 1 in tuple and variable b should be place holder 3;
int a,b ;
| You could use from std::tie and std::ignore in tuple such as :
int a, b;
tie(std::ignore, a, std::ignore, b)= tuple1;
|
63,062,631 | 63,063,161 | Variadic template function rvalue parameters silently moved C++ to the function | The following code compiles and prints: move move. I would prefer that it didn't compile since merge takes rvalue references and I don't move t1 and t2 to it.
class A {
public:
A() = default;
A(const A& other) { std::cout << "copy "; };
A(A&& other) { std::cout << "move "; };
};
template <typename... Tu... | For why is this possible, See Reference_collapsing.
Now If you want to prevent your function from accepting lvalues, you can use the following code
#include <tuple>
#include <iostream>
class A {
public:
A() = default;
A(const A& other) { std::cout << "\ncopy "; }
A(A&& other)noexcept { std::cout << "\nmo... |
63,062,721 | 63,101,200 | CLR Application not starting | I have spent now some days trying to resolve this one. My problem is that my developed Application won't start on other systems. There is no error message, nothing.
To be more specific, i have developed an application accessing native C/C++ librarys provided by a manufactorer. Therefore in my solution i have my WPF App... | Thanks @drescherjm. The Redistributable was already installed but indeed i needed to build the release version. Now it works.
@dxiv The Documentation is very poor on that api. I had lot of other issues and seems like other people too. Recommendation was to not use this library in other threads :D :D
Thank you both for ... |
63,063,047 | 63,063,080 | Error when erasing an object element of a vector when operator overloading is defined | In the simple example program below, I have a vector of objects t_cell which I initialize with 5 elements. I also have a test vector of integers.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
class t_cell {
public:
int id;
t_cell operator = ( const t_cell &rhs_cell ){
... | The purpose of operator= is to change *this to match the state of the operand and then return a reference to *this, but that's not what you're doing -- instead, you are creating a new value and returning it. The returned value is promptly discarded by the caller, and so invoking the operator doesn't have any observabl... |
63,063,697 | 63,075,109 | Convert a QString to a const char* | For the purpose of creating a custom exception class, I need to convert a QString to a const char*. Here's the main code of the aforementioned class:
// File "Exception.cpp"
const auto MESSAGE_PREFIX = QStringLiteral("Exception ");
Exception::Exception(const char* file, int line, const QString& cause)
: m_Message... | Your problem is that you are returning an invalid pointer:
const auto ba = m_Message.toLocal8Bit(); // here you create a bytearray
return ba.constData();//here you take the pointer to the data of the bytearray
//then you destroy the array, hence the pointer.
//then you return... |
63,063,835 | 63,064,811 | Why is my sound file not being found when I run my program from the desktop? | I am making a simple snake game with SFML and am currently trying to add a sound that plays whenever the snake "eats" one of the dots. So I downloaded a sound file and put it in my project directory and added this to my code:
sf::SoundBuffer buffer;
buffer.loadFromFile("Crunch.wav")
sf::Sound crunch;
crunch.setBuffer(b... | loadFromFile() looks in the current directory, when you build and run in visual studio the directory is ProjectName\ProjectName by default, in this case it seems you have Crunch.wav in the ProjectName\ProjectName folder alongside the .vcxproj file, so you should make sure to keep Crunch.wav with the .exe in the same wa... |
63,063,876 | 64,394,978 | Evaluate infix string expression consisting of only addition and multiplication | How can I evaluate an infix string expression which only consists of + and * operators. (No parenthesis).
Example 1:
Input: "1+2*3"
Output: 7
Example 2:
Input: "1+2*3+4"
Output: 11
Here is my code I have so far (which is not giving correct result), I wonder if I can do it with one stack (or none)
int evaluateExpres... | int evaluateExpression(string s) {
string token = "";
char currOperator = '+';
stack<int> st;
string temp = s + '.';
for(const char &c : temp) {
if(isdigit(c)) {
token += c;
}
else if(c != ' ') {
... |
63,064,119 | 63,064,345 | C++ Macro takes proceeding code to be out of namespace | Currently I have a program which need attribute packing for numerous functions. The code must be interchangeable between Windows Visual Studio C++ and GCC C++. Currently it is very hard to read and I wanted to clean it up with a C++ macro, however, I noticed that after I use the macro once, the next lines of code exit ... | There is no need to typedef a struct declaration in C++. That is only needed in C, if you don't want to use the struct keyword every place a struct type is used (variables, function parameters, etc).
In Visual Studio, it would be easier to just put a single #pragma pack(push, 1) before the first struct declaration, an... |
63,064,549 | 63,064,592 | Sorting class array in ascending order | Quite new to programming and in need of some help, I'm looking to sort an class array in ascending order based on age, but I can only get the code to work in descending order. I may be overlooking something small since I've worked on this far too long so I'd appreciate any help!
#include <iostream>
#include <string>
us... | int sort(family[4].getAge()); is not a function declaration (and you can't implement a function inside of another function). It is actually a variable declaration. It is declaring a variable int sort that is initialized with the value from family[4].getAge() (which is undefined behavior since index 4 is out of bounds... |
63,064,932 | 63,064,959 | Is there multiple ways to cin vector elements? | I have a program that adds multiple vectors in 1 vector. I saw a method of instead of .push_back to add elements and I used it, but I am wondering why this works because I thought vector[] indicated the index, so why is cin >> vector[] adding elements into the vector if square brackets indicate the index?
input - outpu... | vector<int> q2(2) makes a vector q2 that has 2 default-constructed int elements in it. You don't need to push_back() elements, because it makes 2 elements for you when it is constructed.
cin >> q2[b] merely edits the int elements that already exist in the vector.
|
63,065,076 | 63,065,143 | Win32 window not redrawing when controls are updated | I am new to win32 programming, so I apologize in advance. I have a window with 2 problems that seem related.
if I resize a window, it leaves a portion of the background black, or all of it if I minimize.
I have a SysLink that when clicked calls ShowWindow to hide itself and shows a hidden combobox control. The combobo... | The window class is registered without a background brush. To fix that, and the repaint along with it, add (for example) the following before RegisterClassW.
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
|
63,065,338 | 63,065,363 | Compiler fails to recognize a templated class | This is a very stripped-down version of some code I have that fails to compile.
template <typename name_of_type_t> class classA_t
{ /* etc etc etc */ };
template <typename name_of_type_t> class classB_t
{
public:
classA_t<name_of_type_t> && return_new();
};
classA_t<name_of_type_t> && classB_t::return_ne... | classB_t is a template. When declaring its member function out of the class definition, you need to declare the template parameter list again, and specify the template parameters in the class type, e.g.
template <typename name_of_type_t>
classA_t<name_of_type_t> && classB_t<name_of_type_t>::return_new()
{
classA_t... |
63,065,710 | 63,066,066 | Use of & operator in C++ Range Based Loop ..Confusing | char SArray[6]={'a','b','c','d','e','\0'};
for(char n: SArray) {
n = 'R';
}
for (int i =0;i<7;i++) {
cout << "Slot " << i << ":" << SArray[i] << endl;
}
Slot 0:a
Slot 1:b
Slot 2:c
Slot 3:d
Slot 4:e
Slot 5:
Slot 6:R
If loop is written this way for(char n: SArray), C++ puts 'R' After the array, to the next address(... | My suggestions are:
First learn references & operator. But let me try to explain in a simple way than we can go more complex and explain the loop.
& represents reference and in simple terms references is different name for the same variable. For example
int a = 5;
int& b = a;
b is different name for a. Next example:
i... |
63,065,783 | 63,065,930 | How to compare using base class in derived class data | I have base class and derived class in C++.
I want to determine if the data of the derived class is the same using the pointers of the base class.
enum type
enum class FruitType: int{
Apple,
Orange,
};
base class
class Base{
public:
Base(FruitType t): fruit_type(t){}
FruitType fruit_type;
};
derived c... | You could add an abstract method sameData() to the base case
class Base{
public:
Base(FruitType t): fruit_type(t){}
FruitType fruit_type;
virtual bool sameData(const Base& other) const = 0;
};
Override in the derived classes:
class Apple : public Base{
public:
Apple(int i): Base(FruitType::Apple), foo(... |
63,065,887 | 63,065,961 | Loop logic, stuck inside a infinite loop | The following loop acts like a lock, it only accepts certain user input values for the program to continue.
I want to exit the while loop when selection has the either of the following values: "X","x","Y","y" . In the following I have programmed it to do so but when testing the code and entering those values, the loop ... | while( selection != "X" && selection != "x" && selection != "Y" && selection != "y"){
cin >> selection;
}
Since you were using the or(||) in order for that entire statement to evaluate to false all of the individual statements would need to be false. You need to use an and(&&) since then the entire statem... |
63,066,309 | 63,066,494 | Why can I not assign a memory address number to a pointer? | We know a pointer has a name and a value, the essence is variable, the value is hexadecimal number which is a memory address.
int a = 10;
int * p = &a;
cout << p << endl; // 0x7ffee04fe2b8
int * q = 0x7ffee04fe2b8; // why can not assign address number to the pointer `q`?
If I assign 0x0, it works:
int * q = 0x0... | In the C language you CAN assign addresses from constants. It is not a good idea. But you can do it.
Example compiler error:
$ cat c-ptr-test.c
int main() {
long *p = 0x0011223344556677;
return 0;
}
$ make c-ptr-test
cc -Wall -W -pedantic -g -O3 -flto -fno-fat-lto-objects -pthread -MMD -std=c11 -pthread -flto -f... |
63,066,454 | 63,066,515 | Initialize C++ struct that contains a fixed size array | Suppose I have a POD C struct as so:
struct Example {
int x;
int y[10];
int yLen;
}
With the following code, the program doesn't compile:
Example test() {
int y[10];
int yLen = 0;
auto len = this->getSomethingLength();
for (int i = 0; i < len; i++) {
y[yLen++] = this->getSomething(... | Declare the structure as a whole instead of its parts and then initialize it:
Example test() {
Example result;
auto len = this->getSomethingLength();
for (result.yLen = 0; result.yLen < len; result.yLen++) {
result.y[result.yLen] = this->getSomething(result.yLen);
}
return result;
}
Decla... |
63,066,840 | 63,070,416 | Recursive Binary Search Function | int binarySearch(int a[], int low, int high, int x)
{
if (high >= low) {
int mid = low + (high - low) / 2;
if (a[mid] == x)
return mid;
if (a[mid] > x)
return binarySearch(a, low, mid - 1, x);
return binarySearch(a, mid + 1, high, x);
}
... | The answer is yes, it is tail recursive. It doesn't do anything with the results of each of its recursive calls, except directly returning those results right away.
This means you could replace it with a loop which would update the low and high variables while looping until the stopping condition is met. The a and x va... |
63,066,970 | 63,067,185 | how to terminates all the preallocated threads in a threadpool? | I have used below structure to create a threadpool, now the question is how do I let all the preallocate threads end properly?
std::vector<pthread_t> preallocatedThreadsPool; // threadpool
std::queue<int> tcpQueue; // a queue to hold my task
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_... | TLDR: You just need a thread-safe variable that all threads can check for an exit condition in between work items. Use pthread_join to wait for a thread to exit.
First, let's get the while loop in your thread function correct with respect to condition variables.
Instead of this:
pthread_cond_wait(&condition_var, &m... |
63,067,265 | 63,082,198 | Is it possible to create consecutive OR statements using Z3 expr_vectors? | I'm trying to create a constraint such that a value X is one of the members of the expr_vector such as,
context c;
expr_vector v(c);
expr x = c.int_const("x");
expr i1 = c.int_val(5);
expr i2 = c.int_val(7);
solver s(c);
s.add(x == i1 || x == i2); // this is what I want to create iteratively
I tried to create an expre... | This functionality is provided by the z3 API, and is called expr_mk_or, available here
You can also implement this as a loop: Start with a boolean-expression initialized to false, and in each iteration use the or combinator to string them together. If you post what you tried, we can point out what you might've done wro... |
63,067,409 | 63,067,655 | C++ static array initiation: does inline initialization reserve space? | In C++, are the following two declarations equivalent?
static volatile uint16_t *ADCReadings = (uint16_t[64]){0};
or
static volatile uint16_t ADCReadings[64] = {0};
I'm reserving space for a buffer used inside and outside an ISR on AVR. But, though it would be interesting, I'm not looking here to know if this is the ... |
Are the following two declarations equivalent?
No. (uint16_t[64]){0} is a temporary array (a compound literal*), and if you try to compile the first line, you'll get a self-explanatory warning/error:
warning: temporary whose address is used as value of local variable 'ADCReadings' will be destroyed at the end of the... |
63,067,985 | 63,068,467 | Arithmetic Template Swap faster than std::swap? | I looked around and combined a basic temporary variable swap with a type template restricted to arithmetic types. Why is this faster than std::swap?
template <typename T, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
void swp(T& x, T& y) {
T t = x; x = y; y = t;
}
Here is the specific imp... | Take a look on assembly of this simple code, when optimizations are enabled (-O2).
#include <algorithm>
int foo(int a, int b) {
for(int i = 0; i < 100000000; i++) std::swap(a, b);
return a;
}
template <typename T, typename std::enable_if<std::is_arithmetic<T>::value>::type* = nullptr>
void swp(T& x, T& y) {
... |
63,068,212 | 63,068,512 | why loop is skipping input in first iteration? | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
main function
int main(){
long long int T;
string s;
cin >> T;
while(T--){
getline(cin, s);
cout << s << endl;
}
}
while loop skipping input on first iteration
only printing blank lines
I want pass string as input on... | cin >> T reads to the end of the number and not to the end of the line.
So with the first getline(cin, s); you read the rest of the line after the number.
You can call cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); right after the cin >> T; to ignore everything that is left in that line.
|
63,068,559 | 63,068,836 | Splitting a string into two different vectors C++ | I'm trying to split a string into two different vectors. However, I can't for the life of me figure out what I'm doing wrong.
I have a whole bunch of strings that I'm passing through (parsing through from a .txt file) that looks like this:
01 Sam
02 Pam
03 Lam
04 Ham
I'm trying to pass them into two different vectors
... | Splitting data by spaces is exactly what operator>> does when you read a string. No need for the extra getline, your loop can be simplified to something like this:
std::string numberBuf;
std::string nameBuf;
while(linestream >> numberBuf >> nameBuf) {
numbers.push_back(numberBuf);
names.push_back(nameBuf);
}
... |
63,069,329 | 63,138,033 | I am trying to install cudf from source for conda, I cannot use cmake to install it | I am trying to install CUDF from its source file as given in the page (https://github.com/rapidsai/cudf/blob/branch-0.15/CONTRIBUTING.md#setting-up-your-build-environment )
After the following few steps, I cannot complete it by doing the cmake
Build and install libcudf after its dependencies. CMake depends on the nvcc... | Please note that cudf 0.15 does not support CUDA 10.0 and python 3.6.
It seems to be a CUDA/permissions issue.
Did you install/ build your conda env as root and now you are trying to run build as a user?
What is your output for nvidia-smi?
Also if you have the CUDA toolkit installed and the env's cuda version matches t... |
63,069,817 | 63,071,026 | c++ should I prefer union or exception | I have a use case of unions, but as many programmers I quite find it ugly to use unions. So I tried using exception handling not in the way it is meant to be. I understand that this will introduce some loss of time due to handling of exceptions. My question is : is there a clean way to do that ?
here is the code, with ... | I'd strongly suggest against using exception for this, it's error-prone, and not what they are meant for.
One of the issue would be extensibility. Using exception, say you add one type, you have to be sure you've add it to your try-catch statement. Moreover, it's a bad habit, because it break the usual code flow. (say ... |
63,069,934 | 63,070,020 | friend class and the scope of function arguments | I'm writing a reflection utility for self usage, I simplified the code(remove complicated templates) as below:
class A {
private:
friend class Field;
int i;
};
class Field {
public:
Field(int A::* p) : p(p) {}
private:
int A::* p;
};
Field field(&A::i);
the compiler complains about i is private of class ... | In the line
Field field(&A::i);
you are accessing a private data member pointer (&A::i) from within a toplevel scope. This is not related to the class Field being a friend of A. What you could do instead, is giving friend access to a function that is supposed to instantiate Field objects, e.g.
class Field;
class A {
... |
63,070,090 | 63,070,145 | when we call function, is argument parenthesis () is needed if no argument pass like func; vs func(); | The static function getROI always returns 1 and also causes a warning :
the address of 'static float Account::getROI()' will never be NULL
#include <iostream>
using namespace std;
class Account
{
private:
int account_no;
int balance;
static float ROI;
public:
void setBalance(int x){balance=x;}
i... | It says the address will never be zero.
Which is true ... if the address were zero, reading it would be de-referencing a null pointer.
So you think you're looking at the data, but you're really looking at a pointer to the data, and (I presume) comparing that address to zero.
|
63,070,174 | 63,076,676 | boost::python how to use function member as python callback | I want to use this python module: https://python-omxplayer-wrapper.readthedocs.io/en/latest/ on my c++ app.
It is a omxplayer python wrapper and has some callback events that I want to link to my c++ class function member.
I did it with success using a static function like this:
void foo(py::object player) {
std::... | Ok, with @pptaszni help I found how to do it.
The problem was that boost could not detarmine the function signature because boost::bind return a function object.
To avoid this problem, I have to specify the signature when call make_function.
Example:
pyOMXPlayer.attr("pauseEvent") = py::make_function( boost::bind(&OMXP... |
63,070,449 | 63,070,633 | Read binary file into struct and also problems with endianness | I want to read a binary file image.dd into struct teststruct *test;. Basically there are two problems:
1. Wrong order because of little / big endian.
printf("%02x", test->magic); just gives me 534b554c instead of 4c55b453 (maybe this has something to do with the "main problem" in the next part). Its just "one value". ... |
You must allocate the structure and read data into the structure instead of reading into an pointer directly. If you are going to read only one structure, you won't need to declare pointers for the structure.
printf("%x ", test->magic); invokes undefined behavior because pointer (automatically converted from the array... |
63,071,550 | 63,076,914 | SDL2_image rendering - Images render properly only when source SDL_Rect's properties are printed | My C++/SDL2 program uses a Sprites class with a std::map of pointers to SDL_Textures and member functions for loading and rendering images, however when the program ran none of the loaded images showed up in the window.
I've found that the Sprites instance is given a correct pointer to the renderer and IMG_LoadTexture ... | Your SDL_Rect is not correctly initialised. Printing "fixes" it, but only by chance.
Your SDL_QueryTexture allows you to initialise w and h, but x and y have completely random values. As to why EXACTLY printing the values fixes things is beyond me, but I suspect that the random values don't go well with SDL_RenderCopy ... |
63,071,555 | 63,072,581 | compiler error when casting uint64_t to struct | I'm getting following error:
error: no matching function for call to ‘ab::ab(uint64_t)’
ab looks like this:
struct ab {uint32_t a; uint32_t b;} __attribute__((packed));
Why can't I cast uint64_t to ab?
os: Linux 5.7.9-arch1-1 x86_64
compiler: g++ (GCC) 10.1.0
|
Why can't I cast uint64_t to ab?
Because uint64_t is not convertible (even explicitly) to ab.
If you want a to contain the bytes in lower memory addresses, and b to contain the bytes in higher memory addresses1, then you can do:
ab a = std::bit_cast<ab>(some_uint64_t);
std::bit_cast is introduced in C++20. Prior to ... |
63,072,518 | 63,178,109 | QMediaPlayer::position() return zero | I was trying to get position of current media like that:
player->setNotifyInterval(500);
connect(Player::player, &QMediaPlayer::positionChanged, this, &Player::ChangedPosition);
void Player::ChangedPosition(qint64 position)
{
Player::currentPosition = position; //qint64 variable
//currentPosition still 0
... | need to use this pointer if I create object like that: player = new QMediaPlayer(this);. Wrong example:
connect(Player::player, &QMediaPlayer::positionChanged, this, &QMediaPlayer::setPosition);
Constructor of the correct class:
Player::Player()
{
try
{
player = new QMediaPlayer(thi... |
63,072,580 | 63,073,441 | Problems with wrapping Lua into a C++ class | I'm using the Lua C API in C++ and I'm wrapping it into a class as follows:
class LuaScripting {
public:
lua_State *lua;
LuaScripting();
~LuaScripting();
bool execute_script(const std::string &script);
};
LuaScripting::LuaScripting() {
lua = luaL_newstate(); /* Opens Lua */
luaL_openlibs(lua... | That's because you are copying the LuaScripting object. I bet testWritingInt8 is declared like this:
void testWritingInt8(LuaScripting lua)
Notice the lua parameter is not a pointer or a reference to a LuaScripting object, it is a LuaScripting object.
So when you call testWritingInt8(lua), the computer copies the LuaS... |
63,072,582 | 63,073,640 | Why the function is failing in case of numbers greater than 48 digits? | I am trying to find
(a^b) % mod
where b and mod is upto 10^9, while l can be really large i have tested upto 48 digits with success
using this relation
(a^b) % mod = (a%mod)^b % mod
#define ll long long int
ll powerLL(ll x, ll n,ll MOD)
{
ll result = 1;
while (n) {
if (n & 1)
... | It does not work because it is not mathematically correct.
In general, we have that pow(a, n, m) = pow(a, n % λ(m), m) (with a coprime to m) where λ is the Carmichael function. As a special case, when m is a prime number, then λ(m) = m - 1. That situation is also covered by Fermat's little theorem. That's only a specia... |
63,073,014 | 63,074,640 | Using enable_shared_from_this in polymorphic inheritance with virtual destructor | I have the following class structure for Managing callbacks with different prototypes:
class MethodHandlerBase: public std::enable_shared_from_this<MethodHandlerBase>{
public:
virtual void operator()(void* data) = 0;
virtual ~MethodHandlerBase(){}
};
class MethodHandlerA: public MethodHandlerBase{
private:
... | Some minor points:
You could move the shared pointer into the lambda to avoid an atomic increment and decrement
No need to use a dynamic pointer cast since you know for sure the dynamic type (plus you don't check the result is not empty anyway!)
void MethodHandlerB::operator()(void* data){
auto thisPtr = std::sta... |
63,074,779 | 63,075,031 | Error request for member '.......' in '......', which is of non-class type '.....' | for(i=0;i<x;i++)
{
for(j=0;j<i;j++)
{
if(bor.hasil[i]<bor.hasil[j])
{
bor.n[i].swap (bor.hasil[j]);
tmp=bor.hasil[i];
bor.hasil[i]=bor.hasil[j];
bor.hasil[j]=tmp;
}
}
}
how to fix error request for member 'swap' in 'bor.te... |
how to fix error request for member 'swap' in 'bor.tes::n[i]', which is of non-class type 'char'?
Although it seems not to go with the code presented in the question, the diagnostic is relatively clear. It is complaining about an attempt to invoke a method named swap() on the object designated by bor.tes::n[i]. Tha... |
63,075,138 | 63,076,686 | Where is the C++ debugger executable located in Visual Studio 2015? | I am looking for the directory and file name of Visual Studio 2015 debugger to import it into QT Creator.
My problem is, that I have no idea what its name and folder is.
When googling for it only tutorials of how to debug appear.
| After reading all links posted by phonetagger and vahancho I knew what I need looking for...
so: the executables name is cdb.exe and it can be found at C:\Program Files (x86)\Windows Kits\10\Debuggers\x64
BUT! only if Debugging Tools for Windows are installed
here is a great discussion about it, and how to install it:
... |
63,075,577 | 63,078,139 | SplitEmptyFunction doesn't split empty function | This is (part of) my .clang-format:
AllowShortFunctionsOnASingleLine: InlineOnly
BraceWrapping:
AfterFunction: true
SplitEmptyFunction: true
And even though SplitEmptyFunction is set to true, it still formats my code like this:
void foo()
{}
What am I doing wrong?
| It turns out that SplitEmptyRecord is the setting I was looking for, that is kinda weird, looks like a bug.
|
63,075,693 | 63,094,776 | Custom type {fmt} formatters with external termplates, any drawbacks? | I have a header that defines all {fmt} formatters for my custom types.
To improve compile times, I wanted to reduce the dependencies of this custom formatter header, and decided to define all formatters as external templates, where the implementation is put in a .cpp, with the declarations in the header file as follows... |
what I loose by not having a format function templatized on the FormatContext type?
You'll lose the ability to format through an output iterator.
Previously this would mean that you won't be able to use
format_to[_n]. However in the current master this limitation has
been removed and both format_to and format_to_n wo... |
63,076,106 | 63,080,184 | Sigevent timer can't be restarted nor it executes a callback | I have a t_timer set using a struct sigevent and a struct itimerspec of 6 seconds.
My program is supposed to refresh this timer if a certain event happens, otherwise, at timer expiration, the callback should be executed and finally the program should stop
However not only the callback is completely ignored, but I can't... | I've found something about this. If you use SIGEV_THREAD_ID, the timer will send a signal to the thread id. So you have to install a signal handler in the thread and the function catch_alarm won't be called, just the signal handler, but in the thread.
If you use SIGEV_THREAD, then the function catch_alarm will be calle... |
63,076,312 | 63,154,900 | How to populate torch::tensor with c++ array? | This is very basic: I am normally using Eigen3 for my math operations, but need to use libtorch for a network forward pass. Now I want to populate the torch::tensor with the data from my Eigen3 (or pure C++ array), but without a for loop. How can I do this?
Here is the solution with a loop:
Eigen::Matrix<double, N, 1> ... | Libtorch provides the torch::from_blob function (see this thread), which asks for a void* pointer to some data and an IntArrayRef to know the dimensions of the interpreted data. So that would give something like:
Eigen::Matrix<double, N, 1> inputEigen; // previously initialized;
torch::Tensor inputElement = torch::from... |
63,076,375 | 63,079,256 | Adding non-cObject data (custom class) into a packet in Omnet++ | I am trying to create a packet and attach a custom object. I read through the manual and tried following their suggestions but I am stuck.
According to the manual: Non-cObject data can be attached to messages by wrapping them into cObject, for example into cMsgPar which has been designed expressly for this purpose.
cMs... | The recommended way of carrying own classes (objects) via message in OMNeT++ is to add this to definition of a message. For example:
cplusplus {{
#include "MyClass.h" // assuming that MyClass is declared here
typedef MyClass *MyClassPtr;
}};
class noncobject MyClassPtr;
packet MyPacket {
int x;
MyClassPtr p... |
63,076,502 | 63,077,442 | std::make_tuple and rvalue reference | Like below, why "vv" here is not an rvalue-reference? Here the type of "v" is rvalue-reference, and according to the inference rule of decltype, the decltype of an rvalue-reference (not a prvalue) should be the type of rvalue-reference, right?
int main(int argc, char **argv) {
int x{};
const auto [v] = std::make_tu... | Happens because std::make_tuple<int&&> returns std::tuple<int>. From cppreference:
template<class... Types>
tuple<VTypes...> make_tuple( Types&&... args );
For each Ti in Types..., the corresponding type Vi in VTypes... is
std::decay<Ti>::type unless application of std::decay results in
std::reference_wrapper<X> for ... |
63,076,730 | 63,077,139 | How to link a shared library (.so) to a CUDA source file (.cu) using nvcc? | Currently, I'm compiling my CUDA source file using:
nvcc -O3 --shared -Xcompiler -fPIC -o CuFile.so CuFile.cu
I'd like to call functions from a shared library called GlobalFunctions.so.
How can I link the library to the CUDA source file?
So far, I've tried
nvcc -O3 --shared -Xcompiler -fPIC -lGlobalFunctions -o CuFile... | It seems evident to me that you are making some mistakes in library naming/usage/referencing, but since you don't show any actual output, I'll just make a suggestion. The changes below should make evident some of the errors (e.g. not preceding library name with lib, not specifying -L. or similar, etc.) I suspect none... |
63,076,851 | 63,077,084 | Filesystem not found | Any time I try to use the filesystem library, it gives me error: 'filesystem' is not a namespace-name
My Code is
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
std::cout << "Current path is " << fs::current_path() << '\n';
}
I am using gcc (MinGW.org GCC Build-2) 9.2.0.
Is ... | Try like that:
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
|
63,077,400 | 63,077,534 | A problem of ending the implementation of the code | this code works well for all samples, but after all samples are finished, a problem occurs. I don’t know what happens and the program crashes. Is there a problem with this code?
i have this problem when i use strings arrays usualy can it be the problem?
#include <iostream>
#include <vector>
#include <utility>
#include ... | You are using elements of strings without allocating them.
Allocate elements by inserting
for(int i=1;i<=(n+1);i++){
str[i].resize(maxi);
}
just after
maxi=maxi+3;
|
63,077,625 | 63,078,066 | Definedness of pointer-integer casts | I am interested in the definedness (undefinedness, implementation-definedness) of casts from pointers to integers and various related operations. Mostly I am interested in C11, but answers for other standard versions (or even C++) are welcome.
For the purposes of this question, assume that the C implementation provides... | This is what the C11 standard has to say about intptr_t:
7.20.1.4 Integer types capable of holding object pointers
The following type designates a signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equa... |
63,077,955 | 63,078,086 | OpenGL doesn´t render a square | i´m currently running opengl 4.5.
I copy pasted a code from internet to draw a triangle, and it worked just fine. I played with the shaders and everything was great.
Then i had a great idea, why not draw a square, so i tried and it just renders the background.
Here is the code :
glfwGetFramebufferSize(window, &width... | The primitive type GL_POLYGON is deprecated and only supported by a compatibility profile OpenGL context. If you use a core profile OpenGL context then you have to use the OpenGL primitive type GL_TRIANGLE_FAN instead:
glDrawArrays(GL_POLYGON, 0, 4);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
Note, OpenGL can only render p... |
63,078,172 | 63,081,249 | How to create a char pointer in C++ that points to a concatenation of integers and commas? | Sorry if the terms are not right, just starting in C++ here... I have the following variables whose values can be 1 or 0 depending on another script result:
int number1, number2;
I need to format a variable as "X,Y" ending with a new line, so I did:
char c_number1 = '0' + number1; //going from int to char
char c_numbe... | Many different ways to handle this:
#include <string>
std::stream result = std::to_string(number1) + "," + std::to_string(number2) + "\n";
const char *pointer_result = result.c_str();
#include <sstream>
#include <string>
std::ostringstream oss;
oss << number1 << ',' << number2 << '\n';
std::string result = oss.str()... |
63,079,001 | 63,079,326 | How to use do while loop in exception handling's try block | #include<iostream>
#include <string>
using namespace std;
class marks
{
private:
string name;
int p,c,m;
public:
class Marks_Error
{
};
void input_name()
{
cout << "Enter Name : ";
cin >> name;
}
void input_Physics_Marks()
{
... | Read my comment but I think this will fix your code to do what you wish(not compiled):
int main()
{
marks m;
m.input_name();
bool moreInput = true;
do{
try //using try block to check error;
{
//I want to add do while here, so it keep getting marks until I enter... |
63,079,260 | 63,079,402 | Using a C++17 library against a C++11 application | Is it possible to consume a library built using C++17 against a C++11 application if all the public facing headers and APIs belonging to the C++17 library that the C++11 application consumes follows C++11 syntax. The internal implementation of the C++17 library does have C++17 specific features.
Does it matter if it's ... |
Is it possible to consume a library built using C++17 against a C++11 application if all the public facing headers and APIs belonging to the C++17 library that the C++11 application consumes follows C++11 syntax.
In general, that is a recipe for disaster. In a subset of cases it might work if you are lucky (for insta... |
63,079,356 | 63,098,817 | Missing files/directories error message with PCL 1.11 | I am trying to create a point cloud using a stereo camera arrangement (calibrated and rectified), a disparity map, and Point Cloud Library. Below is a brief description of my C++ code that is supposed to generate a point cloud using the disparity map.
#include <iostream>
#include <fstream>
#include <string>
#include <o... | First build and install vtk:
Build
tar xf VTK-9.0.1.tar.gz
cd VTK-9.0.1
mkdir build && cd build
cmake ..
make -j
Install
(if you have a different preferred place for installations than ~/.local, just change insdir below)
insdir=$(echo ~/.local)
mkdir $insdir
cmake --install . --prefix $insdir
Then add the include p... |
63,079,394 | 63,079,792 | Order of declarations in Posix structs -- is it guaranteed? | ... or, in other words, is it safe to initialize system structures like this:
struct timespec ts[] = { {0, UTIME_OMIT}, {0, UTIME_OMIT} };
...
int r = utimensat(0, subPath.c_str(), ts, 0);
?
| If you are relying only on POSIX, then no, it is not guaranteed that the initialization you present will have the effect you want. This is the extent of what it has to say about the definition of that structure type:
The <time.h> header shall declare the timespec structure, which shall
include at least the following ... |
63,079,451 | 63,080,023 | How to take multiple integers in the same line as an input and store them in an array or vector in c++? | For solving problems on Leetcode, Kickstart or other competitive competitions, we need to take input of multiple integers in a single line and store them in an array or vector, like
Input : 5 9 2 5 1 0
int arr[6];
for (int i = 0; i < 6; i++)
cin >> arr[i];
or
vector<int> input_vec;
int x;
for (int i = 0; i < 6; i... | Take the help of std::istringstream:
#include <iostream>
#include <vector>
#include <sstream>
#include <string>
int main(void) {
std::string line;
std::vector<int> numbers;
int temp;
std::cout << "Enter some numbers: ";
std::getline(std::cin, line);
std::istringstream ss(line);
while (ss... |
63,079,533 | 63,110,866 | Creating openCL buffers causes lag | So I already have a kernel which creates an array of simplex noise values
int *landmap_flags = new int[68 * 68 * 68];
_clw.CLNoise(landmap_flags, clpos, LOD, chunkSize);
This works fine and allows me to calculate noise on the GPU, however, I've written another kernel to generate vertices based on the noise values and ... | I suppose you allocate and delete these cl_float3* buffers on the CPU side repeatedly for each frame / kernel computation. Buffer allocation of course is slow.
Solution is to allocate the buffers only once in the beginning and reuse them over and over again, so instead of
while(true) {
cl_float3* triangle_flags = n... |
63,079,627 | 63,079,820 | Getting wrong output after calling an overriden method in C++ | I am making a program that contains base class RentedVehicle and its derived class FuelVehicle and the derived class of FuelVehicle as Car class. My code is:
#include<iostream>
using namespace std;
class RentedVehicle {
private:
double baseFee;
public:
RentedVehicle() {};
RentedVehicle(int a): baseFee(a) {... | On this line:
double bF = getCost();
in the Car class, you are calling the most derived version of getCost. But this function:
double getCost() {
double cost = mF + (bF*seats);
return cost;
}
will invoke undefined behavior since you are using bF in this function before it's initialized.
Instead, y... |
63,079,631 | 63,079,651 | How can I avoid having to use decltype when calling this template? | I have the following code, which I use to automatically catch bad_variant_access errors. I am aware that I can use get_if to simplify error handling, but in this particular case, I do not want a pointer. This code seems to work, but is redundant. As you can see I always have to do assert_no_bad_variant_access<decltype(... | Reorder the template parameters. Let variant_T be second, and so it may get deduced
template <typename get_T, typename variant_T>
get_T assert_no_bad_variant_access(variant_T& v, std::string_view msg) {
try {
return std::get<get_T>(v);
} catch (const std::bad_variant_access& bva) {
std::cout << msg << '\n';... |
63,080,461 | 63,080,673 | invalid use of incomplete type, not a namespace error | Here is the error message
points.cpp:17:35: error: invalid use of incomplete type ‘__gnu_cxx::__alloc_traits<std::allocator<std::Point>, std::Point>::value_type’ {aka ‘class std::Point’}
os << "(" << (pointvect[x].getx()) << "," << (pointvect[x].gety()) << ")" << "\n" ;
Here is the class def/dec
class Point
{... | namespace std {
class Point;
ostream& operator<< (ostream& os , vector<Point>& pointvect);
}
declares a class std::Point. Probably the declaration you've given for Point is not declared in the std namespace, thus they are different types.
Secondly, you can't declare a std::vector of an incomplete type and last... |
63,080,719 | 63,156,373 | Unintelligible compilation error for a simple X3 grammar | I have a quite simple grammar I try to implement using boost spirit x3, without success.
It does not compile, and due to all the templates and complex concepts used in the library (I know, it is rather a "header"), the compilation error message is way too long to be intelligible.
I tried to comment part of the code in ... | It is an known MPL limitation (Issue with X3 and MS VS2017, https://github.com/boostorg/spirit/issues/515) + bug/difference of implementation for MSVC/ICC compilers (https://github.com/boostorg/mpl/issues/43).
I rewrote an offending part without using MPL (https://github.com/boostorg/spirit/pull/607), it will be relea... |
63,080,853 | 73,493,190 | How to Handle Corners in Segment Intersection Checks | I am creating a ray-casting simulation that uses ray-segment intersection checks. On the corners where two segments meet the code determines there is no intersection.
I have tried extending the segments a small distance but this causes other issues with the simulation. What can I do in this situation?
The code for the ... | You need to include equal to checks for when the float is zero:
if ((t >= 0.0f && t <= 1.0f) && u >= 0.0f) {
|
63,081,139 | 63,081,179 | Reset shared_ptr in custom destructor of parent object | Say I have an object A who'se destructor I need to override for some reason
class A
{
private:
shared_ptr<B> m_ptr;
public:
A(shared_ptr<B> ptr) {m_ptr = ptr}
~A() {m_ptr.reset() // is this needed?
}
Do I need to reset the shared_ptr it holds because if I was using the default destructor, it would hav... | No.
The pointer cleanup is provided by the destructor of the shared pointer, which is called automatically.
See the relevant entry in isocpp faq: When I write a destructor, do I need to explicitly call the destructors for my member objects?
|
63,081,230 | 63,081,346 | String to Float with Precision in C++? | Is there a better way to convert a String to a Float?
I'm using this method here:
std::string test = "4.9102919";
float test2 = std::atoi(test.c_str());
std::cout << test2;
It prints out: 4 instead of 4.9102919.
| You are just using the wrong function.
The behavior of atoi is described by its name itself: ascii to integer. That's why your input is truncated to its integer part, before being assigned to the float variable.
What you need is std::atof, instead: ascii to float.
|
63,081,509 | 64,946,811 | Call C++ (host) methods directly from C# using .NET Core | Embedding .NET Core into a C++ application you can call managed methods like it's described in this tutorial with this sample. You can even send a function pointer as a parameter for the managed code to call back into the host.
But is there any way to invoke unmanaged methods directly, without using callbacks? With Mon... | I've solved it by creating an entry point and then calling the methods using Reflection.
Here's an example:
using System;
using System.Reflection;
public class MyType
{
public string CallMe(int i, float f)
{
return $"{i} and {f}";
}
}
class Program
{
public static string CallArbitraryMethod(st... |
63,081,625 | 63,081,765 | What does this function expect to return? | Program specifies the following:
Write a program with total change amount as an integer input that outputs the change using the fewest coins, one coin type per line.
The coin types are dollars, quarters, dimes, nickels, and pennies.
Use singular and plural coin names as appropriate, like 1 penny vs. 2 pennies.
Your... | Your code is taking user input, converting it manually directly in main() before calling ExactChange(), and then passing the result of that conversion to ExactChange() for it to display as-is.
The way I read the instructions, and the way the screenshot shows the tests being performed, it is more likely that ExactChange... |
63,082,254 | 63,082,449 | Dereferencing pointer and storing reference to the pointed data, then getting address of reference and performing pointer arithmetic on it. c++ | In order to make a diagram(of my own, to understand pointers/pointers-to-pointers/arrays) that is out of the scope this question, I want to know if it is adequate to assume the following:
int *intptr = new int[10]{0};
int &intref = *intptr;
int thirdInt = *((&intref)+2);//is this defined behavior and always equivalent ... |
then getting address of reference
To clarify this bit: It is not possible to "get address of a reference". When you apply addressof operator on a reference, you are getting the address of the referred object.
this code invoke undefined behavior
No.
always equivalent to intptr[2]?????
Yes (except in case of a clas... |
63,083,195 | 63,083,276 | Vulkan has problems loading "vkCreateDebugUtilsMessengerEXT" function address | CONTEXT: Im using a gtx 760 with up-to-date drivers, windows 10 and the latest version of vulkan. Im currently following this part of the tutorial on their main page(Vulkan`s): https://vulkan-tutorial.com/en/Drawing_a_triangle/Setup/Validation_layers
the tutorial makes use of GLFW for the window creation(used in my cod... | Its not VK_EXT_DEBUG_REPORT_EXTENSION_NAME that you have to set up, its : VK_EXT_DEBUG_UTILS_EXTENSION_NAME . Also be sure that your vulkan sdk installation is in excellent condition, also your drivers must be up-to-date. Try restarting your computer after doing these last two things I mentioned just to be safe .
|
63,083,356 | 63,083,820 | cv-qualifiers and rvalue-reference | Suppose we have this piece of code shown as below, the question is that why the cv qualifier (const) for "c" is not kept which the behavior is distinct from "v"?
int main(int argc, char **argv) {
int x{};
int y{};
const auto [v] = std::tuple<int>(x);
const auto [c] = std::tuple<int&&>(std::move(y));
decltype(... | Given
const auto [v] = std::tuple<T>(x);
The type decltype(v) is T const, i.e. const-qualified T. If T is int, then decltype(v) is int const (which also may be written const int). If T is int&&, then decltype(v) is int&& const which is int&& (not const int&& which is a reference to const int). The type int&& const i... |
63,083,580 | 63,083,753 | Insert a vector inside another vector without using the former vector's begin and end (C++20)? | Currently I am inserting a vector inside another like this:
#include <vector>
int main(const int argc, const char** argv)
{
std::vector<int> old_elements{1, 2, 3};
std::vector<int> elements{4, 5, 6};
elements.insert(elements.end(), old_elements.begin(), old_elements.end());
}
What I want to do is somethi... | You can do this:
std::experimental::ranges::copy(get_old_elements(), std::back_inserter(elements));
But it would be more efficient to do this:
template <typename From, typename To>
void append(const From& from, To& to) {
to.insert(std::begin(from), std::end(from), to.end());
}
append(get_old_elements(), elements)... |
63,083,847 | 63,083,925 | How to pass char** as argument to a thread function | How can I pass a char** to a thread function?
char* myData;
std::thread t(load_frame(&myData));
I want to do something like this.
currently, the code does not compile and I get this error
error C2893: Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept(<expr>)'
| You are using std::thread::thread incorrectly.
You can use it as follows (as @ IgorTandetnik has said):
char* myData;
std::thread t(load_frame, &myData);
Live
|
63,084,038 | 63,084,067 | What is the elegant way to delete tmpfile created by boost::filesystem? | I had a code snippet
if (!boost::filesystem::exists(tempDir)) {
boost::filesystem::create_directories(tempDir);
}
auto path = tempDir / boost::filesystem::unique_path("gfbfv1-%%%%-old");
do_something_maythrow(path);
remove(path);
How can I ensure that path is always ... |
Should I write a FileDeleter which takes a path and remove that path on destructor which utilize the so-called RAII concept
This is a fairly reasonable solution. Be careful to take care of any exceptions that the deletion may raise because you wouldn't want to throw from a destructor, especially from one that is bein... |
63,084,250 | 63,086,923 | C++ Queuing function calls | I have a function that queues function callbacks to be executed in another thread.
void Queue(std::function<void()> callback)
{
std::lock_guard<std::mutex> lock(queueMutex);
queue.push_back(callback);
}
The queued functions are called using this function in the main thread:
void ProcessQueue()
{
std::lock_... | I would choose the first option. In the second version, the additional cost of creating and calling the lambda. Since you use capture by value [=], it can be quite costly when capturing heavy objects.
std::function also affects performance.
The second version uses two std::function copies the lambdas with captured para... |
63,084,457 | 63,086,557 | Swapping pointers: equivalent of `std::unique_ptr::swap` | I'm not sure how to translate C++ std::unique_ptr::swap into Go.
I am using std::unique_ptr<T,Deleter>::swap in C++:
std::unique_ptr<bool[]> maskA{new bool[num]};
std::unique_ptr<bool[]> maskB{new bool[num]};
// ...
maskA.swap(maskB); // Swap operation
Would I be missing something if I just use a simple maskA, maskB... | The short answer:
This will be equivalent in terms of functionality but the actual performance implications are different. Use *[]bool for nearest equivalent.
Properties:
The assignment with exchange has the following properties:
the values of maskA and maskB will be exchanged
because these are slices, the underlying ... |
63,084,469 | 63,084,621 | When and how does openGL calculate F_depth(depth value) | Meaning at this point the projection has already been done. This article gives us the projection matrix used by OpenGL, and the factor that affect the z-coordinate of a point is the row:
[ 0 0 -(f+n)/(f-n) -2fn/(f-n) ]
Note, this matrix is computed to make the ‘pyramidal’ frustum to a unit cube. Meaning the z-coordina... | At perspective projection the depth is not linear, because of the perspective divide.
When a vertex coordinate is transformed by the projection matrix then the clip space coordinate is computed. The clip space coordinate is a Homogeneous coordinate. Now all the geometry which is not in clip space (in the Viewing frustu... |
63,084,557 | 63,084,631 | C++ input integer print unicode | I'm trying to output Unicode that corresponds to an integer value entered by the user. This is being done on windows 10 in C++ by the way.
Currently I can print Unicode with this code:
_setmode(_fileno(stdout), _O_U16TEXT);
wprintf(L"\u0006");'''
My question is, how do I attach the variable to the Unicode?
| Something like this
wchar_t wstr[2] = { variable, L'\0' };
wprintf(L"%ls", wstr);
Alternatively, you can avoid the expense of wprintf with
wchar_t wstr[2] = { variable, L'\0' };
fputws(wstr, stdout);
In both cases variable is the integer variable you mentioned. You might want to check that is in range for a wchar_t a... |
63,084,763 | 63,085,015 | How to modify C++ class member variables from C callback | My goal is changing the Width and Height in TTerm.
#include <iostream>
extern "C"
{
void SomeCFunctionThatRequireCallback(void (*FuncPtr)(int Width, int Height))
{
FuncPtr(80, 20);
}
}
class TTerm
{
public:
int IO;
int WinchFds[2];
int Width;
int Height;
TTerm()
{
... | If the C callback is yours or you can change it, you may pass a pointer to the class instance and call some member function in the static method:
extern "C"
{
void SomeCFunctionThatRequireCallback(void * ptr, void (*FuncPtr)(void *, int, int))
{
FuncPtr(ptr, 80, 20);
}
}
TTerm()
{
... |
63,084,821 | 63,085,058 | String class constructor accepting list of const char* | In my String class, I want to make a ctor that accept variable length of arguments (const char*) like parameter pack with variadic template.
Something like following
class String
{
public:
String(const char*... xList)
{
// Internally appending all const char* present in xList and
// pop... | Here is a working example using variadic templates and SFINAE which won't compile if you don't provide const char*s
#include <type_traits>
#include <list>
#include <iostream>
struct String
{
std::list<char> ls;
template<class ... Args, class = std::enable_if_t<std::is_same_v<std::common_type_t<Args...>, const ... |
63,085,379 | 63,088,525 | sub arrays / vectors in C++ using iterators is causing a crash | I wrote a piece of code to print all sub arrays using Iterators, from this [example solution][1]
[1]: https://stackoverflow.com/questions/421573/best-way-to-extract-a-subvector-from-a-vector
void printarray(std::vector<int> array) {
for (auto a : array) {
std::cout << a <<" ";
}
std::cout<< std::end... | Assign i to j in the inner loop and you will see what you expect:
void subArrayPrinter(vector<int>& arr) {
for (int i = 0; i < arr.size(); i++) {
for (int j = i; j <= arr.size(); j++) {
std::vector<int> newVec(arr.cbegin() + i, arr.cbegin() + j);
printarray(newVec);
}
}
}... |
63,085,831 | 63,087,163 | Should I use lock_guard, scoped_lock or unique_lock in this situation? | I have read many of the questions already answered that relate to this but none of them gave me a clear understanding of which I should be using when I have multiple writers but a single reader. The code below is a contrived example of what I'm talking about.
struct StateInfo {
long wd{};
uint32_t perc{};
};
... | To summarize what was already written in comments:
Yes, the code is correct. However, it may be inefficient, because it disallows reading from any array element while writing to another array element. You might want to do more fine-grained synchronization by using a mutex for each array element.
class Blah
{
const... |
63,085,980 | 63,091,943 | How to include ESP8266 mac as arg in GET request? | I am trying to build a request string that includes the ESP8266 WiFi.macAddress as an argument. How can I put the MAC value in the middle of a URL get as shown below?
http://example.com/somepage.html?user=bob&mac=12:34:56:78:90:11&tries=7
| WiFi.macAddress() returns a String, so you can use the + operator to add the
value returned in your url
String url = "http://example.com/somepage.html?user=bob&" + WiFi.macAddress() + "&tries=7";
|
63,086,806 | 63,086,857 | Query about function overloading | When using function with same name, parameter list must differ(either in type of parameter or number of parameters used). I was just practicing with this concept. I wrote the following code.
#include <iostream>
int myFunction(int n)
{
return 2*n;
}
float myFunction(float n)
{
return 3*n;
... | Literals have types too. As integer literal 3 is of type int, then the 1st overload is selected.
As floating point literal 3.3 is of type double (but not float; with the suffix f like 3.3f the type is determined as float), the calling is ambiguous because it could convert to both int and float implicitly.
|
63,086,826 | 63,086,905 | Linked List: Inserting a node at the end | I've been learning Data Structures and currently working with Linked List. I'm trying to add a node at the end of the linked list but not able to figure out the correct logic for it. I've tried inserting a node at the beginning and it works fine.
This is the code:
#include <bits/stdc++.h>
using namespace std;
class No... | Play with the code.
void insert_end(int data) {
Node* temp = new Node(); // 1
temp->data = data;
temp -> next = nullptr;
Node* n = head;
if (!n) { // 2
head = temp;
return;
}
while(n->next) { // 3
n = n->next;
}
n->next = temp;
}
Short explanat... |
63,086,868 | 63,087,432 | QAbstractListModel returning unexpcted result on Qt::DisplayRole | I have created a very minimal QAbstractListModel with two roles, display and test
InvoiceTabModel::InvoiceTabModel(QObject *parent): QAbstractListModel(parent)
{
}
QVariant InvoiceTabModel::data(const QModelIndex &index, int role) const
{
Q_UNUSED(index)
if(role == 123)
return QVariant("testRole");
... | display is a property of Button.
When using data coming from a model, always use the model. prefix to disambiguate (model.display).
|
63,087,090 | 63,087,398 | How to return a 3D array from user defined function? | I want to return a 3-dimensional array from a user-defined function into my main function.
Let's consider a simple example for any particular values of a, b and c arrays;
int*** my_function(int a[], int b[], int c[])
{
for (int i = 0; i < 2; i++)
{
for (int j; j < 2; j++)
{
for (int k; k < 2;... | A better alternative to using pointers is to use std::vector as that will take care of the details of memory allocation and deallocation.
How to initialize 3D vector?
3D vector is simply a vector containing two other vectors inside it. So, if you want to initialize a 3D vector of size X * Y * Z with a value A. Then it ... |
63,087,214 | 63,087,335 | How to change the value of all nodes in a BST tree? | How can I change the value of all the nodes in a tree ?
I filled my BST tree with multiple key-value.
Everything is working perfectly, I just didn't know how can I change the value of all of the node by adding log2 on them.
How can I iterate through each node ?
my Node.hpp
class Node{
private:
Node *left; ... | Since you have distinct concepts of a Node and a BST (which is good), you need one function that acts on a node, modifies the value of the node with whatever rules you decide, and calls itself on that node's children.
Then you can encapsulate this in your BST by having a wrapper function that calls the above function w... |
63,087,728 | 63,087,831 | Why does this happen c++ | Hello I am trying to make a game somewhat like Pokemon but I'm stuck on printing stats.
I am trying to output a level with it showing what level the animal reached.
Any help on the fact I'm not getting expected results?
My code:
visualanimal.h (not used yet):
#include <string>
#ifndef VISUALANIMAL_H
#define VISUAL... | + has a higher precedence than <<, so the line cout << this->level + ".Its stats are now"; is evaluated as cout << (this->level + ".Its stats are now"); - the value of level is used as an offset into a string literal ".Its stats are now", which is not what you want.
Change it to
cout << this->level << ".Its stats a... |
63,087,990 | 63,088,154 | C++ reference to overloaded function is ambiguous | Consider following C++ code:
#include <vector>
struct A {
template<int Count, typename InputIt, typename OutputIt>
static OutputIt func(InputIt first, OutputIt result) {
// write some stuff to result...
return result;
}
};
template<typename Self>
struct Utils {
template<int Count, type... | You have two issues here. First, you need to explicitly pull in the func identifier from both base classes (necessary due to multiple inheritance):
struct C : A, Utils<C> {
using A::func;
using Utils<C>::func;
};
And next, you need a template keyword in Utils::func;
static std::vector<int> func(InputIt first) ... |
63,088,800 | 63,089,041 | Why command don't execute? | i try execute command to CMD, but it don't work
Includes:
#include <Windows.h>
#include <processthreadsapi.h>
#include <shellapi.h>
#include <stdio.h>
#include <iostream>
How i try open notepad:
ShellExecute(NULL, (LPCWSTR)"open", (LPCWSTR)"cmd", (LPCWSTR)"/c notepad.exe", NULL, SW_NORMAL);
| This works
ShellExecute(NULL, L"open", L"cmd", L"/c notepad.exe", NULL, SW_NORMAL);
Don't use casts to remove compiler errors. The errors are telling you that you are using the wrong types, use the right types instead.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.