question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
65,716,896 | 65,719,932 | Iterate over template pack that checks if instance is of a particular variant | I want some reusable code where I can pass a variant instance and a bunch of types and check if the instance is of that type at compile time. And if not, maybe return something like nullopt.
In pseudo-code, ideally it would be something like this:
template <typename ...Ts>
auto getType(const std::variant<Ts...>& v)
{
... | You might do:
template <typename ...Ts>
std::optional<std::variant<Ts...>> getType(const std::variant<Ts...>& v)
{
std::optional<std::variant<Ts...>> res;
((res = !res && std::holds_alternative<Ts>(v) ? std::get<Ts>(v) : std::nullopt), ...);
return res;
}
but it is mostly pointless, as you have then again... |
65,717,010 | 65,718,320 | Initialize complex map in constructor with initializer list | I was wondering the other day whether it is possible in C++ (any standard) to initialize a map in an initializer list of a constructor with a loop or a more complex procedure than literals such that I can make it a const member variable?
class MyClass {
public:
const int myInt;
const std::unordered_map<int, int... | You could use a lambda function inside constructor initializer list. Like so:
class MyClass {
public:
const int myInt;
const std::unordered_map<int, int> umap;
MyClass(int i) : myInt(i), umap( [i]() -> decltype(umap) {
std::unordered_map<int, int> tu;
for(int j=0; j<i; j++)
tu[j]=j;
... |
65,717,109 | 65,717,742 | Can internal linkage rule break a valid c++03 code in c++11? | If there is valid code in c++03, Can it break in c++11 because of Internal linkage rule introduced?
Clause C.2.6 Clause 14: templates point 3 14.6.4.2
I am not able to think of any example.
Any help is appreciated.
| For reference, this is the C++03 version of §14.6.4.2 [temp.dep.candidate] "Candidate functions":
For a function call that depends on a template parameter, if the function name is an unqualified-id but not a template-id, the candidate functions are found using the usual lookup rules (3.4.1, 3.4.2) except that:
For th... |
65,717,133 | 65,718,324 | SQLite how to limit the number of records | I want to limit the number of records in my SQLite table to for example 100 records, and then when I INSERT the 101th record, the first record (the oldest) be removed from the table. In other word, I want to prevent the table from growing more than 100 records and always have the last 100 records. Is there any setting ... | You can do it with a trigger.
Say that your table is this:
CREATE TABLE tablename (
id INTEGER PRIMARY KEY,
name TEXT,
inserted_at TEXT DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now'))
);
In the column inserted_at you will have the timestamp of the insertion of each row.
This is not necessary if you declared the... |
65,717,594 | 65,717,768 | Unable to read memory on kernel32.dll base address | I am making some research and currently i need to get base address of the KERNEL32.dll.
What i already done:
// get PEB structure
PPEB peb = (PPEB)__readfsdword(0x30);
// get ldr linked list and go to kernel32 module
PLDR_DATA_TABLE_ENTRY ldrDataTableEntry = (PLDR_DATA_TABLE_ENTRY)peb->Ldr->InMemoryOrderModuleList.Fli... | The issue is in this line:
PLDR_DATA_TABLE_ENTRY ldrDataTableEntry = (PLDR_DATA_TABLE_ENTRY)peb->Ldr->InMemoryOrderModuleList.Flink->Flink->Flink;
The InMemoryOrderModuleList is not the first member of the LDR_DATA_TABLE_ENTRY structure, so you need to use the CONTAINING_RECORD macro to get the correct ldrDataTableEnt... |
65,717,614 | 65,717,818 | How to convert std::vector<uint8_t> to std::basic_string<std:::byte> for usage with pqxx | I am upgrading an application from using libpqxx 7.1.2 to 7.3.1 and one of the things that have changed in the meantime is that pqxx::binarystring has been deprecated in favour of std::basic_string<std::byte>.
My issue is that I use std::vector<uint8_t> in C++ to represent a SHA-1 hash, which I then need to store in Po... | It is strange that they have chosen a basic_string instead of a vector for this, but this works:
std::basic_string<std::byte> a(
static_cast<const std::byte *>(static_cast<const void *>(data.data())),
data.size()
);
It should be fine because uint8_t is trivially copyable and std::byte pointers can alias others... |
65,717,687 | 65,718,211 | C++: How to read multiple lines from file until a certain character, store them in array and move on to the next part of the file | I'm doing a hangman project for school, and one of the requirements is it needs to read the pictures of the hanging man from a text file. I have set up a text file with the '-' char which means the end of one picture and start of the next one.
I have this for loop set up to read the file until the delimiting character ... | From your example input, it looks like '-' can be part of the input image (look at the "arms" of the hanged man). Unless you use some other, unique character to delimit the images, you won't be able to separate them.
If you know the dimensions of the images, you could read them without searching for the delimiter by re... |
65,717,695 | 65,717,807 | MAkefiles and linking : libraries order? | I've a created a make file to buid a project with multiple folders, multiple libraries. When I perform a full rebuid (i.e. deleting any previous objects and outputs) everything goes well. But if I modify one of the dependencies... it gets compiled (so far so good), the librari is moved to the rightplace, but then theli... | The traditional behavior of linkers is to search for external functions from left to right in the libraries specified on the command line. This means that a library containing the definition of a function should appear after any source files or object files which use it.
Source
|
65,717,961 | 65,718,018 | How to sort a vector with given column only on a triplet value? | I have a struct with three int in it.
struct x{
int a,
b,
c;
};
I am using the struct to store triplets in the vector as the triplets will represent source, destination and weight.
vector<x> myVec;
and I am adding values in it with myVec.push_back({a, b, c});
So far so good, but I want to sort them according ... | You can use a lambda expression as for example
#include <vector>
#include <iterator>
#include <algorithm>
// ...
std::sort( std::begin( myVec ), std::end( myVec ),
[]( const auto &a, const auto &b )
{
return a.c < b.c;
} );
You can define the lambda expression object ... |
65,718,168 | 71,408,972 | Variadic templates operator | Can somebody explain these statements?
What those operator (Eg: , + ...) does here?
1: Sum of args
template <typename... Args>
int function(Args... args)
{
return (args + ...);
}
2: Comma operator
template <typename... Args>
int function(Args... args)
{
((std::cout << args),...);
}
3: General case
template <... |
(args + ...) expands to (args#0 + args#1 + args#2 + .....args#n)
((std::cout << args),...) expands to (((std::cout << args#0),std::cout << args#1) std::cout << args#n)
otherfunction(args...) args is a expanded argument like (args#0, args#1,...)
|
65,718,418 | 65,718,523 | Extract full extension of file path | Using std::filesystem, and given a path like /path/to/file.tar.gz, how may I extract the full or complete file extension - in this case tar.gz?
It appears that std::filesystem::extension() only returns the fragment after the last dot in the filename. With the path specified above the result would be .gz.
Qt provides QF... | There is no dedicated method for this, but you could implement it with simple string operations:
std::filesystem::path path = "/path/to/file.tar.gz";
std::string filename = path.filename().string();
std::string extension(std::find(filename.begin(), filename.end(), '.'), filename.end());
|
65,718,512 | 65,718,925 | Vulkan: how to safely replace a commandBuffer | When my scene updates (e.g a new model introduced), I re-record my draw commmand buffers into new command buffers (tempBuffer) using the function buildCommandBuffers.
I have an array of drawCmdBuffers which are used in the main draw routine.
To complicate matters slightly, my buildCommandBuffers function could be gett... | It looks like you need CPU-CPU synchronization (typically a mutex) around access to the imagesInFlight[] array and the drawCommandBuffers[] or the individual elements within it. Otherwise you could be waiting for the fence for the most recent frame, while the other thread is submitting command buffers for the next fram... |
65,718,645 | 65,721,074 | Converting epoch to UTC date format using date.h | A very simple question. I have been using date.h to get epoch in milliseconds and nanoseconds from a full datestamp.
istringstream temp_ss1{timestamp1};
sys_time<nanoseconds> tp1;
temp_ss1 >> parse("%Y/%m/%d,%T", tp1);
std::cout << tp1.time_since_epoch().count() << "ns\n";
What is the method to go ... | If you're not picky about the format, you can stream the sys_time<milliseconds> out. If you would like to control the format, you can use date::format with these formatting flags. For example:
std::cout << format("%Y/%m/%d,%T", tp1) << '\n';
The precision of the output will match the precision of the time_point.
Is... |
65,718,783 | 65,719,522 | Sherlock and Array hackerrank problem 'wrong answer' on test cases | I have used a prefix sum to solve this problem and it passes a few test cases, yet for a larger number of inputs (n, longer arrays) it seems to fail. I am not able to find the error in the code. I have pasted the code below:
#include<stdio.h>
using namespace std;
int main() {
long long t, n, arr[100000], pre[100000... | #include<stdio.h>
using namespace std;
int main(){
long long t, n, arr[100002], pre[100002];
scanf("%lld", &t);
while(t--){
bool val=true;
scanf("%lld",&n);
arr[0]=0;
for (int i = 1; i <= n; i++)
{
scanf("%lld", &arr[i]);
}
if(n == 1)
... |
65,718,867 | 65,719,277 | recursive call from cycle: big O of algorithm and its steps | I want to understand how to evaluate the complexity, big O, of below algorithm and how to approach those kind of issues of big O estimations in the future with kinda-like algorithms.
#include <iostream>
std::size_t const jobSize = 3;
std::size_t jobCallCounter = 0;
std::size_t jobsDoneCounter = 0;
void doJob( std::si... | You can find a recusive formula for that. If the time complexity for the problem with R recursion number and C cycle size (it is not an input to the recursive function) is denoted by T(R), we will have the following recursive formula:
T(R) = C* T(R-1) + 1
And for the initial case of the recursion T(0) = J. The 1 in th... |
65,719,022 | 65,857,383 | VS2017 debugger gives wrong value of static variable when debugging c++ code | Today i stumbled over a weird debugging situation.
I have 2 files (FileA.cpp and FileB.cpp in this example). In both files i declare a static variable named static int TestVar;
Both Files have a Function to modify the static variable:
void ModifyTestVarFileA();
void ModifyTestVarFileB();
Now i start debugging and step... | it seems like the "big" discussion here is over.
So I want to answer my question as follows:
You have to take care that all of your static (in german we say module global) variables are named differently when using Visual Studio and want to debug / watch them in the watch window. VS is not able to distinguish variables... |
65,719,033 | 65,719,195 | Template argument deduction error in C++ variadic function | I'm trying to compile this code:
#include <functional>
#include <string>
#include <iostream>
namespace outcome {
//// Class c_out (T)
template <class T = void>
class c_out {
public:
bool success = false;
std::string error = "";
T result;
// Then
... | failed is not a function, failed is an overload set. You cannot name an overload set and pass it as an argument to a template and deduce a single function type.
[](auto&&...args)->decltype(auto){return outcome::failed(decltype(args)(args)...);}
is a 95% compatible function object that dispatches to the overload set o... |
65,719,140 | 65,720,079 | Accessing a global and namespace variable | I am trying to access variable x using using directive in the following code:
#include <iostream>
using namespace std;
int x = 10;
namespace e {
int x = 5;
}
int main() {
using namespace e; // Because of this line compiler shows error
cout << x;
return 0;
}
In general we use the following line to access x but I am get... | Let's start with another example.
const int x = 10;
namespace e {
const int y = 5;
}
int main()
{
std::cout << e::y;
using namespace e;
std::cout << y;
}
There is variable with value 10 and name x in global namespace (which can be referred to as x simply) and variable with value 5 with name y in namespace e (which m... |
65,719,224 | 65,995,393 | Using all CPU cores in Python C API | Is it possible in latest Python's C API to anyhow use all CPU cores?
Because of GIL Python can use only one CPU core at a time, thus performance is low on multi-core machine.
But C API has not-well-documented possibility to have several Interpreters within one C++ program.
Is it possible anyhow by incorporating several... | Currently, cpython uses one shared GIL for all interpreters. The GIL needs to be held when running python code to protect internal structures. Because of this, python code can not be concurrently executed, even in separate interpreters.
Python 3.10 will have incomplete support for this ([subinterpreters] Meta issue: pe... |
65,719,409 | 65,746,676 | Export include directories of custom target to consumer | I have a standalone library at my-library/ with a custom target that generates some headers via an external command. In order to export the directory containing these headers as consumable from a parent directory, I'd like to do the following:
add_custom_target(my-target ALL
COMMAND ...
)
target_include_directories... | If you want to build the library with the main project then you probably want to expose the generated headers as an interface library. This way the consuming target doesn't care or know the headers are generated and just uses target_link_libraries() like normal.
You also probably don't want to use a add_custom_target(... |
65,719,419 | 65,719,555 | What are second <> after function name in template funciton declaration? | In a Stroustrup "A Tour of C++" he wrote example of find_all as
template<typename C, typename V>
vector<typename C::iterator> find_all(C& c, V v)
// find all occurrences of v in c
{
vector<typename C::iterator> res;
for (auto p = c.begin(); p!=c.end(); ++p)
if (∗p==v)
res.push_back(p);
return res;
}
What is typename C... | template<typename C, typename V> //template declaration
vector<typename C::iterator> //return type (vector of iterators)
find_all //function name
(C& c, V v) //argument list
Function find_all returns vector<typename C::iterator>, or "vector of iterators to C".
The reason why typename is needed is explained in this que... |
65,720,157 | 65,720,349 | Unable to create a folder with todays date in c++ | Im trying to create a folder with todays date in c++. WHile in python its very easy , in c++ im finding it challenging.
I tried this code where first I tried to print the date and then use the date values to create a folder. I even tried inserting unix commands but even those didnt work.
I simply want to create a direc... | You can make use of std::localtime and std::puttime to get a formatted date.
For example:
#include <iostream>
#include <chrono>
#include <sstream>
#include <iomanip>
int main()
{
auto const now = std::chrono::system_clock::now();
auto const in_time_t = std::chrono::system_clock::to_time_t(now);
std::strin... |
65,720,220 | 65,720,389 | Is there a way to declare a variable sized vector globally from a function? | #include <bits/stdc++.h>
using namespace std;
int grid(int x, int y)
{
static vector<vector<int>> vec(x + 1, vector<int>(y + 1, 0));
if (vec[x][y] != 0)
return vec[x][y];
if (x == 0 || y == 0)
return 0;
if (x == 1 && y == 1)
return 1;
vec[x][y] = grid(x - 1, y) + grid(x, y ... | You obviously can't create a global vector when the size of the vector depends on user input. But you can resize an existing vector.
vector<vector<int>> vec; // create at zero size
int grid(int x, int y)
{
vec.resize(x + 1, vector<int>(y + 1, 0)); // resize to required size
...
|
65,720,269 | 65,721,147 | Why is this there a difference in these two methods of vector addition? | I have written two methods to add multiple vectors together in c++. The input arguments are multiple vectors.
Method 1: The add simple method
This method contains an add1 function that is called recursively and adds two vectors by using a loop until the tail of arguments is added together. The result of each vector add... | Yes allocating memory is slow.
Here is a more efficient solution:
template<class T0, class...Ts>
std::vector<T0>& increment( std::vector<T>& V0, std::vector<Ts> const&... Vs){
for( T0& e:V0 ){
auto i=std::addressof(e)-V0.data();
(e+= ... +=Vs[i]); // binary left fold
}
return V0;
}
template<class T0, clas... |
65,720,665 | 65,720,769 | Initialize const variable in constructor after changing it | I have a Client class, which receives an std::string variable called emailAdress. This is what the code looks like now, and it works:
private:
const std::string email;
Client::Client(std::string emailAddress) : email{emailAddress}
{
}
Now, I want to check if the email contains characters like an @ or a valid nam... | You can pass the parameter to a function, and let the function return the modified string.
class Client {
private:
const std::string email;
static std::string validateEmail(std::string email) {
// ...
return modifiedEmail;
}
public:
Client::Client(std::string emailAddress) : email{valid... |
65,720,795 | 65,732,863 | Can I have a vector of polymorphic values under a fixed sized assumption? | Consider the below code, a derived class replaces a virtual member function with a variant of the function, but does not add any new member variables. Values of Base and Derived are added to a common container, std::vector and as expected the Derived value is sliced. However by copying the representation in memory of... | Starting with your questions:
Does the above code fall into undefined behaviour?
Yes. Use of memcpy on non-trivially copyable objects is undefined behavior.
If so is there a way to implement this without the memcpy or equivalent in a way that would be defined behaviour?
Yes, there is. It will still use polymorp... |
65,720,876 | 65,721,468 | How can I make my nested for output align on right in C++? | I was just learning about nested for and one of my tasks is to make my output align on right, but I can't quite figure out how I can do that
My code:
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int x,y;
for (y=1; y<=5; y++)
{
for (x=y; x<=5; x++)
{
... | Not sure you want to use a C function but this works. A possible way to accomplish this task is to add padding in front of the character you want to print. with printf, using '*' in the format string will tell printf to get the value from the arguments. So,
printf("%*s", y, " ");
s will be filled by the char " " and ... |
65,721,199 | 65,722,466 | C++ LLVM unique_ptr issue | I honestly have no clue what to do here.
I was following this LLVM tutorial of C++ (https://llvm.org/docs/tutorial/MyFirstLanguageFrontend/LangImpl02.html) when i came across this function:
static std::unique_ptr<ExprAST> ParseNumberExpr() {
auto Result = std::make_unique<NumberExprAST>(NumVal);
getNextToken(); // ... | If you use private inheritance (like class A:B{} or struct A: private B{}) then you can only do the conversion to the base-class inside the type itself or in a friended function or type.
So if you want unique_ptr to be able to do the conversion, it's easiest if you just use public inheritance like
class NumExprAST : p... |
65,721,338 | 65,727,140 | Installer: Cannot find python in path environment variable directly after installing it as 3rd party software | For my software (for Windows only) I create an installer with NSIS. In order for the software to work properly I deliver python (version 3.6.5) as a 3rd party software (.exe file). Further I need to conduct a pip upgrade and install some modules (e.g. NumPy).
My approach for the NSIS installer is as follows:
Run execu... | When a user logs on Windows reads the environment variables from the User and Machine parts of the registry and starts the initial process with these merged variables. When a new process is created it inherits the environment of its parent (unless you specify a new custom environment when starting the process).
Applica... |
65,721,342 | 65,721,511 | Problem with converting and comparing dates in c++ | I want to write a custom class DateAndTime to simplify work with dates in my project.
The problem is that I cannot compare the dates properly or I have a problem with converting the dates.
My goal is:
Create a DateAndTime from string
Create a DateAndTime as a current date
Compare 2 dates using the custom DateAndTime c... | Your template (%Y-%m-%d %H:%M) does not match your input (2021-14-01 14:17:33) and you are not checking errors.
|
65,721,604 | 65,916,879 | Is there a way to check the arity of Rcpp::Function? | I need to check the arity of a function in an Rcpp block at run time. What I would like to do is something akin to the following:
double loglikelihood(Rcpp::List data, Rcpp::List params, SEXP i, Rcpp::RObject custom_function) {
Rcpp::Function f = Rcpp::as<Rcpp::Function>(custom_function);
double res = 0.0;
... | So I solved this using a workaround that is a little bit clunky but after giving it some serious thought, this is the least clunky of three methods I tried implementing.
The method I ended up going with is checking the arity of the function on the R side using methods::formalArgs, wrapping the (function, arity) pair in... |
65,721,950 | 65,811,845 | How to move a Gtk::Window with native widows api? | Background
I am developing an application in C++ with Gtkmm 4. I am creating a Gtk::Window. Now i want to move this window to the center of the screen. In Gtkmm 3 there were methods such as Gtk::Window::set_position and Gtk::Window::move, but they were removed in Gtkmm 4. I have already worked out how to get the screen... | According to this source:
GDK exports gdk_win32_window_get_handle() as a public symbol—but its
declaration is not available in a public header, so you’ll have to
define it yourself:
HGDIOBJ gdk_win32_window_get_handle (GdkWindow *window);
It seems a <gdk/gdkwin32.h> header is also available, which makes the mac... |
65,722,341 | 65,722,505 | Split an integer into bytes and combine back into the integers results into error | Toy program to split an integer into 4 bytes and later combine these bytes to get back the input value results into error. However the program works for positive integers. I am interested in signed integers. Need help.
Expected Output: -12345
Actual Output: -57
int main()
{
int j,i = -12345;
char b[4];
b[0... | There are actually two problems that leads to your "error".
The first is that the result of e.g. b[0] << 24 will be an int. When you cast that to a char (and assuming that char is an 8-bit type) then you cut off the top 24 bits of the value, truncating it.
The second problem is that char could be unsigned (it's impleme... |
65,722,774 | 65,723,603 | c++ Histogram random numbers | I have been assigned the following question. Write a program that generates 10000 random integers in the range 0-99 and produces a Histogram
from the random data. Assume that we wish to count the number of numbers that lie in each of the
intervals 0-9, 10-19, 20-29, ........., 90- 99. This requires that we hold 10 coun... | Your use of nums is incorrect, and ultimately you don't really care about retaining those values anyway. All you care about is that they happened; not what they still-are after the fact.
Gathering data for a specific range in 0..99 , broken into segments of 10 each (0..9, 10..19, 20..29, etc) can easily be done by doin... |
65,722,794 | 65,724,420 | How to use the QOpenGLWidget object? | I created a form for the application in Qt Designer and placed a QOpenGLWidget in it and got an openGLWidget object, but now I can't figure out how to draw with this object.
I will not be able to inherit from the object to write code inside its methods and other things...
| You are able to inherit from it. You just have to use the widget promotion mechanism in Qt Designer to promote your new QOpenGLWidget to your derived type.
|
65,723,214 | 65,724,670 | Why does string not work here while char const* does? | Why does string not work here when I catch an error, and char const* does? What is the difference between the two?
try {
throw "connection fail";
} catch( string e ) {
if(e == "connection fail") {
std::cout << "caught: " << e << std::endl;
}
}
|
You're not throwing a std::string, so you can't catch one.
Why is that not a string?
Because in C++, the perfidiously-misnamed string literals (that's what "abc" is) are not actually strings. A string literal allocates some static storage for the contents of the string, and evaluates as a const char (&)[N] type, i.... |
65,723,302 | 65,725,945 | C++ function pointers | I'm experimenting with c++ as an excerise. I'm implementing a template class "MioVettore" that implements different reordering algorithms.
I'm implementing ShellSort and I want to be able to tell what kind of numerical series to use. To do that I thought it was a good a idea to assign a different function to a function... | There are two ways to approach this issue.
State that the member variables are static.
Say where the function pointers are pointed to (to which class).
For the first option,
When looking at the three functions, we can see that it doesn't do anything/ doesn't have anything to do with the member variables. It performs... |
65,723,518 | 65,723,782 | C++ Strings getting printed as hex, when that isnt the purpose | im working on a project for school where we are supposed to create a Contact book.
I stumbled on to a problem where my program prints out strings as hexa symbols, i have never encountered this before and have no idea on how to combat it.
The strings are getting printed out on the terminal from an array.
#include <iostr... | You are printing the addresses of the arrays I_namn and T_Nummer in the function listALLcontacts here:
cout << "#" << nr << " " << I_namn << " " << T_Nummer << endl;
You should use the index, i, to print the found entry:
cout << "#" << nr << " " << I_namn[i] << " " << T_Nummer[i] << endl;
A note unrelated to the pro... |
65,723,565 | 65,728,100 | error: too many arguments for class template in a parameter packed class template | I created a primary template and two specializations: one is for a void-type, the other is a parameter pack for different parameter types.
The background is a "connection"-engine, to connect member functions returning void, so I don't need the return type, just the parameter type.
The classes are just like wrappers, pr... | All you need is a primary variadic class template:
template <typename... TParams>
class CalleeCreator final
{
// ...
};
You don't need to a partial specialization, and you don't need to specialize for R(void) - that's an archaism (from C), the way to write a function type taking 0 parameters in C++ is with empty p... |
65,723,592 | 65,723,715 | My C++ program doesn't stop when it's supposed to | I'm trying to learn C++, but every time I try to run my program it closes itself before you see what it has to show, even ignoring my cin << statements.
As you can see, someone told me to fix it using <cstdio>, but I don't understand what's happening.
When I run this it stops at the cout << statement at the end, but if... |
if i erase one of the two functions a the end (the cin.get() or the getchar()) it would just continue after the first "cin>>" statment ignoring the other function [sic]
It is very difficult to understand what you're trying to say, but this part leads me to believe you're asking why only one of those two functions isn... |
65,723,617 | 65,747,752 | How do I change the value of a variable in an object with file handling? | I am working on a project with oop and file handling and I need a changeQuantity() method where the name of the item and a number(positive or negative) is passed. I want to change the quantity with this method and write the changes to the file.
My Object:
class Item(){
int itemId, quantity;
char tit... | I removed parameters except the file name from file.open() method. As fstream already has default parameters ios::in | ios::out, I removed that and it worked the way I wanted it to. But it does not work 100% of the time. It still repeats the problem sometimes and I haven't been able to find that out why.
|
65,724,598 | 65,729,658 | PyDrake: Extracting AutoDiff gradients from a robot (controlled via Differential Inverse Kinematics) | I am using PyDrake do build a simple model of a Franka Emika Panda robot arm which picks up and places a brick.
I would like to observe how a change in the initial chosen starting position of my brick affects a custom target loss function. Therefore, I would like to use the AutoDiffXd functionality built into Drake to ... | Your deductions look correct to me, except perhaps the very last comment about MathematicalProgram. MathematicalProgram knows how to consume AutoDiffXd, but to take the gradient of the solution of a MathematicalProgram optimization, one needs to take the gradients of the optimality conditions (KKT). We have an issue ... |
65,725,380 | 65,725,792 | C++ freertos Call overriden function of base class from subclass after getting semaphore failes | I am trying to make a base class that holds a semaphore and wait until it can take the semaphore and then call a function in a derived class. (I want to have a number of different base classes that implement the function different but all of them schuld execute this function only after acquiring the semaphore.
I am not... | xSemaphoreTake expects the handle to be passed by value, you pass it by pointer, that is definitely wrong.
The code compiles because SemaphoreHandle_t itself is a hidden pointer (hence this not being a good practice, but occurs often in low-level stuff for other good reasons). This also means that you can and should p... |
65,725,772 | 65,725,847 | Shorter move constructor when class has an atomic member | I am trying to write a move assignment operator for a class that contains an atomic variable. Since atomic's are not movable as per this answer, I've realized that I have to write a move assignment operator that loads the atomic and then stores it. But, I then have to manually call move on all the other fields in my cl... | Consider
class Test {
std::atomic<int*> val{nullptr};
struct Movables
{
// MANY MORE FIELDS HERE
} movables;
public:
Test& operator=(Test&& other) {
this->val.exchange(other.val);
this->movables = std::move(other.movables);
return *this;
}
};
|
65,725,848 | 65,726,132 | How can read as integer as a line from a file and put in a nested vector | Let's say I have a txt file
Rahim
5 6 7
Karim
6 7 8
Rahman
7 8 9
I want to save those name in a vector and I want to put those number in a nested vector as integers.
I tried this but it's not working.
#include <string>
#include <vector>
using namespace std;
int main(){
vector<vector<int> > data;
vector<i... | So I suggest you use an istringstream to read the integers from the second string
#include <sstream>
nameF.push_back(name);
istringstream buffer(values);
vector<int> temp;
int value;
while (buffer >> value) {
temp.push_back(value);
}
data.push_back(temp);
An istrings... |
65,726,341 | 65,756,129 | How to pass matlab::data::TypedArray<double> as pointer to construct Armadillo matrix in MATLAB mex file? | Could someone with more experience advise me how to achieve the above point please?
This must be certainly a trivial matter; however, after many days and nights of trying, researching and reading up on internet I still cannot my head around it.
Setup:
Two C++ source files and a header file:
main.cpp
contains the gener... | There is a similar question at MATLAB Central. Changing the lines
double* darrY = matlab::data::TypedArray<double>(std::move(inputs[0])).release().get();
double* darrD = matlab::data::TypedArray<double>(std::move(inputs[1])).release().get();
to
TypedArray<double> matrix1 = std::move(inputs[0]);
TypedArray<double> matr... |
65,727,217 | 65,730,040 | Apply projection prior to piping to view or action | I would like to apply a projection prior to piping a range into an action or view. Consider the following example:
#include <iostream>
#include <range/v3/view/map.hpp>
#include <range/v3/action/sort.hpp>
#include <range/v3/algorithm/for_each.hpp>
int main()
{
std::vector<std::string> strings{"1.2","100.2","11.2","... | Update(2021.01.26):
Doing actions on projected views might cause confusion. E.g. imagine a projection function with signature int&(std::pair<int, int>&) / int&&(std::pair<int, int>&&) that return the first component of a pair, apply that projection on a range of std::pair<int, int>. What should happen if we filter?
It... |
65,727,293 | 65,727,317 | Element missing after assigning the vector to another vector | I am refreshing information about c++. In the example below I expect that v.size() will be 2. I try adding * before name but it wasn't good way. If Someone has any advice how to do, I will be grateful.
#include <iostream>
#include <vector>
using namespace std;
class Vector {
private:
vector<int> vec;
publi... | vec=v;
This will call the std::vector assignment operator overload. From cppreference, this will...
Copy assignment operator. Replaces the contents with a copy of the contents of other
So you're giving vec a copy of v. When you do vec.push_back(3), you're affecting your copy of v that's now stored in vec. The two ar... |
65,727,313 | 65,727,385 | Inconsistent behavior in static_casting between CUDA and C++ | I'm trying to figure out why the following behavior is inconsistent between CUDA and C++. Note that the values of x is exactly the same, its the static_casting that seems to be inconsistent.
#include <cstdio>
template<typename RealType>
long long __host__ __device__ __forceinline__ FLOAT_TO_FIXED(RealType v) {
ret... | You seem to be negating a 64-bit value of -9223372036854775808, which causes a signed integer overflow (the value of 9223372036854775808 is not representable in a 64-bit signed integer). This is undefined behavior in C and C++. This means you can get whatever result, depending on the compiler and the hardware executing... |
65,727,465 | 65,727,585 | how to implement a mutex using a new synchronization tool that blocks the thread until it's value is larger than a giving bound? | i am studying synchronization , and i found this topic the hardest thing i came across in coding thus far ! i really need help , and maybe i will start to understand this subject !
i learned about mutex with simple lock and unlock , and i learned about condition varibales and ( that uses signal and wait) i also undesr... | If you have a semaphore, then implementing a mutex is trivial since it is basically a sempahore of size 1.
Say you have your semaphore initialized to 0 as shown in the question. Then if you call H(h, 0, -1) by two threads, the first one to arrive will go in right away and will set the value to -1. The other thread will... |
65,727,693 | 65,727,895 | Close a C#/C++ DLLImport or atleast deallocate its heap memory? | I have a C# .NET Framework application that calls an unmanaged C++ DLL via DLLImport, to parse a bunch of files given by the user and perform some operations.
I would like to have a progress bar on my C# application, as this file parsing might be a long process. The best way I have thought to do this is to parse a coup... | Since you've confirmed that files are independent, you should try parallelize the operation.
On the producer side of the process, set up a List or an array with file names. If the list gets too big (really, REALLY big so it stresses available RAM), you may want to replace it with a combination of BlockingCollection and... |
65,728,369 | 65,731,785 | Unable to compile project with cmake - undefined reference to `ns_initparse' | i can compile project with pure g++ command, but i can't do same with cmake. Sorry for dumb question. I just start to work with cmake and google won't give me any solutions.
This is working fine
g++ -static main.cpp -o test -Wl,-Bstatic -lresolv -lutil -lstdc++
But when i compile with cmake i receive such errors
undef... | Try linking additional libs with target_link_libraries. Defining sources per target is also fancy:
add_executable(test)
target_sources(test
PRIVATE
Source/main.cpp
)
target_link_libraries(test
PRIVATE
-lresolv
-lutil
)
target_compile_options(test
PRIVATE
-Wl
)
|
65,728,409 | 65,729,540 | Scrolling text gets negated in static control (C++ WinAPI) | I have some weird control,
CreateWindowEx(!tset&USE?WS_EX_OVERLAPPEDWINDOW:0,
tset&USE?"static":"edit",0,WS_CHILD|WS_VISIBLE|
(!tset&USE?ES_MULTILINE|ES_WANTRETURN|ES_AUTOVSCROLL|WS_VSCROLL //when it's edit
:SS_NOTIFY|SS_EDITCONTROL),5,60,390,474,hwnd,HMENU(10),0,0); //when it's static
SetWindowSubclass(GetDlgItem(hwnd... | In the interests of removing the question from the Unanswered list, I'll repeat and expand upon one of the comments.
Looking at the images, we can immediately see a clear difference in the way they're each presented. The left image has each line starting with a different character, while the right image always starts w... |
65,728,516 | 65,728,545 | Program crashing (No idea) | Program keeps crashing. I'm assuming it's because the pointer is pointing out of bounds when I try to deallocate the memory, but I'm not so sure if that really is the problem. Any idea?
#include <iostream>
using namespace std;
int main()
{
const int sze = 3;
int *ptr1 = new int[sze];
for (int i = 0; i < ... | You are advancing the pointer that new[] returns. You really should not be doing that at all. You need to pass delete[] the same address that new[] allocates. As your commented out code says, you would need to decrement the pointer back to its original value to avoid the crash.
You should use another pointer to iter... |
65,728,638 | 65,728,782 | Debug Assertion Failed error when accessing function in DLL | I'm currently learning how to create a C++ library to be referenced in other projects, and I am running into an issue with a "Debug Assertion Failed" error: is_block_type_valid(header-> _block_use). I followed the walkthrough shown here: Create and use your own Dynamic Link Library. Oddly, I am getting the expected ans... | std::string is not a safe type to use in a DLL function parameter. Non-POD types should never be passed over a DLL boundary, unless they are type-erased (such as by using a void* pointer) and are only ever accessed directly by code on one side of the boundary and not the other side.
Assuming the caller is even using C... |
65,728,723 | 65,728,803 | Virtual function not called in class | In the main() function below, d is a base class pointer (of type A) which points to a derived class (of type B). Yet when the member function f(int) is called on this pointer, i.e. d->f(1), the compiler calls the non-virtual function in the base class A (labelled #2), i.e.
void f(int n) const { std::cout << n; }
Why? ... | d is a pointer to a const A. This means any call to a member function will call the const-qualified overload if one exists. In your case, the const-qualified version of f in the base class (#2) is not virtual, so the fact that d is pointing to a B object doesn't matter. The base class const-qualified overload is the on... |
65,728,730 | 65,728,851 | Linked list consist of a class throws exception 0xC0000005 | So i have a Linked list implementation of my own and it can successfully keep integers and call them when needed with overloaded [] operator but when it comes to storing a class in my linked list, it seems that i can't call the class appropriately (using the same [] operator).
Called functions and members of my Linked ... | There are other problems with the code you posted as well (e.g. isEmpty() is not declared or defined), but I'll focus on the issue you explicitly mentioned.
In your operator:
T& operator [](int indx) {
assert(indx >= lenght - 1);
// You declare this variable on the stack
T result;
result = sea... |
65,728,852 | 65,728,986 | (de)serialize struct containing __uint128_t in c++ | I am trying to serialize and deserialize a vector of structs containing the __uint128_t datatype. Following is an attempt to write a simplified version, without utilizing sizeof(Test) to serialize:
typedef __uint128_t data_t;
//typedef uint64_t data_t;
struct Test {
data_t element;
int count;
Test()=default;
};
tem... | The assert passes because its condition is true. The problem is actually that you're trying to print x.element before x.count. x.element is an extended integer type, and there is no support for printing extended integers in the C standard library (extended integers don't exist in the C standard), so printf doesn't know... |
65,728,941 | 65,748,566 | Error from meson build for a missing header which exists | From this simple Meson build file I get an error on line *** about a missing header file:
# meson.build - src/
subdir('config')
subdir('testers')
subdir('utilities')
headers += [
]
mainPrj += [
'entrypoint.cpp'
]
autoTest += [
'entrypoint_test.cpp'
]
Source = [ headers, mainPrj ]
SourceTest = [ headers... | You do not need to list your header files. Just add include directories like this:
inc_dir = include_directories('path/to/include')
in your case:
inc_dir = include_directories('src/config')
MyProgExe = executable('MyProg', Source, include_directories: inc_dir, ...)
What I usually do is to declare project dependency:
... |
65,728,987 | 65,729,166 | Check for the type of a template parameter and use another template | I have a template function for a class C, and have two other template functions for typename T, which I would like to use as shown below:
template <typename T>
std::string MyHelperFunction1(...) { ... }
template <typename T>
std::string MyHelperFunction2(...) { ... }
template <class C>
std::string MyFunction(...) {
... | You can try using template specialization to decide which function to call, eg:
template <typename T>
struct helper {
static std::string MyHelperFunction(...) {
return "";
}
};
template <typename T>
struct helper<Struct1<T>> {
static std::string MyHelperFunction(...) {
return MyHelperFuncti... |
65,729,229 | 65,729,364 | How to resize 2d vector | #include <iostream>
#include <vector>
using namespace std;
int main(void)
{
vector<vector<int> > matrix;
matrix.resize(3, vector<int>(4, 1));
for (size_t i = 0; i < 3; i++)
{
for (size_t j = 0; j < 4; j++)
{
cout << matrix[i][j];
}
cout << endl;
... | matrix.resize(5, vector<int>(7, 0));
only add new vector of size 7 not modifying actual vector.
Just resize actual vectors to 7 with:
for (auto &row: matrix) row.resize(7);
so now is working:
1111000 ... |
65,729,318 | 65,729,382 | C++: What does thread t { F() } do? | I am reading chapter 15 (concurrency) in Bjarne Stroustrup's "A Tour of C++". I don't understand his introductory example in section 15.2 (he makes a reference to section 6.3.2, which didn't seem to answer my question). The following actually compilable code originates from my endeavor to understand it:
#include <iostr... | From the reference for std::thread, you are calling the following constructor for t1, t2, and t3:
template <class Function, class... Args>
explicit thread( Function&& f, Args&&... args);
where
f - Callable object to execute in the new thread
t1 is constructed from a direct-initialized object of type F. Since F ... |
65,729,369 | 65,737,450 | C++ Error I can't piece together: misunderstanding limits of data types? | Been working through LeetCode things as a supplement to get ahead before taking my intro course this term at university and as a way to pick up C++. I'm very comfortable with Python, but obviously working backwards here is rather difficult. At any rate, this algorithm seems like it should work, but, per the title, it i... | int findMaxConsecutiveOnes(vector<int>& nums) {
int len = nums.size();
int i;
int temp = 0;
int max = 0;
for(i=0; i < len; i++){
if(nums[i] == 1){
temp++;
if (temp > max){
max = temp;
... |
65,729,519 | 65,729,549 | How to use std::async with void method with no parameters? | I'm assuming there's something very simple I'm missing about std::async. I'm trying to run 2 void methods asynchronously, with no return values.
#include <future>
class AsyncTestClass {
public:
void Initialize()
{
std::async(&AsyncTestClass::AsyncMethod1);
std::async(&Async... | AsyncTestClass::AsyncMethod1, being a non-static member function, can only be called if an instance of AsyncTestClass is supplied. You probably meant this:
std::async(&AsyncTestClass::AsyncMethod1, this)
This creates a std::future object whose value will be obtained by evaluating this->AsyncMethod1().
By the way, the ... |
65,729,849 | 65,740,759 | It seems the current standard draft cannot interpret why two structured binding declaration conflict with each other | struct A{
int a;
};
struct B{
int b;
};
auto&& [x] = A{}; //#1
auto&& [x] = B{}; //#2
int main(){
}
In this example, all compilers give an error that the x at #2 conflicts with that introduced at #1. However, IIUC, there's no rule in the post-C++20 working draft standard which can interpret what's the reason... | This is just a missing case in [basic.link]/11: that if one (of the two declarations) declares a structured binding, the program is ill-formed. (One could alternatively merely require that the other also declare a structured binding and then extend the list in [basic.def.odr]/1, but that’s more complicated and suggest... |
65,729,898 | 65,729,899 | How does BOOST_PP_SEQ_SIZE works? | According to https://www.boost.org/doc/libs/1_68_0/libs/preprocessor/doc/ref/seq_size.html:
BOOST_PP_SEQ_SIZE macro expands to the size of a seq.
Sample Code
#include <boost/preprocessor/seq/size.hpp>
#define SEQ (a)(b)(c)
BOOST_PP_SEQ_SIZE(SEQ) // expands to 3
This is magical. How does it work?
| You can read the source here: https://www.boost.org/doc/libs/1_75_0/boost/preprocessor/seq/size.hpp
There are versions for different compilers, but not much difference. The definition of this macro looks like:
# define BOOST_PP_SEQ_SIZE(seq) BOOST_PP_CAT(BOOST_PP_SEQ_SIZE_, BOOST_PP_SEQ_SIZE_0 seq)
# define BOOST_PP_S... |
65,730,112 | 65,730,164 | reverse string program is not working correctly | I tried writing a string reversing program in C++. Though it seemed really simple, Idk why I ain't getting the correct output.
Here's my code:-
#include<iostream>
#include<string>
using namespace std;
string Reverse_string( string &s ){
for( size_t i{}; i<s.size() ; i++ ){
s.at(i)= s.at( s.size()-1-i );
... | In your code you are assigning the values s.at(i)= s.at( s.size()-1-i ); and thus it is changing the previous value of s.at(i), but you should swap the values of respective indexes, s.at(i) with s.at(s.size()-1-i). And also you only need to traverse the first half of the string to swap with respective last half of the ... |
65,730,751 | 65,730,782 | Why do I need to make this non friend == operator overload a member function to avoid "undefined reference" errors? | I have the following class, it is defined like so:
namespace ns{
class Bit{
public:
explicit Bit(bool bit);
Bit() = default;
explicit operator bool () const;
[[nodiscard]]
bool value() const;
[[nodiscard]]
Bit operator==(const Bit& rhs) const;
//friend Bit operator==(const Bit &lhs, cons... | ns::Bit ns::operator==(const ns::Bit &lhs, const ns::Bit &rhs) {
return ns::Bit(lhs.value() == rhs.value());
}
you prototyped ns::operator== then defined ::operator==.
Only ns::operator== is found via ADL. ::operator== may also be found depending on what other == operators and what namespace you are in, adding conf... |
65,731,112 | 65,732,306 | C++: same code but different output for a linked list | I've written a program for removing the duplicates in a linked list, but I got different outputs from two online platforms, which are repl.it (using C++) and onlinegdb.com.
repl.it -> 10 20 20 30 40 50 (X)
onlinegdb.com -> 10 20 30 40 50 (O)
I'm confused about why the output might be different? Is it because of differ... | C++ has undefined behaviors when the code is buggy, which means the output won't be necessarily the same even the code is the same. The only possibility that the code generates the different outputs must be the buggy code itself instead of the compiler.
The solution is:
void removeDuplicateLinkedList(Node *p) {
Node ... |
65,731,261 | 65,731,869 | From enum type declared in a class/struct get to a peer static method also declared in that class/struct? | Briefly: In a template that takes an enum type as parameter (not a scoped enum, a regular old pre-C++11 enum) I need to call a method, declared in the same struct as the enum, which takes an enum value as its parameter. Is there a way to do this?
In full: Suppose I'm "self-scoping" unscoped enums as follows:
struct W ... | I don't know that it's possible as stated, and don't think it is.
A relatively cheap alternative could be to maintain the association between names by hand. In the sample code below, this is done by specializations of a helper template WX<> (tried here).
#include <string>
#include <vector>
using std::string;
using std:... |
65,731,280 | 65,731,341 | How do I delete a pure virtual function inherited from base class? | Let's say I have a base class called Human. Baby and Adult are sub-classes of Human. Human has a function run as a pure virtual function and I don't want Baby to inherit run but if I don't override run, Baby would become an abstract class.
class Human{
public:
// Some human attributes.
virtual void run()=0;
};
... | This is not possible. Consider the following code:
Human *CreateAPerson() {
return new Baby();
}
int main() {
Human *human = CreateAPerson();
human->run();
}
The compiler would have no way to know that human->run() is illegal.
|
65,731,770 | 65,731,813 | Why is the order of destruction same as order of construction, with static object (C++)? | The code is :
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A::A" << endl; }
~A() { cout << "A::~" << endl; }
};
class B
{
public:
B() { cout << "B::B" << endl; }
~B() { cout << "B::~" << endl; }
};
int main()
{
B b;
static A a;
return 0;
}
The output is :
B::... | Static local variables will be destroyed at program exit.
The destructor for a block-scope static variable is called at program exit, but only if the initialization took place successfully.
So b will be destoryed firstly at the end of main(), a will be destroyed after that.
For the initialization,
are initialized th... |
65,731,778 | 65,731,919 | Microsoft HTTP SERVER API environment requirments | I want my C++ application/process to be an HTTP server that listens to requests from another Java process. I am planning to use Microsoft's HTTP Server API for this, but the documentation says:
The HTTP Server API is supported on Windows Server 2003 operating systems and on Windows XP with Service Pack 2 (SP2).
Does ... | The requirements section (unless otherwise stated on the page) are always minimums. MS is very clear when something has been removed from the API (and even then is almost always a strong warning to quit using something rather than actually removing it).
|
65,731,787 | 65,751,691 | opencv can't open a yuv422 image while rawpixels.net can display the image | I am trying to open a yuv format image. I can open it with rawpixels.net and display it after setting the following
width:1920
height:1080
predefined format: yuv420 (nv12)
pixel format yuv
But if I open with opencv with the following code I failed to open.
#include <iostream>
#include <opencv2/core.hpp>
#include <open... | The very first thing to do when dealing with raw (RGB, BGR, YUV, NV12 and others) images is to know the dimensions in pixels of the image - you are really quite lost without those - though you can do certain tricks to look for correlation to find the row width since each row is essentially similar to the one above norm... |
65,732,465 | 65,732,512 | Creating a subfolder in a directory in c++ throws syntax error | I’m trying to create a subdirectory with today’s date in a folder. The code compiles succesfully, but throws an error during runtime.
#include <iostream>
#include <chrono>
#include <sstream>
#include <iomanip>
#include <bits/stdc++.h>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
int main()
{ ... | You can't put ss.str() inside double quotes and expect the shell to execute the C++ code.
Instead you should evaluate ss.str() in your program and pass the results to the shell
string str_ = "mkdir -p Anita_/" + ss.str();
const char *com = str_.c_str();
system(com);
This version uses + to append "mkdir -p Anita_/" and... |
65,732,730 | 65,732,869 | Call to a [[noreturn]] function and order of destruction | Considering following code, I or, rather the developer of original code, would expect that function-local object would be destroyed before the call to [[noreturn]] fubar() function.
#include <iostream>
#include <iostream>
using std::cout;
using std::endl;
class Static
{
public:
Static() { cout << "Static::Static"... |
It's exactly same behaviour as if fubar() wasn't noreturn.
As expected; [[noreturn]] is a red herring here, as the fubar() does not return (and thus fulfills the requirement that the attribute is intended to signal).
From [dcl.attr.noreturn]/2 and [dcl.attr.noreturn]/3 [emphasis mine]:
/2 If a function f is called w... |
65,733,104 | 65,769,301 | Embedding Windows Media Player in MFC | I am trying to embed WMP in a newly created MFC dialog based application using Visual Studio 2019.
These are the steps I'm following:
Create new project
Go to resource view and click Insert ActiveX Control
Select Windows Media Player and click OK
Change the newly created WMP element's ID to something less general, lik... | In my opinion, the code automatically added in the class file added by VS2019 conflicts with the definition in WinMediaPl. After comparing the code automatically added by VS2017 and VS2019, I find that the automatically added code below is redundant in CWMP_Player.h or other .h.
// Operations
public:
// IWMPPlaylist
/... |
65,733,134 | 65,739,236 | Memory leak while using C# dll in a C++ | The situation is, I wrapped C# dll to use it in a C++ project and when I execute C++ project I can't see any sign about memory leak but the memory increases little by little. I think it's because the GC in C# library doesn't work in C++ project and I don't know how to solve it. Please help me.
My code is below:
C#
... | From SafeArrayAccessData documentation
After calling SafeArrayAccessData, you must call the SafeArrayUnaccessData function to unlock the array.
Not sure this is the actual reason for the leak. But when debugging problems, a good first step is to ensure you are following all the rules specified in the documentation.
|
65,733,227 | 65,736,064 | std::list::insert thread safety | Supposing all the operation I can do is either:
Inserting new element into an std::list (or)
Reading the back() element of the list
Am I thread safe? Any thread can do any of the two operations in any order. I'm not expecting any specific order to see, for eg if I insert an element and then read the back() I am NOT e... |
Am I thread safe?
Potentially yes; Not necessarily.
It is crucial where the element is inserted. If you insert to the back of the list, then you have a data race, and therefore UB. If you insert elsewhere other than the end (and therefore the list must be non-empty prior to insert), then it should be thread safe.
|
65,733,375 | 65,733,376 | How to use function pointers to access member functions? | The Problem
Lets say that we have a simple class to sort a list of integers,
class Sorter {
public:
Sorter() {}
~Sorter() {}
enum class Algorithm { Bubble, Heap, Merge, Insertion };
void SetVector(const std::vector<int>& vec) { mVector = vec; }
void Sort(Algorithm algo)
{
void (Sorte... | Lets look at this simple example,
struct Greeting {
void SayHello() { std::cout << "Hello!\n"; }
void (Greeting::*pfHello)() = nullptr;
};
int main()
{
Greeting g;
// Lets assign the function pointer to the pfHello variable.
g.pfHello = &Greeting::SayHello;
// Now lets call it like a traditi... |
65,734,232 | 65,740,213 | Get last windows update check C++ wuapi | I'm trying to get the last windows update check using wuapi. I have the following code:
VARIANT variant;
VariantInit(&variant);
IAutomaticUpdatesResults* pAutomaticUpdatedResults = NULL;
if (pAutomaticUpdatedResults->get_LastSearchSuccessDate(&variant) != S_OK)
throw;
std::cout << variant.date << std::endl;
Unders... | You can obtain an IAutomaticUpdatesResults* from IAutomaticUpdates2::get_Results.
IAutomaticUpdates2 is an interface implemented by the AutomaticUpdates coclass.
Full sample:
#include <Windows.h>
#include <wuapi.h>
#include <iostream>
int main() {
HRESULT hr;
hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHRE... |
65,734,272 | 65,734,483 | MySQL DELETE query doesn't delete element from c++ code | I have this simple code:
std::stringstream del;
int ret = 0;
del<<"DELETE FROM 'database_name' WHERE id=\""<<id<<"\""; //id is a parameter of the function
std::string query = del.str();
const char* ch_q = query.c_str();
ret = mysql_query(conn, ch_q);
if(ret == 0)
{
std::cout<<"Re... | Your statement has an error where you're naming the table.
From the MySQL manual page on identifiers:
The identifier quote character is the backtick (`)
So:
DELETE FROM `database_name`
You've used a single-quote instead:
DELETE FROM 'database_name'
|
65,734,328 | 65,734,441 | Crossworks String Conversion | We are using Crossworks IDE to run freeRTOS in C++. Here, we are sending data via serial com using "HAL_UART_Transmit" built in STM32_HAL function. We want to send Sensor data via serial com to external device.
here is an exmaple format:
float humiditySensorValues[2];
uint8_t buffer[100] = {"Temperature = ? \r\n"} ; ... | Use snprintf:
char buffer[100] = {0};
int len = snprintf(buffer, sizeof(buffer), "Temperature = %f \r\n", (double)humiditySensorValues[0]);
HAL_UART_Transmit(&husart3, (uint8_t*)buffer, len, HAL_MAX_DELAY);
Do not use sprintf as that does not check for buffer overflow.
|
65,735,308 | 65,814,997 | modifying custom type Rcpp::List objects in place | I am struggling to figure out how to modify custom type list elements in an Rcpp::List; below is some code to illustrate my problem (using Rcpp modules).
#include <Rcpp.h>
class Base {
public:
Rcpp::NumericVector data;
Base() {
this->data = Rcpp::NumericVector();
}
void append(double x) {
... | You need to understand how R objects work (Rcpp being a wrapper). The key is
R objects are all pointers (SEXP being a pointer to SEXPREC)
When you push_back to a vector you are potentially changing the underlying pointer.
Therefore your NumericVectors are not guaranteed to refer to the same object after push_back.
... |
65,735,790 | 65,735,882 | Custom C++ exceptions with template arguments | I'm trying to learn how to use custom C++ exceptions with template arguments. This is a dummy program that I'm trying to compile unsuccessfully:
#include <string>
#include <iostream>
template <class T>
class MyException : public std::exception {
public:
T error;
MyException(T err) { error = err; };... | You can't catch any template! You can catch only specific type so only specific instance of template. So your code should look like this (quick fix):
#include <string>
#include <iostream>
template <class T>
class MyException : public std::exception {
public:
T error;
MyException(T err) { error = er... |
65,735,934 | 65,738,477 | How do I initialize hwnd | I'm trying to make a 32 bit game for experience but I have run into a problem
an error keeps popping up saying "Uninitialized variable hwnd used" I understand what it means but I don't
know what to initialize hwnd as. I have tried setting hwnd to render_state.memory but it doesn't like that ether.
( if you try to compi... | Based on the information you provide it's impossible to say for sure, but here is my best guess:
Change the signature of your render_backround() to this: void render_backround(HWND hwnd)
Remove the line HWND hwnd; from that function
In your second .cpp file replace this line render_backround(); with this: render_bac... |
65,736,623 | 65,736,697 | How to use a compile-time interface with a runtime type? | I have a function that takes a T and calls specific functions on the supplied object. Until now it was used from compile-time objects, so all was great. Minimal example:
#include <iostream>
struct A {
void fun() const { std::cout << "A" << std::endl; }
};
struct B {
void fun() const { std::cout << "B" << std::e... | std::visit([](auto const& x) { use_function(x); }, var);
|
65,736,814 | 67,684,514 | How to get unsigned long long from C++ to Kotlin through JNI? | I'd like to read an unsigned long long from my Kotlin code.
The value comes from C++ code through JNI.
Here is the C++ code :
unsigned long long getMaxValue() {
return -1;
}
Here is the JNI code :
extern "C"
JNIEXPORT jlong JNICALL
Java_com_tb_of_1ir_MainActivity_getMaxValue(JNIEnv *env, jobject thiz) {
static... | It is not possible in a simple way. Maybe by decomposition.
|
65,736,831 | 65,737,463 | CMake two source files with the same name | Question is pretty simple, If i have CMake project with the following structure
sources/foo.cpp
sources/bar/foo.cpp
Does cmake guaranties lack of compile conflicts with same file names in different directories?
|
Does cmake guaranties lack of compile conflicts with same file names in different directories?
Cmake will work with no problem with two files with same name. It would be pretty useless if it wouldn't.
As for "guaranties", from cmake licensing:
CMake is distributed under the OSI-approved BSD 3-clause License.
On the... |
65,736,891 | 65,736,958 | how to print the contents of the vector to screen in c++ whose each element is pair in a pair | I am working on a assignment in which the elements of the vector of this type vector<pair<string,pair<int,int> > > A .
for(auto it=A.begin();it!=A.end();it++)
cout <<*it.first<<" "<< *it.second.first <<" "<<*it.second.second;
but it is showing errors.
Can anyone help me?
| you need to use (*it).first instead of *it.first, because *it.first means a iterator which is it.first, but actually the iterator is (*it).
You can get rid of this problem by using ->, like it->first. Because if you use -> it is lot easier than using *.
vector<pair<string,pair<int,int> > > A;
for(auto it = A.begin(); ... |
65,737,696 | 65,737,852 | What is wrong with my vector declaration in c++? | I'm having trouble declaring a vector of class objects. The class I'm trying to reference is in a header file and its constructor calls for an array of 6 strings.
string Data[6];
vector<Gamer> fileOut;
void split(string input)
{
stringstream ss(input);
int count = 0;
while (ss.good()) {
string sub... | Since your vector is declared as follows
vector<Gamer> fileOut;
you do not need new here
fileOut.push_back(Gamer(Data));
or even
fileOut.emplace_back(Data);
Also make sure you include whatever header is required for the definition of Gamer
#include "Gamer.h"
|
65,738,027 | 65,768,543 | How do I fix LNK2019 errors after adding libpng to a VS2019 C++ project through Nuget? | I am creating a solution that requires the use of libpng. I installed this library and its dependencies through Visual Studio 2019's Nuget Package Manager, and including <png.h> and using functions and macros from the library does not lead to errors. However, should I try building the solution, I get one LNK2019 error ... | The issue why the automatic nuget cannot add the lib dependencies into the Linker is that the c++ nuget is for v140 and v120 build tool. And if your project is created by VS2019, VS uses v142 build tool(for VS2019) by default.
You can check the targets file(Methods to import lib automatically) from the nuget package <s... |
65,738,296 | 65,738,297 | How to run a simple OpenCV code in C++ on linux? | I wrote a simple OpenCV code using C++ and run it in linux:
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
using namespace std;
int main()
{
cv::Mat image;
image = cv::imread("sajjad.jpg", 1);
cv::namedWindow("Display Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Display ... | 1- Install dependencies:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install libgtk2.0-dev pkg-config
2- To compile OpenCV you will need a C++ compiler. Usually it is G++/GCC or Clang/LLVM. also OpenCV uses CMake build configuration tool:
sudo apt install -y g++
sudo apt-get install cmake make
3- Clone repo... |
65,738,895 | 65,771,598 | How to pass boost::log::expressions::smessage to nlohmann::json constructor? | I have a code similar to this:
const auto jsonFormatter = boost::log::expressions::stream << boost::log::expressions::smessage;
I want to escape the message using nlohmann::json, something like:
nlohmann::json json{boost::log::expressions::smessage};
I can do following to convert boost::log::expressions::smessage to st... | I really appreciate help and the other answers, which may be better in other cases, but long story short, I tried a lot of solutions and went with this one in the end (I can update it if it can be improved):
#include <boost/phoenix/bind/bind_function.hpp>
..
nlohmann::json EscapeMessage(
boost::log::value_ref<std::... |
65,739,439 | 65,739,479 | Use Class Member Function Pointer before Class Definition C++ | I have the following code:
// FILE_NAME: compiler.h
typedef enum Precedence { /* ENUM MEMBERS */ } Precedence;
typedef enum TokenType { /* ENUM MEMBERS */ } TokenType;
typedef void (Compiler::*ParseFn)();
typedef struct ParseRule {
ParseFn prefix;
ParseFn infix;
Precedence precedence;
} ParseRule;
class... | You need to (pre-)declare Compiler as a class before referring to it:
class Compiler;
typedef void (Compiler::*ParseFn)();
|
65,740,166 | 65,746,592 | How can I go reverse in a switch case | I have 2 LEDs and when I press a button it should change the pattern in this order: off, first LED on, both LEDs on, second LED on.
Now I want to add a second button that does the same but in reverse: second LED on, both LEDs on, first LED on, Off.
I tried creating a second switch-case, but it doesn't work.
Code:
void ... | Your other answers are fine, but I wanted to sketch out a slightly different approach. Use the buttons to increment or decrement a "state" value (take care of wrap-around!). Use a separate routine to turn on or off the LEDs depending on this state. The code inside loop() becomes simple. The hard part is writing the "is... |
65,740,355 | 65,740,638 | How to delete instantiation of a member function template? | I am learning how to stop instantiation of a member function template. In c++20 requires clause is used to put constraint on template arguments and using this I am able to stop instantiation in c++20.
What line of code could replace the requires clause in c++11/14/17 in this code.
#include <iostream>
#include <string>
... | Using the type trait std::enable_if:
#include <type_traits>
// ...
template<typename T,
typename std::enable_if<
!(std::is_same<T, bool>::value || std::is_same<T, std::string>::value),
int
>::type = 0
>
constexpr auto increment_by_one(T targ) const noexcept -> decltype(... |
65,740,807 | 65,741,014 | CMAKE creating an additional directory in the build file | My current project structure looks like this:
Project
--src/
--CMakeLists.txt
--Graph.cpp
--Graph.hpp
--main.cpp
--build/
--CMakeLists.txt
The CMakeLists.txt in the Project folder lookalike this:
cmake_minimum_required(VERSION 3.18)
project(GRAPHTHEORY VE... | Build artifacts and cache is kept in a directory that reflect the subdirectory you added in CMake with the add_subdirectory command.
However, you can change where the final target end up by changing the default value of RUNTIME_OUTPUT_DIRECTORY. For example, this code will put it in the bin directory:
set_target_proper... |
65,740,895 | 65,742,598 | How to sanitize every input for a range of character in my Qt application | I have a Qt application that has a bunch of QLineEdit, QTextEdit etc that the user can modify and put any text he likes.
When saving in this application a XML file is written, partly from what the user has put in these fields. Then the XML file is transformed to HTML through saxonb-xslt.
The problem is that currently t... | I think to best way to handle this is to do input validation already at the input fields. Qt has support for this, see the documentation of the QValidator class and these SO questions:
Qt QLineEdit Input Validation
and (becauese QTextEdit doesn't have support for validators out of the box):
QRegExpValidator with QTextE... |
65,740,922 | 65,741,331 | Why is g++ Giving Me Conflicting Errors While Compiling? | I am attempting to compile my second, (still noobish) C++ program, and g++ is giving me these errors:
new.cpp: In function ‘int main()’:
new.cpp:10:4: error: ‘cin’ was not declared in this scope
cin >> name;
is the first. Here's the second:
^~~
new.cpp:10:4: note: suggested alternative:
In file included from n... | Here is a little bit of explanation for a c++ and g++ newbie:
new.cpp:10:4: error: ‘cin’ was not declared in this scope
cin is declared under the std namespace. See https://en.cppreference.com/w/cpp/io/cin
The second one is not an error, but a suggestion by the compiler by pointing to the alternative found by the com... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.