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,763,216 | 65,763,554 | How do you compare the content of an edit control to the text in a file? | I am writing a simple text editor using the Win32 API and I am trying to write a function to compare the content of the file to the content of an edit control. I currently have this:
BOOL checkForModification (PCWSTR pszFileName, HWND hEdit) {
BOOL bSuccess = FALSE;
DWORD dwTextLength = GetWindowTextLengthA(hEd... | Seriously, use a debugger and test it with a file that contains simple text like ABCDE. You should be able to figure out the problem in less than 30 seconds just by inspecting a few variables!
You can trivially determine that the problem is not reading the documentation of function GetWindowTextA (https://learn.microso... |
65,763,740 | 65,764,033 | how boolean_type operator is getting called on if statment? | I have a header file that defines a class with a boolean_type conversion operator in it, which is used in main.cpp. I am not able to understand how the boolean_type operator is getting called in an if statement
Header.h
template <typename Type>
class Sptr
{
public:
struct boolean_struct { int member; };
typedef... | C++ is all to happy to make a construct work, so long as it can (within certain constraints) find a valid conversion sequence to types that work in the given context.
In this case, the compiler sees an if statement, which expects an operator of type bool. It will therefore attempt to form a bool value from sPtr. A conv... |
65,763,868 | 65,764,562 | Is there any way to go through the indexes of a 2D arrangement as if it were a piece on a game board or something like that? | I am trying to develop the code for an exercise that was assigned to me, but I can't find any way to do what I need to accomplish. The exercise in question consists of changing and printing the values of a 10x10 2d array filled with zeroes generating a pattern like this:
1 1 1 1 1 1 1 1 1 1
1 0 0 0 0 0 0 0 0 1
1 0 1 1 ... | Kindly refer to this
In first conv function I made a general pattern without snake
Then I focused on positions from where the snake connects other rows or column
#include <bits/stdc++.h>
using namespace std;
void conv1(int a[10][10])
{
int temp=0;
for(int i=0; i<10; i++)
{
if(i%2==0)
{
... |
65,764,253 | 65,764,299 | What is the purpose of adding a pointer in: typedef unsigned char UCHAR, *PUCHAR; | What is the purpose of adding a pointer in: typedef unsigned char UCHAR, *PUCHAR;
(there are a lot of other examples of typedefs with additional pointers) I found that next to UCHAR stands *PUCHAR pointer and checked sizeof(UCHAR) and sizeof(PUCHAR) the results was 1 byte and 8 bytes. Is this pointer size fixed or is f... | UCHAR stands for unsigned char which is 1 byte in size. PUCHAR stands for unsigned char*. To store a pointer you need 8 bytes (in a 64 bit application). That's why the size of UCHAR is 1 byte and size of PUCHAR is 8 bytes.
Why a pointer is 8 bytes?
That's because in a 64 bit application, the address of a single byte h... |
65,764,279 | 65,764,399 | Is there a way to call varying function of member object based on template variable | I have the following code:
class Person {
void func1() {
obj_.function1();
}
void func2() {
obj_.function2();
}
void func3() {
obj_.function3();
}
Object obj_;
};
It's pretty obvious there is a pattern here...
I would like to know if I can call different functions based on template argumen... | template <auto Func>
void generic() {
(obj_.*Func)();
}
Then foo.generic<&Object::function1>() calls function1.
Prior to c++17:
template <void (Object::*Func)()>
void generic() {
(obj_.*Func)();
}
should work.
|
65,764,854 | 65,764,910 | C++: Dynamic polymorphism for operators | Is it possible to have dynamic polymorphism for operators? I have a vector of base-class pointers:
std::vector<Event*> events;
where each event is a different derived class (e.g. StartEvent). All derived classes have their operator<< implemented such that they can be printed to the console.
However, this does't work:
... | The classical solution is to declare an << overload as a friend of the base class, and then use it to invoke the appropriate virtual method:
std::ostream& operator<< (std::ostream &stream, const Event &e) {
e.format_output(stream);
return stream;
}
Now, simply declare format_output() as an ordinary con... |
65,765,085 | 65,765,422 | Is there a way to wrap a function call in or overload a functions call? | My aim is to have a class that inherits from another class in C++ and overloads all of the parents class methods in an identical fashion.
So when a method is called some code is run, the original method is called and a bit more code is run all in the derived class overload method.
class Base
{
Base() {}
~Base() {}
... | With inheritance, you might do:
class Base
{
Base() {}
virtual ~Base() {}
virtual void base_method()
{
// Does something.
}
};
class BaseWrapper : public Base
{
public:
BaseWrapper(Base base) : Bas( base ) {}
void base_method() override
{
// Some code ...
Base::base_method();
// Some ... |
65,765,322 | 65,765,513 | Visual Studio debugger no longer showing lines of code preceding line of code where crash happens | I while ago when I had a crash in Visual Studio it would show me the lines where the code crashed as well as all the lines before that that called the function containing the line on which the code crashed.
Since a few months and a few updates in Visual Studio, it started showing only the line on which the crash happen... | I was able to find how to display the call stack window: while debugging, in the Debug menu, select Windows > Call Stack.
This shows all the function calls down to the line where the crash happens. Solved the cause of the particular crash straight away by the way.
|
65,765,573 | 65,765,750 | The result of the encrypted message after implementing RSA is 0 using the GMP library | I am using the GMP library functions in order to implement the RSA algorithm.
Here is my code:
const char* random_String() {
srand (time(NULL));
const char * tab[] = {"Alice", "Bob", "encryption", "decryption"};
std::cout << sizeof(tab)/sizeof(tab[0]) << std::endl;
int indice = rand() % (sizeof(tab)/si... | This code
mpz_set_str(M, mess, 10);
converts the random string mess to an integer. For this to work the string must consist of decimal digits, but this is not true for any of your random strings. So the function fails and M is unchanged.
If you check the return value of mpz_set_str you will see that it is -1 meaning t... |
65,765,843 | 65,767,095 | Variable template type | Just want to confirm that type of templated variable can be independent of template. This compiles by g++:
template<class T>
constexpr long MAX_AS_LONG = static_cast<long>(std::numeric_limits<T>::max());
Does it confirm to the standard?
(In all the examples on the internet, type of templated variable is T itself).
| There is no requirement the type of a template variable differs based on template arguments.
A common example is std::is_same_v<T,U> which is always a bool.
|
65,766,506 | 65,766,836 | How to reduce memory usage? Problem from code forces | I solved this problem from codeforces: https://codeforces.com/problemset/problem/1471/B. But when I upload it it says memory limit exceeded. How can I reduce the memory usage? I used C++ for the problem. The problem was the following: "You have given an array a of length n and an integer x to a brand new robot. What th... | You don't need to build the array as specified to compute the sum
You might do:
int pow(int x, int n)
{
int res = 1;
for (int i = 0; i != n; ++i) {
res *= x;
}
return res;
}
int compute(const std::vector<int>& vec, int x)
{
int res = 0;
int i = 0;
while (true) {
const auto ... |
65,766,767 | 65,767,387 | How to add normal attribute to vertices included in multiple triangles | I have a large buffer with many vertices which are all layed out in an even grid in the XZ plane but with varying heights in the Y axis. To join up these vertices the index buffer is written in a way that most of these vertices will be included in 6 different triangles. The only way I can think of giving these vertices... |
with many vertices which are all layed out in an even grid in the XZ plane but with varying heights in the Y axis
If any of the constituent values of an attribute differ, they are in effect different vertices.
is by having the vertices being repeated six times in the vertex buffer
Given the fact, that if they have ... |
65,766,800 | 65,767,215 | Why doesn't defining `__cxa_throw` cause a link error? | Why doesn't the following C++ program have a link conflict with the system-provided __cxa_throw ?
#include <cstring>
void __cxa_throw(void *, void *, void (*)(void *)) {
std::puts("bad luck");
}
int main() {
throw 13;
}
Is there something magical about that symbol? For a normal function this would be an ODR... | As @Igor pointed out, you need to add extern "C" to prevent name mangling.
But the cause why it works is because the symbol is most likely defined as weak. This means that if you redefine it, the linker will use your version instead of the standard's library.
Gcc's source code confirms they define it as weak. I am unsu... |
65,767,289 | 65,767,600 | Possibly learning old C++ standard | I am interested in learning C++, and I found a book that seems to be the right fit for me. However, even though the book is quite new, some readers criticized that an earlier version of the book did not really dive into the new C++ standards (such as C++11, C++14, C++17) and rather used the "old C++ standard" (i.e., pr... | Some code have changed in C++11, main changes, IMO, are:
way to "return" big object:
Pre-C++11, it has been recommended to use output parameter to avoid copy:
void MakeVector(std::vector<int>& v) {
v.clear();
// fill v;
}
Since C++11, no longer required for movable types, and return by value is the way to ... |
65,767,476 | 65,767,531 | Separate string into different strings at space C++ | I'm taking in string inputs and I need to read in multiple words from one line and push them into a vector. I can't for the life of me figure out how to split the string whenever there's a space character. I know I need to use the getline() function, but I feel like I've tried everything and I'm stuck.
Here's my code s... | You can use getline() to take the input and then use stringstream for splitting the strings. Like:
#include <sstream>
#include <vector>
#include <iostream>
using namespace std;
int main(){
string arr;
getline(cin, arr);
stringstream ss(arr);
string word;
vector<string> v;
while(ss >> w... |
65,767,658 | 65,767,769 | Allow a user to not only input multliline text but move up and edit previously entered lines | Im working on a crude console based text editor in C++ kind of like nano. I've already figured out a basic way of inputting multiple lines of text and writing it to a file correctly (input ends when they enter a code: //end). However, at the moment the user is unable to move upwards (using arrow keys) and edit lines th... | For advanced use, you need access to the console API.
For a simpler version, look at the primitive visual editors.
Editing a line consists of moving to the line, printing out the content, and then letting them insert or delete characters on that line.
Look at sed or ed or even vi.
|
65,767,777 | 65,768,041 | c++ file read/write infinite loop that rewrites the txt again | I'm trying to learn how to use file handling in C++.
I'd like to save and edit the contents of variables, however, there seems to be a problem with my logic because somehow the following program re writes the contents of the file infinitely.
#include <stdio.h>
#include <iostream>
int main(int argc, char const *argv[])... | This program exhibits undefined behavior. From C99 standard (which governs C standard library functions and is incorporated into the C++ standard by reference):
7.19.5.3/6 When a file is opened with update mode ('+' as the second or third character in the above list of mode argument values), both input and output may ... |
65,768,972 | 65,769,009 | C++ Stack Frame/Activation Record and 'this' pointer | This is my first post here, if I am messing something up I would appreciate any advice.
Does C++ implement an activation record? My experience with this has been largely with Java so I am unsure if it is the same for other languages.
If so, in C++ is it correct to say that 'this' is a pointer to the previous record on ... | this only exists within a class or struct. It does not exists within a free function.
this points to the object whose member function is called.
In your case, this points to an instance of Example and thus the type is Example*
I don't know the term ActivationRecord. C++ doesn't know the concept of a function stack, tha... |
65,769,079 | 65,769,154 | Erasing from a vector, passed by reference | I'm attempting to erase elements from a vector, by index, which has been passed by reference to some function. Typically, I'd do so like this:
void erase_element(vector<int> &my_vector, int index){
my_vector.erase(my_vector.begin() + index);
}
void make_vector(){
vector<int> my_vector = {1,2,3,4,5};
erase_... | One of i, j, or k will be the size of its respective container. The erase call for that element will be equivalent to a.erase(a.begin() + a.size()), or a.erase(a.end()). The iterator passed to erase must be valid and dereferenceable. The end iterator is not derefenceable and cannot be passed to erase.
You must check t... |
65,769,149 | 65,769,320 | Setter Function in my class not working with C++ | So I'm new to C++ and I made a simple program that stores a variable on a class, but the setter function I made never works. What is wrong with my code and why?
Main.cpp:
#include <iostream>
#include <chrono>
#include <thread>
#include <string>
#include "ExampleClass.hpp"
void yourMom(std::string test1, std::string te... | First of all, that function name is nice ;)
Second of all, no you cant do things like that in C++. Theres something called scopes in C++.
The Test example{}; in the yourMom function is instantiated inside the scope of that function. Which means that the Test example{a, b}; cannot be altered by the Test example{} which... |
65,769,395 | 65,770,112 | iterators implementation in STL containers | This is the sample code I've written, just a simple version to test out an iterator implementation:
template <typename T>
struct ArrayIterator {
using value_type = typename T::value_type;
using pointer = value_type*;
using reference = value_type&;
using self = ArrayIterator;
pointer ptr;
ArrayIterator... | You can’t use inheritance like you want because the code will have a catch-22 if you try. ArrayIterator will try to define its value_type as an alias of the array’s value_type before the latter has been defined yet. That is why you are getting the compiler error.
Your iterator has no need to access the Array class itse... |
65,769,735 | 65,782,411 | How to use gcc options --wrap=symbol in class method | This is a simple example that can help me print malloc params value
void *__wrap_malloc(size_t size)
{
printf("My malloc function!\n");
return __real_malloc(size);
}
But I want to use in class method, like that
class A{
public:
void test(int a)
{
printf("%d", a):
}
}
This using type gives ... |
how to use it correctly?
To use at all, you first have to have a symbol. So first move the inline function definition to be non-inline so a symbol may be generated for it. Then you need to find the mangled name of the symbol. So first correct your typos and compile the library to an object file:
// a.hpp
class A {
pu... |
65,770,499 | 65,776,536 | Cppcoro not accepting result from an constom awaitable struct | I decided to write my own awaitable in order to loader to learn how C++ coroutine works. For now, I want to build my own struct that is equivalent to this:
cppcoro::task<int> bar()
{
co_yield 42;
}
This is what I came up after reading CppReference's coroutine page. Which states Finally, awaiter.await_resume() is c... | The problem is, I think, that you declared your return type as task<int> but you don't actually co_return any int.
Does the problem go away if you co_return n?
|
65,770,504 | 65,770,658 | Reversing a doubly linked list doesn't show the first node in output | I am not able to print the first node after reversing doubly linked list.
I have used structure to create nodes , I can tell that I am correctly swapping the prev and next pointers but it doesn't give the output as expected.
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *next;
No... | You are returning the second node in the list instead of the first node. You are returning the most recent good value of curr->prev when you should be returning the most recent good value of curr (which will be the head of the reversed list).
The minimal code change is probably:
return prev->prev;
|
65,770,954 | 65,771,267 | How to reopen the form designer in Visual Studio 2019 while the `MyForm.cs` is missing? | I Created a windows form by using an empty C++ CLR project and got an error in a new tab of form designer and I closed that tab and fixed the error in MyForm.cpp by copying the following code:
#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThreadAttribute]
void Main(array<Strin... | I solved the Issue. If you have this Issue you can follow the steps to solve it.
According to the version I am using is VS Enterprise 2019 Registered
Steps:
Options>>Environment>>Preview Features >> and
Enable the Preview of .net Core SDK
Restart the app and open the project and double click on the MyForm.h under heade... |
65,771,106 | 65,771,379 | c++ function call for char as parameter | I have my function defined as the following
void initBoard(char board[3][3]){
for (int x=0; x<3; x++){
for (int y=0; y<3;y++){
board[x][y] = '-';
std::cout << board[x][y];
if (y == 0 || y == 1){
std::cout << '|';
}
else if (y == 2){... | In C++, the compiler needs to know these things about a parameter,
The type of the parameter.
The name of the variable (optional).
Default argument (optional).
When you define a parameter (in your case char board[3][3]), this just works as a container. Just picture this, when your at an airport, they give you buckets... |
65,771,290 | 65,773,440 | asio::io_service::run doesnt return after boost::asio::io_service::work is destroyed | As title says I'm having this problem when I can't understand why this thread
never stops running even after Client's destructor destroys asio::io_service::work variable
When I'm running this program output is always like this
Anyone sees what I'm missing here?
#include <boost/asio.hpp>
#include <thread>
#include <a... | I cannot reproduce the error on either compiler.
Here example for gcc 9.3 and boost 1.73
Normally the work destructor will use something like InterLockedDecrement on windows to decrement the number of outstanding works.
It looks like some compiler or io_service/work implementation issue.
As stated in comments, io_servi... |
65,771,392 | 65,771,433 | Why isn't shared_ptr implicitly converted to boolean when returning it in a function? | The following won't compile:
#include <memory>
class A;
bool f() {
std::shared_ptr<A> a;
return a;
}
int main()
{
f();
return 0;
}
and fails with:
Compilation failed due to following error(s).main.cpp: In function ‘bool f()’:
main.cpp:13:12: error: cannot convert ‘std::shared_ptr’ to ‘bool’ in return
... | Because the user-defined operator for converting an std::shared_ptr to bool is explicit:
explicit operator bool() const noexcept;
Note that an implicit conversion to bool in the condition of an if statement – among others – still happens even with an explicit user-defined conversion operator to bool :
std::shared_ptr... |
65,771,743 | 65,771,776 | How to transfer a table from a text file to C++ | I'm fairly new to C++ and I need some help.
The input is a text file that looks something like that:
5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
In the first line there is an integer N and then there are N lines with N numbers. How can I read the file and create a table (a 2d array)? Like that: [ [1,2,... | You don't need explicitely convert string to text via stoi. istream::operator>> does that for you:
ifstream in(filename);
int n;
in >> n;
vector<vector<int>> v(n, vector<int>(n));
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
in >> v[i][j];
|
65,771,918 | 65,772,083 | Error: No CMAKE_Fortran_COMPILER could be found for Visual Studio 2019 Fortran support | I am using CMAKE to build Open Source Projects (like those are available at GitHub etc.) and I also have installed Visual Studio 2019. There is a problem that CMAKE can not find Fortran compiler in my system whereas I've installed MinGW with Fortran compiler. The error is:
**The Fortran compiler identification is unkno... | You need to show where your fortran executable file to CMakeList.txt like
set(CMAKE_Fortran_COMPILER "C:/MinGW/bin/gfortran.exe")
EDIT 2 for Visual studio 2019:
If you want to produce Visual Studio 2019 solution
Download Intel® oneAPI HPC Toolkit here.
If cmake cannot find Fortran compiler add a cmake flag CMAKE_Fort... |
65,772,375 | 65,777,590 | How to glob file name pattern matching in linux using c++ 98 | Below is the piece of code, where I am trying to find file with matching pattern from directory path provided.
the expectation is to list all the files with pattern matching,
for example under "/usr/local" path, the below files are present
abc.txt axy.txt bcd.txt azz.txt bby.txt
with pattern matching code, i am expecti... | As mentioned in the comments, you'll only match on a file named exactly a, you globfree when you shouldn't and thrown an exception that you don't catch.
#include <glob.h>
#include <cerrno>
#include <cstring>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
std::vector<std::string> glob(con... |
65,772,848 | 65,773,138 | What does `VkDescriptorSetLayoutBinding::descriptorCount` specify? | Having read the docs and done a little looking around I'm still unclear.
The title largely sums up the question, but to ask a more specific question:
Given a shader with a single binding and it's binding being:
layout(binding = 0) buffer Buffer {
uint x[];
};
I know that setting VkDescriptorSetLayoutBinding::descr... | VkDescriptorSetLayoutBinding::descriptorCount says the number of descriptors (in your case uniform buffers) the binding has. For example, lets say that we have an array of buffers,
layout(binding = 0) buffer Buffers {
uint x[];
} buffers[5];
Then the VkDescriptorSetLayoutBinding::descriptorCount should be equal to... |
65,772,907 | 65,773,198 | Is it allowed to pass the address of a CPO as an algorithm parameter? | I remember having read somewhere that since C++20 it is no longer allowed to use the address
of a function in the namespace std, so that new overloads of such functions can be added without
breaking user code. Does this also hold for function objects?
In particular, can customization point objects be passed as paramete... | Yes, it is fine to pass CPOs as parameters. They are objects with static storage duration, similar to std::cout etc.
The difficulty of passing overloaded functions as parameters is one of the main reasons for CPOs to exist.
|
65,773,128 | 65,773,204 | How do predicate and/or predicator data members and/or member functions work in C++? What does (elem.*predicator)() do in the following snippet? | I have the following snippet of code that seems to be making use of predicates but I am unable to figure out what (elem.*predicator)() does. I tried looking for some easier to understand documentation regarding the same on the web as well as SO (closest thing I found was this) but couldn't find anything that could help... | .* and ->* are the pointer-to-member operators.
Those are pointers that can store which method of a class to call.
See [expr.mptr.oper] in the standard or questions like Calling C++ class methods via a function pointer.
|
65,773,157 | 66,033,075 | g++ optimization breakes for loop | So, I have this codesnippet here
for (int t = WILSON_TEMPORAL_START, t_i = 0; t <= WILSON_TEMPORAL_END; t++, t_i++)
{
for (int r = WILSON_SPATIAL_START, r_i = 0; r <= WILSON_SPATIAL_END; r++, r_i++)
{
std::cout << r << " " << WILSON_SPATIAL_END << std::endl;
wilson_loop[conf_id][t_i][r_i] = comp... | I just solved the problem, I made an error in defining the preprocessor constants. I'm still not sure, why it changes output when using a different optimization mode, but it works now :)
|
65,773,437 | 65,773,756 | How Do while inside switch statement works in c | I have a code snippet where a do while statement is inside switch condition of case0, by default the case value is case1 but it seems executing case0. The output of the program print is 6. How is this possible, can someone explain the flow of code here. Thanks in advance for your answers.
int main()
{
int a = 1, t ... | Switch cases are similar to labels for goto.
You start at case 1, which is inside the loop – effectively using that as your starting point – and then execute the loop normally while "falling through" the cases as you go.
Here is the equivalent using goto:
int main()
{
int a = 1, t =0,n=2;
if (a == 0)
go... |
65,773,703 | 65,774,313 | Problem compiling json with visual studio | I have another program that uses json but I do not manage to make it compile. I think that the problem is related to the library I am using to parse a Json file, so, I coded a small code to try to understand better how it works.
When I am compiling the program using visual Studio 2019 in Windows the following errors ap... | It seems like you are using an old interface of this library: https://github.com/open-source-parsers/jsoncpp ?
There is this error reported e.g. : https://github.com/open-source-parsers/jsoncpp/issues/815
This is a warning that says you should not use the old interface but instead the newer one. The warning is handled ... |
65,774,060 | 65,774,273 | Build a library in C++ which does not require class instantiation | Sorry if this seems to be a beginner question, but I can't seem to work out the best approach for my C++ library. I have build a static library, which contains driver API handling code. Currently in order to use it in a higher layer of the software (a simple app with GUI), I need to link the library to the project and ... | Supposed you have this:
#include "myLibrary.h"
// Some GUI code here
MyLibrary *mLib;
mLib = new MyLibrary;
// Using the library methods
mLib->startProcess();
Your library can hide the MyLibrary object like this:
startProcess() {
static MyLibrary* myLib = new MyLibrary;
myLib->startProcess();
}
Such that... |
65,774,133 | 65,828,982 | Using Tesseact OCR in an existing Visual Studio C++ project | I want to use the Tesseract-OCR library with my already existing C++ project. I followed the steps mentioned in this answer.
I cloned the Github repo from here
Ran the build_tesseract.bat
Opened 'tesseract.sln' and set 'tesseract' as startup project before compiling it
for both 'release' and 'debug' configurations
Aft... | For anyone looking to use Tesseract-OCR with Visual Studio 2017+, I found an alternative method(Not exactly, It was straight to my face all along).
Using VcPkg seems to be the best and easiest way as mentioned in Tesseract-OCR documentation itself.
Install VcPkg from the instruction here
Navigate to the installation f... |
65,774,714 | 65,774,865 | Is it possible to overload (shadow) a virtual function? | I would like to shadow the virtual function of a base class, and introduce a new virtual function with the same name and same signature, except for the return type.
Something like:
struct A {
virtual int f() = 0; // Newly introduced method: A::f.
};
struct B: public A {
int f() final { return 1; } ... | Overloading is impossible without changing the function signature (which the return type is not a part of). But thanks to default function arguments, we can have different signatures, but still call with the same number of arguments. Using something like C++20's std::type_identity (easily implementable in any standard ... |
65,774,829 | 65,828,949 | How do I link in all of PyTorch with a pybind11 .so? | I have a pybind11 c++ project which uses the pytorch c++ api:
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <math.h>
#include <torch/torch.h>
...
void f()
{
...
torch::Tensor dynamic_parameters = torch::full({1}, /*value=*/0.5, torch::dtype(torch::kFloat64).requires_grad(true));
torch::opt... | I eventually found I needed to use the Anaconda version of torchlib rather than my own, as well as using Torch's CppExtension. Here is my working setup.py:
from distutils.core import setup, Extension
from torch.utils.cpp_extension import BuildExtension, CppExtension
def configuration(parent_package='', top_path=None)... |
65,774,857 | 65,775,542 | Find the index of the first occurrence of even number in the array, with runtime cost O(log(n)) | I have to implement an algorithm, with runtime cost of O(log(n)), that find the first occurrence of an even number in an array with these properties:
The first elements of the array are odd, and the following ones are even
I don't know how many elements are odd, and how many are even, but i know that at least there is... | There are several problems:
You don't have a termination condition for the recursion.
You recurse into both halves of the array, destroying the logartihmic complexity even if you add that termination.
Your subdivision method is mysterious; you should look at the element in the middle and then choose one of the halves.
... |
65,775,014 | 65,775,536 | How to use std::indirect_result_t in C++20 | std::indirect_result_t is introduced in C++20 and I am wondering how to use std::indirect_result_t correctly. Could someone give an example usage of it?
| You use it to name the result type of dereferencing a pack of arguments into a callable.
Given a callable f of type F, and indirect arguments is... of types Is..., std::indirect_result_t<F, Is...> is equal to decltype(f(*is...))
|
65,775,033 | 65,775,130 | Optional class members without runtime overhead | I have the following very general problem that I have not found a satisfying solution to yet:
So I want to have two classes A and AData that are basically identical except that the latter has an additional attribute data and each of the classes supports a function foo(), which is different because it depends on the exi... | You can use static polymorphism and curiosly recurring template pattern.
Both A and AData provide foo() but behaviour is class-specfic through doFoo(). Also not using virtual dispatch avoids runtime overhead of vtable lookup.
template <typename TData>
class Abase
{
public:
void foo()
{
static_cast<TData*>(... |
65,775,436 | 65,794,218 | How to use OnMouseLeftButtonDown on WPF for C++ | I'm doing a demo project on Windows Presentation Foundation with C++, and I'm trying to invoke a callback function when the user clicks the mouse anywhere on the screen.
I just have an empty main page:
public ref class MainPage sealed
{
public:
MainPage();
};
I know that I must override OnMouseLeftButtonDo... | So the problem was that my project was configured for UWP, not WPF. Silly me...
Thanks for the tips!
|
65,775,508 | 65,778,070 | Android JNI crashes (SIGABRT) | I have an Android Kotlin application that calls a simple JNI function, the latter calling a C++ singleton.
There is a crash (SIGABRT) when I call the JNI function. I can't see what is wrong...
Kotlin code :
stopProcessing() // Calls stopProcessing JNI function
JNI code :
extern "C"
JNIEXPORT void JNICALL
Java_com_tb_o... | I had to remove the [[noreturn]] statement in the C++ singleton class.
Thanks to Richard Critten who commented (Add an answer and I'll accept it).
|
65,775,589 | 65,776,484 | C++ container to support row and column lookup | Given several data types, I'm trying to implement a method to determine which type can be converted to by all other types.
Int -> Float -> Boolean
A int can be converted to a float which can converted to a boolean. However this is not the case for the other way round, e.g. a boolean cannot be converted to a float.
So g... | There is std::is_convertible, but I think your table doesnt match the definition of std::is_convertible (eg std::is_convertible<int,float>::value and std::is_convertible<float,int>::value are both true).
Nevertheless, your table only depends on types, hence there is no need to make the table occupy memory. You can enco... |
65,776,190 | 65,778,236 | Get member from last possible class of a parameter pack | I want to get the value of a member variable of the last possible class in a parameter pack.
For eg. I want getLastB(a_, b_, c_, d_) to return 100 in the code below (the value of c_.b), and not 40 (the value of b_.b)
#include <type_traits>
#include <iostream>
#define ADD_HAS_MEM_VAR_CHECKER(var, name) ... | You need to remove reference from T
static bool const value = sizeof(chk<typename std::remove_reference<T>::type>(0)) == sizeof(yes);
Your code would also fail for situations like when the last one contains b, or b is not of type int.
If you can use C++17 you can write it like this:
template<typename T> ... |
65,777,139 | 65,777,199 | Handling circular dependencies in C++ | So, I know that there are many questions on stack overflow out there that are trying to handle circular dependencies. But none of those could really answer my question, if it is possible to have two classes know each other, and, more importantly, access information from each other. So, basically, I have read that you c... | Since the C++17 standard you don't need the full EntityBase class definition for the Scene class, only a forward declaration:
#pragma once
#include <vector>
#include <string>
class EntityBase; // Forward declaration
class Scene
{
public:
std::vector<EntityBase> entities;
std::string name;
Scene(std::str... |
65,777,274 | 65,777,972 | Why is my unique_ptr immediately deleting itself? | I'm playing with a couple of concepts that I am still rather new to. What I am trying to do is dependency inject a "Screen" object into the private member "TempCtrl::mScreen" using unique pointers. I believe I am implementing the design pattern correctly, but I have never done this with unique pointers and it would s... | Using a deleted function doesn't mean something is deleting itself.
A deleted function in C++ is a function which, when the C++ compiler thinks it should call it, it generates an error on purpose.
Here, your deleted function is your unique_ptr’s "copy constructor".
A copy constructor is how you take an object in C++ an... |
65,777,697 | 65,805,188 | Updating QLineSeries in Chart doesnt work at all | I'm melting my brain right now and cant figure out, why my chart isn't updating at all.
I've declared the following in my applications *.h-File:
QT_CHARTS_NAMESPACE::QChart* chart;
QT_CHARTS_NAMESPACE::QLineSeries* series;
QT_CHARTS_NAMESPACE::QChartView* chartView;
In my constructor of my mainwindow *.cpp file I've ... | I found out, that createDefaultAxes() caused this problem. I inserted both (x,y) axis insted of createDefaultAxes() like so:
QT_CHARTS_NAMESPACE::QValueAxis *axisX = new QT_CHARTS_NAMESPACE::QValueAxis;
axisX->setRange(0, this->series->points().length());
axisX->setTickCount(10);
axisX->setLabelFormat("%d");
c... |
65,777,820 | 65,778,233 | How to std::reverse_copy bytes of an int into char array | I'm learning socket programming and need to convert data from host byte order(in my case LITTLE ENDIAN) to network byte order. So I need to swap the byte order of the data that I will be sending. So, I used to std::memcpy say integer into a temp char array, then swap the bytes of that temp char array. But now I'm tryin... | You have too many calls to std::begin. You want just:
std::reverse_copy(reinterpret_cast<const char*>(&a), reinterpret_cast<const char*>(&a) + sizeof(decltype(a)), r_arr);
|
65,778,085 | 65,780,037 | Unable to use swap without temparary variable | Quick sort program
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
// constant
enum {MAX = 10};
// class
class A
{
private:
int arr[MAX];
public:
A() // constructor
{
srand(time(0));
for(int i = 0; i < MAX; i++)
arr[i] = rand() % ... | The error is not because of swap, it arises from the calling function that has send a same variable to be swap. This causes the arithmetic to give zero for a-b.
In the following code:
int A::Partition(int left, int right)
{
int pivot = arr[right], i = left - 1;
for(int j = left; j <= right-1; j++)
{
... |
65,778,129 | 65,870,926 | JNI - Weird behavior using RxJava in native cpp callback function | I have a c++ function that I want to call from my Kotlin code.
That c++ function gets a callback function as an argument, doing some work and calls the callback when completes.
I already done it a few times before and everything was OK. However, I want to wrap it in a way so instead of passing a callback, it will retur... | So after some research I found:
When I call a C/C++ function from Java, the JNI does not create any new thread behind the scene. [see here]. Hence,
The code runs synchronously, meaning - the subject emits an item and then the function returns the subject and being subscribed. So after the subscription, it missed the e... |
65,778,204 | 65,778,505 | C++ Class getting input | I wanna ask you quick question. How can get the name, surname, id and age as an input? These are must be taken as input and variables must be private. How should I code about it?
#include <iostream>
using namespace std;
class Employee{
private:
string Name;
string Surname;
int IdNumber;
int age;
publ... | One simple way is to use the constructor you have defined
int main()
{
string name, surname;
int id, age;
cin >> name >> surname >> id >> age; // read user input
Employee someone(name, surname, id, age); // create employee from user input
...
}
Using a constructor is the normal way to give c... |
65,778,607 | 65,778,936 | Deduce template arguments from std::function parameter types | Why the following class A can't deduce its template parameters in the code below:
#include <functional>
template <class... Ts>
class A
{
public:
using Func = std::function<void(std::decay_t<Ts>...)>;
A(Func func) : m_func(func)
{
}
private:
Func m_func;
};
int main()
{
//compiles
A<int... | Two issues.
Implicit conversion (from lambda to std::function) won't be considered in template argument deduction; which causes deduction failing.
The existence of std::decay_t results in non-deduced context; then Ts can't be deduced.
The following code compiles.
#include <functional>
template <class... Ts>
class ... |
65,778,697 | 65,779,831 | How to release BYTE memory? | Quick question: do I have to / how do I release memory from this allocation of memory?
unsigned char *uString = new unsigned char[4096]();
And if I have to, would I do it like this?
free(uString); delete[] uString;
| You use the free function when you allocate memory with the C functions like malloc calloc and more.
In c++ you use the operators new and delete (Also thier array friends new[] and delete[]).
When you want to delete object created with the operator new[], you call the operator delete[].
For example:
int main(void)
{
... |
65,778,909 | 65,779,085 | Template class with template constructor specialization for initializing a templated base class | I have a template base class with a template parameter of type bool. The constructor parameter list of this base class depends on whether the template parameter is true or false. I want to derive from this class another template class with a template parameter that is any type. I need this derived class to call the cor... | After playing around with this, a little bit, I came up with this, which I guess falls under the category of "workaround", which you are willing to consider:
template<class T> class CL :
Base<is_integral<T>::value>
{
public:
CL() : CL{ is_integral<T>{} } {}
template<typename U=T>
CL(std::true_type) : B... |
65,778,974 | 65,781,045 | Undefined reference to `libbgp::BgpFsm::tick()' | I started working with c++ a few weeks ago, and I started a new project to start learning more. I'm encountering an issue with an external dependency. I'm trying to use a library called:
libbgp, and I installed it base on their documentation.
Here is my code:
https://gist.github.com/amb1s1/9b2c72294da0ec9416810c8686d3a... | Before running the executable, you have to tell it where to find the libgdp.so file, if it is not stored in a standard place such as /usr/lib or /lib. Following should help you:
$ export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:/usr/local/lib"
$ ./ambgp
If you do not want to export the LD_LIBRARY_PATH each time you start t... |
65,779,069 | 65,779,070 | Compiler variance for the type of deduced (non-type) template parameter | Consider the following example:
#include <type_traits>
struct A {};
template <A const i> void f() {
static_assert(std::is_same_v<decltype(i), A const>); // #1
A& ar = i; // #2
}
int main() {
f<A{}>();
}
which both Clang(1) and GCC(1) rejects with the foll... | Both GCC and Clang are (probably) correct to emit errors for both #1 and #2 for f.
As per [temp.param]/6 [emphasis mine]:
A non-type template-parameter shall have one of the following
(possibly cv-qualified) types:
(6.1) a structural type (see below),
(6.2) a type that contains a placeholder type ([dcl.spec.auto]), o... |
65,779,552 | 65,779,821 | Function with loop as parameter | I have the following two function bodies, let A be a set of instructions, and let B(i,A) be another set of instructions that depends on A (for example a variable that is defined in A is used in B) and i:
//do A
for(auto i = 0; i < 100; ++i) {
//do B(i, A)
}
and
//do A
for(auto i : someNumbers) {
//do B(i, A)
}
Is... | Yep, with the constraint that the common function should be inlinable.
You can encode the loop condition in an iterator pair or, ideally, a range.
Range version, if supported in C++20 mode:
template <typename Range>
void looper(Range r) {
for (auto i : r) {
B(i, A);
}
}
use std::ranges::iota_view for... |
65,780,170 | 65,780,212 | How can I template a 2D container in class? | template <class T>
class X {
//Member functions don't have template variables.
private:
T<T <int> > array;
};
int main() {
X<vector> obj;
}
What should I write to template<> part to achieve that?
| If you want to pass a class template such as std::vector as an argument, then the template parameter needs to be a template template parameter.
template <template<class...> class T>
class X
{
private:
T<T <int> > array;
};
The template parameter of the template template parameter needs to be a variadic template ... |
65,780,332 | 65,780,403 | lambda move capture for std::thread | I am implementing a timer library inspired by Simple Timer
#ifndef CMS_TIMER
#define CMS_TIMER
#include <thread>
#include <chrono>
#include <atomic>
class Timer {
std::atomic_bool clear = false;
public:
template<class Function, class... Args, class Rep, class Period>
[[maybe_unused]] void setInterval(con... | template<class Function, class... Args, class Rep, class Period>
void Timer::setInterval(const std::chrono::duration<Rep, Period>& sleep_duration, Function&& f, Args&&... args) {
this->clear = false;
std::thread t([this, f=std::move(f), sleep_duration, args = std::make_tuple(std::forward<Args>(args)...))]() {
... |
65,781,185 | 65,782,606 | Translate C# regex with lookbehinds to C++ | @polygenelubricants answer to this question includes a C# regex that is used to split a PascalCase string into separate words, namely:
Regex r = new Regex(
@" (?<=[A-Z])(?=[A-Z][a-z]) # UC before me, UC lc after me
| (?<=[^A-Z])(?=[A-Z]) # Not UC before me, UC after me
| (?<=[A-Za-z])(?=[^A-Za-z... | You can change the regex to not use lookbehind: [A-Z](?=[A-Z][a-z])|[^A-Z](?=[A-Z])|[A-Za-z](?=[^A-Za-z]).
In the end the original regex was looking for the beginning of the new word, so it had to look behind for the end of the previous word. But we can look for the end of a word and look ahead for the beginning of the... |
65,781,309 | 65,781,639 | C++ - Why is this implementation of fibonacci memoization using map so slow? | I am trying to implement a fibonacci function in c++ using memoization. My implementation works but is extremely slow. Why is my implementation so slow? I've seen a similar implementations in javascript using an object for memoization and they were blazing fast. Is it because I used the map data structure?
#include <io... | , std::map<unsigned short, unsigned int> memo)
that is a copy of a map.
You are copying your memoization map every call, then forgetting anything you added to it.
unsigned int fib(unsigned short n, std::map<unsigned short, unsigned int>* memo = nullptr);
unsigned int fib(unsigned short n, std::map<unsigned short, uns... |
65,781,609 | 65,784,883 | Include all source file for build | I have C++ project in my Visual Studio. Additionally I placed directory with source files in it in order to use them like library in my main project.
Everything works fine while code browsing. I can define includes of library headers and navigate to functions.
I got problem during project build. I got a lot of linking ... | Visual Studio does not include all the files in a directory on its own. You need to explicitly include them (you dont have to do this if you add a file within the Solution Explorer or within Visual Studio). Else it wont be listed to the compiler.
To include them, go to the solution explorer and select "Show all files".... |
65,781,641 | 65,784,065 | I'm trying to format a template using {fmt} | I have a simple template somewhat like:
template <typename T, T Min, T Max>
class LimitedInt {
public:
static_assert(Min < Max, "Min must be less than Max");
explicit LimitedInt(const T value)
{
setValue(value);
}
void setValue(const T value)
{
if (value < Min || value > Max) {
th... | The usual rules of specialization apply. Specifically, you should make formatter a template and pass the template parameters to LimitedInt:
template <typename T, T Min, T Max>
struct fmt::formatter<LimitedInt<T, Min, Max>> {
constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
auto format(const ... |
65,781,765 | 65,782,030 | std::multiset comparer does not compile | Why the code below does not compile?
#include <set>
struct FatKey { int x; int data[1000]; };
struct LightKey { int x; };
struct Compare
{
bool operator() (const FatKey& fk, const LightKey& lk) const { return fk.x < lk.x; }
bool operator() (const LightKey& lk, const FatKey& fk) const { return lk.x < fk.x; }... | If you want to use the overloads of find which take an equivalent type and you are using a custom comparator class that class must have a is_transparent member type:
#include <set>
#include <iostream>
struct FatKey { int x; int data[1000]; };
struct LightKey { int x; };
struct Compare
{
bool operator() (const F... |
65,781,922 | 65,781,977 | Performance problems with the C++20 spaceship operator? | Since C++20 the standard library uses the spaceship operator to implement comparison for strings and vectors (according to this video). I am worried that this comes with a potentially huge performance penalty!
Let me explain on the example of the operator != for string:
When I write str1 != str2, the compiler now tran... | That was already addressed by the standardization committee in http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1185r2.html. That change says that a == b and a != b are not calling operator <=>, they are calling operator== and operator !=. The behavior that you describe was a temporary version of the C++20 stan... |
65,781,956 | 65,782,236 | c++ program has triggered a breakpoint on operator[] | I'm creating class Student, and I'm getting an error:
program has triggered a breakpoint
on operator[]. Please help me and show what's wrong, and what is missing.
Fixed:
#include "stdafx.h"
#include <iostream>
class Student {
public:
Student();
~Student();
void Show();
private:
char* Name;
char* Su... | You struct student has pointers, exactly 3 pointers!
It is obvious calling delete[] stud; without handling deletion of char* Name, char* Surname and char* DateOfBirth members of each student object, leads to HEAP CORRUPTION ERROR
|
65,782,061 | 65,782,098 | Why is there no memory leak with non-virtual destructor | I was told that there is no memory leak of B->b in the following code:
struct A {}; // no virtual destructor
struct B : public A {
int b;
}
int main() {
A* a = new B {};
delete a;
}
If it's true, could you explain why?
| Because that is how undefined behaviour works. Memory isn't guaranteed to leak. But neither is it guaranteed to not leak. Any behaviour is possible as far as the language is concerned.
why this is Undefined Behaviour
Because a non-virtual destructor is called through a pointer whose dynamic type is of another (derive... |
65,782,177 | 65,782,842 | Getting unexpected numbers when reading integers from an array | I am trying to read integers from a file to an array, but when I try to read the elements of said array, I get numbers that have little to nothing to do with the numbers in the file.
#include <fstream>
#include <istream>
#include <iterator>
#include <string>
using namespace std;
//Main Function
int main()
{
//Decl... | Note: int a1[s1], a2[s2]; doesn't comply with the ISO C++ standard. For details, see Why aren't variable-length arrays part of the C++ standard? If you cannot know the length of an array prior to runtime, consider using std::vector.
It is as @user4581301 says, you need to rewind the files, since std::distance() will re... |
65,782,522 | 65,782,621 | How to use a shared pointer of a pure abstract class without using reset and new? | In C++ how do I get to use a shared pointer of a pure abstract class without using reset and new?
The example is a little contrived but illustrates the problem I am encountering.
Look at the run() method: reset works but the commented out lines don't...
#include <iostream>
#include <map>
#include <memory>
using namesp... | Instead of new Bar write make_shared<Bar>, as you are making Bar, not Interf.
Bar b;
innerInterf = make_shared<Bar>(b); // copy constructed? (no idea if that is what you want?)
innerInterf = make_shared<Bar>(); // calls Bar::Bar()
Because I see non-virtual destructors, you might want to research about when to use vir... |
65,782,580 | 65,782,707 | Copy part of a string directly to vector error: no match operator= | I want to implement a simple function that will split std::string based on the delimiter ,\s.
For example, split("Emerson, Lake, Palmer") should yield std::vector<std::string> of
Emerson
Lake
Palmer
I discovered, that it could be simply achieved with back_inserter() (the example is very helpful) . The function below i... | When you submit a range as 2 iterators to std::copy() you mean that you want to copy each element that such iterators point to to the target. But std::string::iterator points to individual chars and I do not think you want to copy each symbol into the vector separately. Instead you can create a std::string from pair an... |
65,782,854 | 65,783,054 | Unexplainable result of an expression | I'm currently working on a project where I've got stuck due to "out of range", "memory access violation" and other similar issues. Having spent much time trying to figure out where the problems come from, I came to a trivial piece of code like this:
#include <iostream>
#define RANDOM(min, max) min + RAND_MAX / ((RAND_... | This difference is caused by the different way theses two languages handle decimal numbers.
C++ compilers will use by default the int type when you have natural numbers in your code. However, since the int type does not allow decimal number, it rounds down to the nearest unit each time you make a division in your code ... |
65,783,206 | 65,783,325 | C++: Conditionals in template meta programming | I am implementing a program generating the next prime number from a given number NUMBER known at compile time with C++ template metaprogramming. However, I am currently stuck because I need a conditional value in my template. So I am searching for something like a ternary operator equivalent in C++.
My current approach... | Usually I see this sort of problem solved through specialization
template<int P, bool B = is_prime<P>::value>
struct next_prime
{ enum { value = next_prime<P+1>::value }; };
template <int P>
struct next_prime<P, true>
{ enum { value = P }; };
If you can use C++11 or newer, instead of defining a value, I suggest i... |
65,783,212 | 65,791,219 | cout float without trailing zeros and with only 3 digits after the | I'm trying to print a float variable, I want it to have only 3 digits. However, if they are zeros, they do not end up printing.
For example
1.230 -> should be out like this 1.23
1.456432 -> 1.456
1.4000006 -> 1.4
currently I'm using
cout<<fixed<<setprecision(3) <<res2<<endl;
and its still shows more zeros, like 0.010... | It looks like you don't want to do any kind of rounding. I think this function will do what you want:
#include <vector>
#include <iostream>
#include <string>
std::string remove_trailing_zeros(float num, int precision)
{
const int maxPrecision(6);
if (precision > maxPrecision) {
throw std::invalid_argum... |
65,783,577 | 65,783,689 | Error when applying a function multiple times | I wrote a function to find all combinations of integers between two bounds. To do this, I wrote a function with the same name that finds all combinations of integers between two bounds of a certain size.
In main, I set up a loop to call this function multiple times. When it is ran more than once with bounds that are su... | I don't understand the algorithm, but the problems are clear enough.
Step one, reduce the size of the problem I chose
#define VAR1 1
#define VAR2 2
Run the code, crash in operator[] here,
if (i >= numItems || combo[i]+1 != combo[i+1])
Values of variables
combo = vector of size 1
numItems = 1
i = 0
combo[i+1] is a su... |
65,783,864 | 65,787,204 | How to create a project and add existing projects in Eclipse? | I am using C/C++ perspective in Eclipse.
The Eclipse is integrated with ClearCase VOB and inside the VOB, each specific module has been created as a project.
So in effect, those modules have to be imported as a project into Eclipse (at least, that is what I am aware of and have done).
Consequently, on my project explor... | First, make sure to use a snapshot ClearCase view, not a dynamic one, in order to speed up the compilation time.
Second, try and create a single project in a separate workspace, as described here, where you would:
reference your different module folder as sources
create a Makefile which would compile each project (sin... |
65,784,795 | 65,784,814 | A function that take another function as parameter, "No matching function error" C++ | I'm writing a series of sorting algorithm and calculating the time execution of each algorithm.
#include <iostream>
#include <vector>
#include <chrono>
#include <utility>
#include "sort.h"
template<class T>
void timeTaken(void (*f)(std::vector<T>& nums))
{
auto t1 = std::chrono::high_resolution_clock::now();
... | display is a template; template parameter T can't be deduced in timeTaken(&display);.
You can specify the instantiation by static_cast,
timeTaken(static_cast<void (*)(std::vector<int>&)>(&display));
Or
timeTaken(&display<int>);
Or specify template argument explicitly.
timeTaken<int>(&display);
Other issues:
There'... |
65,785,301 | 65,785,523 | Why do taller letters appear deformed when rendering text with FreeType in OpenGL? | I have managed to draw text with FreeType in OpenGL 4, but the taller letters (e.g. g, d, f, etc.) are somehow being drawn too tall. This is what it looks like. This is what it is supposed to look like. The tall letters are too tall, while the "normal height" letters are just fine.
struct FontChar {
float tx; // te... | I have found the issue. My instincts were correct; the issue was related to the height of the texture atlas. I was not plugging the heights of the glyph bitmaps into the actual vertices, I was instead using the entire height of the texture. All I had to do was pass the heights of the characters into the FontChar struct... |
65,785,318 | 65,785,426 | Is it possible to reserve function reference into unordered_map or vector? | i am making some callback system and i wonder if i can reserve function reference to unordered_map so that i can invoke it later.
float func_imp(float x)
{
return x;
}
int main()
{
using Tumap = unordered_map<int, float(&)(float)>;
Tumap umap;
umap.emplace(0, func_imp);
(umap[0])(10.1); //a referenc... | Regardless of wether this is something you should be doing or not (the comments under your question are covering this already), it's still worth answering your question as is.
The [] operator of map types is a veritable swiss army knife. You can do a lot of things with it.
You can assign a value.
You can lookup the va... |
65,785,388 | 65,788,792 | How can I get a Win32 HANDLE with FILE_WRITE_ATTRIBUTES access for a StorageFile or StorageFolder in UWP? | I am trying to implement Notepad++ style toggling read-only flag for files in an UWP text editor. I tried using SetFileAttributesFromApp but it fails with Access to the path is denied for sensitive file types like Batch files and VBScript files. Then I tried using SetFileInformationByHandle which requires UWP app to ge... | There is no such API to support getting FILE_WRITE_ATTRIBUTES access to the handle created from a StorageFile when the StorageFile instance has read only flag.
If you want to edit the dragged file in your UWP text editor, you could copy the dragged file into the LocalFolder. The copied file will have read and write acc... |
65,786,169 | 65,792,913 | How to use structs in C/C++? | The following is my code and I am getting some errors. Could someone help me understand these errors please?
Struct List :
struct List{
int size;
int arr[];
};
Append Function :
int [] append(struct List a2, int a) {
int size = a2.size + sizeof(int);
int p [size]; //= (int *)malloc(size);
for(int ... | Most of your problems stem from the List structure:
struct List {
int size;
int arr[];
};
The line int arr[]; creates a "variable-length array". You have confused this here with a "dynamic array". A variable length array is simply a trail of bytes abstracted to part of a struct.
Your append function does not ... |
65,786,293 | 65,786,422 | How to compare two strings? Here is my code , it is not giving desired results. It is not comparing properly | My code is all about finding that a particular name exists in names.txt or not
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream file("names.txt");
string names[6];
string test;
cin>>test;
for(int i=0;i<6;i++)
{
getline(file, names[i]);
}
for(int i=0... | C++ std::cin reads until the next whitespace, so only the firstname will be read in your code. You can solve this problem by using std::getline(std::cin, test).
|
65,786,405 | 65,786,625 | What do the different Initializations of Eigen::RowVectorXf do? | I am reading through some docs, and found two different initializations and usages of new with Eigen::RowVectorXf. I could not find what the difference was through the documentation, or even that this was a possibility, and was hoping for some clarifications.
Here is the first version:
std::vector<Eigen::RowVectorXf*> ... | Yes, Eigen::RowVectorXf(5) and Eigen::RowVectorXf(1, 5) both declare a 1x5 row vector.
Neither constructor is deprecated. To clarify, RowVectorXf is just a typedef for Matrix<float, 1, Dynamic>, that is, a float-valued matrix with 1 row. As listed in the Eigen::Matrix documentation, Matrix (and hence also RowVectorXf) ... |
65,786,872 | 65,787,006 | Pass a templated function as argument to another function | Problem
I am trying to make a function which searches for a type in a parameter pack, then creates a lambda which invokes another function with that type as a template parameter e.g.:
auto fn = findType<MyType, SomeType, OtherType>("OtherType");
fn(otherFn) == otherFn<OtherType>();
I would like to write something like... | Function parameters are variables. Not variable templates; just regular old variables. And a non-template variable cannot be given template parameters.
You cannot pass a function template anywhere. You can only pass a particular instantiation of a function template. The closest you can get to what you want is to pass a... |
65,787,465 | 65,787,581 | Comparing occurrences of characters in a string C++ | I am moving from Python to C++ and I am not well versed with the latter.
I have a string s, which contains exactly one character "a" and one character "b" while the other characters are redundant.
I want to know whether "a" occurs first or "b" does.
In Python, I would do it something like this
s = "??a????b"
if s.find(... | You can use the std::string.find() member function with a single char argument – the version (4) overload shown here.
#include <iostream> // NEVER use the <bits/stdc++.h> header file!
#include <string>
using std::cout; // Also not best practice to use "using namespace std"
using std::cin;
using std::endl;
using std:... |
65,787,647 | 65,787,794 | Intended invalid intialization from rvalue using *this | In C++ it is impossible to bind an r-value argument to a non-const l-value reference. But I noticed that when I call on the r-value object the method returning *this it compiles somehow.
Example:
Obliviously this snippet od code will not compile
class X
{
};
void bar(X&)
{
}
int main()... | As mentioned in a comment, foo returns an lvalue, not an rvalue, so passing it to bar is just fine.
If it feels strange that X{}.foo() returns an lvalue even if X{} itself is an rvalue, think of foo() as a function which (implicitly) takes this and returns something (which happens to be what this points to) by lvalue r... |
65,787,725 | 65,794,889 | How to define a class and method in DDS idl file? | I am new to DDS.... so far I have little experience in OpenDDS and CycloneDDS
Is it possible to define a class inside the idle file and have member variables and member methods? or only structure and primitive data types are supported in DDS standards?
| The IDL language is defined in the OMG IDL specification. It consists of a number of building blocks that include Core Data Types, like the structures and primitive data types that you mentioned, and Interfaces, that includes the methods you asked about.
However, only a subset of those building blocks is used by DDS. F... |
65,788,689 | 65,788,821 | function doesn't change object attributes in c++ even with reference | I'm trying to change a balls position by calling a function
struct ball
{
int heading = north_east;
bool visible = true;
int pos_x = ball_start_x;
int pos_y = ball_start_y;
char c = 'o';
};
void move_ball(ball *target_ball)
{
switch (target_ball->hea... | You forgot a bunch of break statements, all of the lines following the case north_east are executed, and the result of adding two and subtracting two is 0
switch (target_ball->heading)
{
case north_east:
{
target_ball->pos_x ++ ;
target_ball->pos_y -- ;
... |
65,788,866 | 65,789,095 | std::random - On Windows always I get the same numbers | After compilation, the program always returns the same results. Unpredictably, the code works correctly on Linux ...
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distribut(1, 6);
for (int i=0; i < 10; i++)
{
std::cout << distribut(gen) << ' ';
}
Compil... | The problem here is that the std::random_device object (which you are using to seed your std::mt19937) may produce the same seed, each time (although it doesn't on my Windows 10 + Visual Studio test platform).
From cppreference (bolding mine):
std::random_device may be implemented in terms of an
implementation-defined... |
65,789,273 | 65,856,718 | Best extension mechanism to be able to adopt third-party dependencies? | I am currently trying to get my feet wet with concepts. Let us assume that I have a concept:
template <class T> concept Initable = requires (T&t) { { init(t) }; };
// just for demonstration purposes, real concept makes more sense ...
and I want to provide an adoption layer for a third-party class like std::optional ... | Resolving to any function that is visible during template instantiation is clearly against the principles of two-phase lookup. I decided to take a different approach instead and use a dummy parameter that is defined in a separate customization namespace:
namespace CP { // CP = CustomizationPoint
struct Token {};
}
... |
65,789,385 | 65,793,209 | Using make_shared with emplace_back and push_back - any difference? | some_vector.push_back(make_shared<ClassName>());
some_vector.emplace_back(make_shared<ClassName>());
I want to check that my understanding is correct that for make_shared and in general for all other functions that returns an object those two calls are identical. Here make_shared will create a new shared_ptr, and then... | vector<T>::push_back has a T&& overload, which does the same as the vector<T>::emplace_back T&& version.
The difference is that emplace_back will perfect-forward any set of arguments to the T's constructor, while push_back only takes T&& or T const&. When you actually pass a T&& or T const& the standard specification ... |
65,789,552 | 65,789,665 | Why does the variable lose its value after exiting for loop? | I'm new in the programming world. I couldn't find anything related online.
My variable num doesn't hold the value assigned to it inside the for loop.
It keeps getting 0 after it exits the loop. I'm pretty sure I have done this before: initialize a variable before a for loop, change its value inside for and then use it ... | The post increment num++ will increment num but return its old value.
You probably meant
num = (A[i][j] > B[i][j] ? num + 1 : num );
or, a bit shorter and a bit clearer in my opinion
if(A[i][j] > B[i][j]) { num++; }
|
65,789,610 | 65,789,822 | How to write function signature for accepting std::vector of any type? | The answer here helpfully shows how to print a std::vector to std::out. I've tried making a generic function for printing vectors of any kind:
something like this:
void MyClass::print_vector(const std::vector<auto> vec) {
for (auto i = vec.begin(); i != vec.end(); ++i)
std::cout << *i << ' ';
st... | You can go simple and use auto deduction:
template <typename Container>
void print(const Container& c)
{
for (const auto& e : c) cout << e << ' ';
cout << endl;
}
This will accept any container for any type with defined operator<< for its elements.
One could also use type traits to enable/disable overloads for d... |
65,789,770 | 65,789,840 | Confusing error from structured binding declaration | #include <algorithm>
#include <tuple>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> points = {{3, 12}, {-2, 5}, {-4, 1}};
vector<tuple<int, int, int>> edges;
for (int u = 0; u < points.size(); ++u) {
for (int v = u + 1; v < points.size(); ++v) {
edges.emplace_back(u, v,
... | Your program is well-formed in C++17, but your GCC version is too old to support C++17:s structured bindings.
As specified in C++ Standards Support in GCC, Structured Bindings (P0283R2) was implemented for GCC 7, and is thus not (fully) available in the by now ancient GCC 5.4.
We may verify this by noting that your pro... |
65,789,835 | 65,790,469 | Should the Protobufs from two different repositories be aligned | Problem Description
We have two codes on different repositories. One is in Java and the Other is in C++. We share a common protobuf. The problem is that on our side which is the C++ side we have less members that the one on the JAVA side. As you can see, on our work is assigned id 4, whereas on Java side it is assigned... | Protobuf serialize and deserialize messages based on field numbers not field names.
For example if CPPContext message gets deserialized on the other side as JAVAContext then your work field will be treated as currency field on the other side.
It is better to use same proto files on both communicating sides. Or at least... |
65,789,957 | 65,790,393 | #include errors detected Linux | I work on a crypt and decrypt tool and i got an error about library :
#include <gcrypt.h>
all the other library without errors just this one and when i peek the problem he show me this :
#include errors detected. Please update your includePath. Squiggles are disabled for this translation unit.C/C++(1696)
cannot open s... |
find the gpg-error.h file. Remember the path.
IF(NOT FOUND) {you need to find it on internet. IF(FOUND) { Copy it to the directory of your choice. Remember the directory} ELSE GOTO ERROR}
Add -I{dirrectory where the file is located} to your gcc command line options. ENJOY. EXIT.
ERROR. Email the program author and as... |
65,790,176 | 65,790,464 | Static polymorphism with final or templates? | What are the advantages and disadvantages of using something like
template <typename TData>
class Base {
public:
void foo()
{
static_cast<TData*>(this)->doFoo();
}
};
class Derived : public Base<Derived>
{
void doFoo() { \*...*\ }
};
instead of
class Base {
virtual ~Base = default;
virtual voi... | Static polymorphism (first case) via CRTP is done at compile time and I would basically prefer it, if all classes are known at compile time. Note also that the Base itself is not a class but a class template, so Base is not a base class of Derived.
It's not just performance but also a design decision of your project if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.