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,997,078 | 66,107,854 | DLL LoadLibrary function is returning error code 193 when loading msvcr100.dll | I'm assuming that my application is 32bit and that this is causing the error. In my solution's Configuration Manager the Active solution platform is set to x64. However my Project platform is set to Win32 and I'm unable to change it for some reason. Is this what is causing my problem? If so, how do I enable changing th... | It looks like there was some sort of corruption in my project. I created an empty solution and added an empty project. I noticed that the project allowed me to select x64 as my platform. I went over to my old project with the intent of moving my stuff over when I noticed that I could now select x64 as the platform on t... |
65,998,341 | 66,002,674 | Writing to registry failing, no data added to key, yet functions returning ERROR_SUCCESS | I am writing a method to add data to registry key using RegSetValueEx() after checking the registry the value has not been written to the key. All 3 functions I use to load the hive, key and add value are returning ERROR_SUCCESS which has got me stumped. I have read this and this, however both of these questions sugges... | Thanks for dxiv for pointing me toward the right resources.
Firstly, after reading the Microsoft information, I decided to change all strings to wide strings, as ANSI no longer needs to be supported in new applications, or when NOT taking user input.
std::string executable to LPCWSTR executable,
std::wcout << executabl... |
65,998,443 | 65,998,517 | even though i passed to lambda capture through move semantic, but it still try construct with copy constructor | C++ | std::promise<int> promise{};
std::function<void()> newTask = [promise = std::move(promise), task = std::move(task)]() mutable
{
}
even though i passed valiable through std::move(promise), compiler still try make promise variable with copy constructor.
message : 'ThreadPool::push_task::<lambda_9f392fbd7670777c18dfd2ef... | As you know, std::function is not a lambda, but a generic container for any kind of invocable type, including lambdas.
To make std::function easy to use, it is copyable.
Therefore, all invocable object we put inside a std::function must be copyable, even if we never actually copy the lambda.
The solution in this case w... |
65,998,518 | 65,998,722 | auto type deduction with uniform initialisation syntax c++11 vs c++17 | I was trying to test auto type deduction. Both Scott Meyers (Effective modern C++) and Bjarne Stroustrup's C++ Programming Language mention that doing
auto val {10};
will deduce val to be of type "initialisation list".
I read that this was changed in C++17 so that if there is only one element in the list, then auto wil... | The paper that introduced this change for C++17—https://wg21.link/n3922—has the statement:
Direction from EWG is that we consider this a defect in C++14.
If something is a defect, that means that the paper is retroactively applied, so future compilers compiling for a previous standard will exhibit the new behavior. T... |
65,998,693 | 65,998,809 | Why does my code output me this error of ';' and ','? | So, coding this, I had, and still having, this error
Pin.cpp:14:19: error: expected ',' or ';' before '{' token
std::string ask(a){"
#include <iostream>
std::string a;
std::string question()
{
std::string ans;
std::cout << "What do you want?\n";
std::cout << "a) Play a game "
<< "b) Sing a... | std::string ask(a)
{
Is not valid C++ syntax. The error is telling you that something was expected before the {.
It is not clear to the compiler (or us) whether you were trying to define a variable
std::string ask(a);
or a function
std::string ask(std::string a)
{
or perhaps this function
std::string ask(std::strin... |
65,998,878 | 65,998,927 | How do you create objects that have an instance pointer of itself in a loop? | I have the following class:
class Worker
{
private:
const int m_id;
Worker* m_partner = nullptr;
public:
Worker(const int &id)
:m_id(id){}
Worker(const int &id, Worker partner)
:m_id(id)
{
m_partner = &partner;
}
}
When I create a vector of workers like this:
std::vecto... | The problem is in the constructor:
Worker(const int &id, Worker partner)
You define the argument partner as a local variable, and its life-time will end (and the object be destructed) when the function returns. This means any pointer to this variable will become invalid as soon as the constructor function returns.
You... |
65,999,081 | 65,999,503 | C++ vector not printing correct value after dereference? | Hi my code is very simple and below:
#include <iostream>
#include <tuple>
#include <vector>
using namespace std;
tuple<int, float, string, vector<int>&> foo() {
vector<int> L = {1,2,3};
cout << L[0] << L[1] << L[2] << endl;
return {1, 1.2, "asdf", L};
}
int main()
{
auto [a, b, c, d] = foo();... | That's because L is a local variable and stored in stack memory which is within the scope of foo() function. At the end of foo() function, the scope of the function is cleaned up (ie. stack memory is cleaned up as well).
You should create your vector in heap memory in order to achieve what you want:
tuple<int, float, s... |
65,999,130 | 65,999,633 | static constexpr undefined reference error on clang | The following code compiles fine on Visual Studio 2019 and on gcc 10.2 (and other gcc versions) with -std=c++11 but fails on clang (versions 9, 10 and 11).
#include <map>
#include <string>
struct repo {
static constexpr const char *x = "sth";
};
int main() {
// 1) This compiles
std::map<std::string, int>... | C++17 introduces the rule that static constexpr member variables are implicitly inline (P0386). Inline variables didn't exist before C++17.
This means that in earlier C++ standards, a compiler may need a static constexpr member variable to be defined. If its address is taken, for example.
In C++ standards earlier tha... |
65,999,297 | 66,005,067 | Qt intercepting undo / redo of widgets | I have an application with several QPlainTextEdits, which may also be added or removed dynamically. I am keeping track of a global QUndoStack. Whenever a QPlainTextEdit is focused and the user presses CTRL + Z or CTRL + SHIFT + Z, I intercept this using
void TextEdit::keyPressEvent(QKeyEvent* event) {
if ((QApplica... | Same remarks as before, this is a weird behavior to me. The user can do a lot of things before pressing the undo combination. By then, the undo stack has no info of what the user has done. For the cross platform problem, QKeySequence can be used.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWi... |
66,000,018 | 66,005,481 | ARM Neon - Accumulate dot product to output's index | I want to achieve vector dot product with the following snippet, where the dot product of vector a and b can be added to c at the first position, so the result will be [30, 0, 0, 0].
#include <arm_neon.h>
#include "utils.h"
int main() {
float a[4]{1, 2, 3, 4};
float b[4]{1, 2, 3, 4};
float c[4];
float... | C = vmulq_f32(A, B);
float32x4_t zero = vmovq_n_f32(0);
vst1q_f32(c, zero);
float32x2_t D = vpadd_f32(vget_low_f32(C), vget_high_f32(C));
D = vpadd_f32(D, D);
vst1_lane_f32(c, D, 0);
|
66,000,893 | 66,003,763 | How to properly create cmake library for both program and test usage and compile it only once | I have code with one big directory of models which are going to be used in two binaries - the main program and tests. I want to put the models to the library which will compile once and then both main program and tests can use it without recompiling it again.
Here are my current directories:
root/
CMakeLists.cpp
... | I believe the reason you see the model files compiled twice is due to the recursive glob in src/CMakeLists.txt.
file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp)
This recursive glob will also walk into src/model and grab the *.cpp files there. So the model files are getting compiled as part of modelLibrary a... |
66,001,266 | 66,001,322 | Reading file with fstream then closing and reading again wont work on Android | I'm having a problem that if I write to a file and read from it, then everything is fine. But then if I close it and reopen it, all the data is gone.
It's running on Android and the filePath2 is from getExternalFilesDir so I don't need permission to write to disk. Here's a minimal reproducible example that will run on ... | Get rid of the std::ios_base::trunc flag when re-opening the file:
discard the contents of the stream when opening
After you write to the file, close it, and reopen it, you are wiping out everything you had previously written.
|
66,001,683 | 66,002,554 | I have a small problem in taking values from a file in c++ | I want to take the body of the map of the game the file, but I have a problem that the code is reading the file content as:
22233
31110
00000
00000
00000
and the file content is:
22222
33333
11110
00000
00000
the code is here:
void Map::loadMap(std::string path, int sizeX, int sizeY) {
char tile;
st... | In addition to the problem the commenters are mentioning (calling atoi on a non-null-terminated string), you're advancing the file stream by two bytes in the loop body (once in get and another time in ignore). get already advances the file by a byte; you don't need to do that again. In addition, you're not ignoring new... |
66,002,324 | 66,003,059 | const tuple to tuple of consts? | If I have a tuple member variable where the types in the tuple are a parameter pack of a class template, I can apply a function to each object in the tuple with a static member function like this:
template<size_t I = 0, typename F, typename... Tp>
static void apply_to_foos(std::tuple<Tp...>& t, F func) {
auto& foo... | You can't cast a const std::tuple<T1, T2> to std::tuple<const T1, const T2> without making copies of the contained items.
You have two options for what you can do though:
1. Deduce the type of t and sidestep the problem entirely:
template<size_t I = 0, typename F, typename T>
static void apply_to_foos(T& t, F func) {
... |
66,002,488 | 66,018,786 | C++ Apply a functor that is stored in a vector of shared pointers to Eigen unaryExpr | I have a vector of shared pointers of functor objects: std::vector<std::shared_ptr<MyFunctor>> and I would like to apply one of them to all the elements in an eigen MatrixXd object.
The abstract base class MyFunctor defines a member function operator() that takes and returns a double and is const. Derived classes impl... | Eigen tries to instantiate an instance of the abstract functor you pass into it, hence the compile error. Note that because you dereference the pointer, you are passing in a sliced abstract object into the unaryExpr method. You could just pass in the derived functor directly, or dynamic_cast to the derived type before ... |
66,002,533 | 66,002,599 | For what reason would a function with void return type be constexpr? | To give a specific example, the push_back() member functions of std::vector became constexpr in C++20.
https://en.cppreference.com/w/cpp/container/vector/push_back
| One of the requirements of a constexpr function is that it can only call other constexpr functions.
So, this allows push_back() to be called from some other constexpr function that might, actually, return something useful.
|
66,002,584 | 66,002,610 | iter_swap yields wrong result | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void myfunction(int i)
{
cout<<" "<<i;
};
void multiply(int a)
{
a*2;
}
int main()
{
int t[]={10,5,9,6,2,4,7,8,3,1};
vector<int> v1(t,t+10);
for_each(v1.begin(),v1.end(),multiply);
iter_swap(v1.begin(), t+9);
... | Given iter_swap(v1.begin(), t+9);, you're swapping the 1st element of the std::vector v1 and the 10th element of the array t. v1 and t are two independent objects. And you're printing out the elements of v1 as for_each(v1.begin(),v1.end(),myfunction);, but the 10th element of v1 is not changed.
You might want
iter_swap... |
66,002,587 | 66,005,940 | openmp collapse with inner loop reduction | I'm trying to vectorise a nested loop with #pragma omp simd, but the inner loop has a reduction in it. Is there any way to do this?
#pragma omp simd collapse(2) reduction(+:total[i])
for (int i=0; i<N; i++){
for (int j=0; j<N; j++){
float distance = sqrt(
(x[i][0]-x[j][0]) * (x[i][0]-x[j][0]) +
... | You cannot pass the variable 'i' to +:total[i] either you specify the array subsection to be reduced or just do +:total. Bear in mind, however, that you need a compiler that supports OpenMP 4.5 array reduction feature.
#pragma omp simd collapse(2) reduction(+:total)
for (int i=0; i<N; i++){
for (int j=0; j<N; j... |
66,002,638 | 66,003,022 | Is there a Win32 API to add double quotes in a string? | I'm searching for a possible Win32 API to add double quotes in a string variable, similar to AnsiQuotedStr of Delphi/C++Builder, where these variable strings are paths respectively, like:
C:\Program Files (x86)\file1.exe - strvar1
C:\Program Files (x86)\file2.exe - strvar2
and this will be sent to a VBScript (via She... | AnsiQuotedStr() wraps a string in quotes, and doubles up any quotes already in the string. There is no Win32 API that is exactly like that. The closest would be PathQuoteSpaces(), which wraps a string in quotes if it contains any space characters. Not the same thing.
But, this is easy to implement manually, especially... |
66,002,687 | 66,003,321 | What happens when you set a map index, with a string index inside, to another string index value? | bool isIsomorphic(std::string s, std::string t) {
//create hashmap
std::map<char, char> ms;
std::map<char, char> mt;
for (int i = 0; i < s.size(); i++)
{
ms[s[i]] = t[i];
mt[t[i]] = s[i];
}
for (int i = 0; i < s.size(); i++)
{
if (ms[s[i]] != t[i] || mt[... | Let's first describe how we can check if two strings are isomorphic or not. According to educative.io:
Two strings are isomorphic if one-to-one mapping is possible for every character of the first string to every character of the second string, and vice-versa.
Example-1: "egg" and "add" are isomorphic, where:
Map... |
66,003,529 | 66,003,642 | Why there is always main function in C? | When writing code using C, the code must include the main function. I always had a question about this. In the case of Python or JavaScript, the main function is not required. However, in the case of C, why should I include the main function?
Does this improve performance?
Or is it just to distinguish between the main ... | There's two primary reasons, and they're sort of related.
Firstly, for any given executable it's important to know where to start executing. In a language like Python there's a script that's executed and while it can include other code, it's understood that there's a "main" script.
This isn't the case in a language lik... |
66,003,724 | 66,003,955 | ctor error function already defined and has different type c++ or mql | i define class with ctor and use it in my code but compiler give me error
class MovingAvrage_Expert
{
public:
MovingAvrage_Expert(void);
~MovingAvrage_Expert(void);
bool Init(void);
double TradeSizeOptimized(void);
void CheckForOpen(void);
void CheckForClose(void);
bool SelectPosition();
}
MovingA... | just should write ; after class
class MovingAvrage_Expert
{
public:
MovingAvrage_Expert(void);
~MovingAvrage_Expert(void);
bool Init(void);
double TradeSizeOptimized(void);
void CheckForOpen(void);
void CheckForClose(void);
bool SelectPosition();
};
:)
|
66,003,932 | 66,004,155 | How can one find all the adjacent vertices, given a table of vertices with a specific rectangle format? | If I have a table of vertexes represented by:
a b c d
e f g h
i j k l
m n o p
How can I get the adjacencies of a node as indexes, if the indexes for this table is as follows:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
For example, node "a" should result: 1, 4, 5. node "f" results in 0, 1, 2, 4, 6, 8, 9, 10.
How can this b... | Here, every node is connected to 8-directional way. So we will try to get grid number of 8 adjacent cells.
// starting from upper left corner for a cell
int dr[8] = {-1, -1, -1, 0, 1, 1, 1, 0}; // 8 direction row
int dc[8] = {-1, 0, 1, 1, 1, 0, -1, -1}; // 8 direction column
int n = 20;
int m = 30;
int r = 1, c =... |
66,004,028 | 66,004,134 | Is there a way to tell Visual Studio to treat a warning as a warning, not an error? | In Visual Studio, warning C4996 (using a deprecated function) is treated as an error, and code that uses deprecated functions doesn't compile at all.
There are various ways to disable C4996 entirely, either suppressing it for a single line, for a translation unit, or for an entire project. But what if I want it to stil... | Found a working solution. It turns out the relevant flag is actually "SDL checks", not "Treat Warnings as Errors". Flipping it from /sdl to /sdl- causes compilation to emit a warning while still compiling.
EDIT: If I want to keep all the SDL checks on except treating Warning C4996 as an error, I can use the flag /sdl i... |
66,004,186 | 66,012,519 | How can I use OpenCV without running 'make install'? | I am new to cmake and OpenCV.
Is there a way that I can use OpenCV on my machine by just building the source code and not installing them to /usr/local/lib on my machine, i.e. without running make install after building the binaries?
| The solution would be to set CMAKE_INSTALL_PREFIX to a specific location:
# in opencv/build
cmake .. -DCMAKE_INSTALL_PREFIX=/home/user/path/to/deps/
cmake --build . --target install
Then, configure your project with the same prefix:
# in your project/build
cmake .. -DCMAKE_PREFIX_PATH=/home/user/path/to/deps/
In your... |
66,006,307 | 66,007,003 | I want to ask about the main difference between CreateThread from Windows amd pthread_create from Linux based OS | I would like to implement an application in C/C++ that runs on Windows and Linux-based OS, the application will be multithreaded so after some research I found there are separate library methods for Windows and Linux respectively.
HANDLE CreateThread( // Windows
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T ... | You're very much confusing two things here: user-level threads and kernel-level threads are one thing. What those mean is that with user-level threads the kernel cannot schedule them independently because it does not know about them; and with kernel-level threads the kernel can schedule each thread independently i.e. d... |
66,006,344 | 66,006,498 | prohibit that the returned reference of a function is overridden by a assignment | is there any way, in C++ 17, to prohibit that the returned reference of a function is overridden by a assignment like the following:
class Error{
public:
Error& doSomething(int);
};
Error a;
Error b;
Error.doSomething(0) = b; // how do I prohibit this?
The reason why I want to do this is, so that this:
class ... | You can return Error either by value or by constant reference, both variants prohibits using result as left side of assignment
class Error{
public:
Error doSomething(int);
}
Error myFunction(void) {
if(True){
return a.doSomething(1);
}
}
or
class Error{
public:
Error const & doSometh... |
66,006,688 | 66,006,862 | Activated button in QMessageBox::question | Is there a possibility to set a default activated button to "No" instead of "Yes"
QMessageBox::StandardButton reply=QMessageBox::question(this, "Warning ", "This will deleate your data, Do you want to continue ?",QMessageBox::No|QMessageBox::Yes);
if(reply == QMessageBox::Yes){
// Deleate Memory
}
else{ ... | Last parameter of QMessageBox::question is for default activated button. Default value is QMessageBox::NoButton which means there is no default button. replace it with QMessageBox::No which means button with "No" label on it. A little bit confusing.
QMessageBox::question(this, "Warning ", "This will deleate your data, ... |
66,008,089 | 66,011,167 | How to get your public ip address using Qt c++ | I'm writing a gui for an net address etc. calculator. All the coding is done but now i want to have a button that will get your computer's ip address. I was looking for a solution and saw various posts on stackoverflow but none of them work for me...
Edit: this piece of code worked for me
QTcpSocket socket;
socket.... | I think the class you are looking for is the QNetworkInterface class.
From the man page:
The QNetworkInterface class provides a listing of the host's IP
addresses and network interfaces.
For example, calling QNetworkInterface::allAddresses() is a quick way to get a list of all the IP addresses on your machine. As fo... |
66,008,388 | 66,011,910 | Transitivity guarantee for transparent comparisons in associative containers | Assume we have an ordered container with custom Key and transitive comparator Less, and we do lookup in it, like this:
struct Key {
int a, b;
auto operator <=> (const Key&) const noexcept = default;
};
struct Less {
bool operator ()(const Key& lhs, const Key& rhs) const noexcept {
return lhs < rhs;... | s.equal_range(ke) is defined as equivalent to std::make_pair( s.lower_bound(ke), s.upper_bound(ke));
and std::set should be partitioned according to comp(x, ke) and !comp(ke, x) (and c(x, ke) implying !c(ke, x)).
See container.requirements#associative.reqmts.general-8 for formal requirements.
So in your case your ar... |
66,008,393 | 66,008,512 | How do you use multidimensional arrays as methods parameter in c++? | I come from java where i would put multidimensional array as methods parameter like so:
void someMethod(int MultiDimensionalArray[][][]){}
how would i do this in c++?
| Function argument cannot be an array in C++. You can write a function declaration with an array parameter, but it is actually adjusted to be a pointer to element of such array. For example, these declare the same function, which accepts pointer to an integer:
void foo(int arr[]);
void foo(int* arr);
The element of a m... |
66,008,670 | 66,008,883 | Pass reference instance to static method when copy-constructor and assignment-operator is disabled | My ClassA looks like this:
class ClassA
{
private:
static uint32_t IDCOUNTER;
uint32_t _id = -1;
public:
ClassA();
~ClassA();
ClassA(const ClassA&) = delete;
void operator=(const ClassA&) = delete;
};
I want to create one specific instance of ClassA and I want it to be passed around but I don'... |
When compiling, I get a linker error. Why is that?
Because you didn't define ClassStatic::referenceToA.
How would I fix this?
Define ClassStatic::referenceToA in (exactly one) translation unit.
|
66,009,034 | 66,090,938 | Is a pointer to function (sometimes/always?) a function declarator? | (This question has been broken out from the discussion to this answer, which highlights CWG 1892)
Some paragraphs of the standard applies specific rules to function declarators; e.g. [dcl.spec.auto]/3 regarding placeholder types [emphasis mine]:
The placeholder type can appear with a function declarator in the decl-s... | The confusion here arises from two different meanings of "declarator": one is the portion of a declaration (after the specifiers) that pertains to one entity (or typedef-name), while the other is any of the several syntactic constructs used to form the former kind. The latter meaning gives rise to the grammar producti... |
66,010,355 | 66,010,488 | macro that applies only once | Is it possible to write a macro, that applies exactly once no matter how many times it is nested?
// how to implement this properly?
#define FOO(x) hello(x) // incorrect, works only for 1 level of nesting
// desired use below
void hello(int x);
FOO(x); // expanded to "hello(x)"
FOO(FOO(x)); // also expanded to "hello(... | You could overload a function on type of argument. With a special type, you could just forward it, only calling the function when actual arguments are provided.
void hello(int x);
struct FOO_hello_called {};
FOO_hello_called FOO(int x) {
hello(x);
return {};
}
FOO_hello_called FOO(FOO_hello_called s) {
return... |
66,010,425 | 66,010,713 | C++ Vector of abstract class of specific base class, as another class member | I have:
A base abstract class Shape.
Then, several child classes, one of them, Rectangle.
A template class called GeneralObject<T>, having a private member T shape (T has a static assert check for being child of Shape), in order for a GeneralObject to be created: GeneralObject<Rectangle>
An ObjectManager which I want ... | Change the member of GeneralObject to be a pointer to T rather than T:
template<typename T>
class GeneralObject {
public:
GeneraObject(std::shared_ptr<T> object) : object(object) {}
private:
std::shared_ptr<T> object;
};
You can use this as
auto gObj = GeneralObject<Shape>(std::make_shared<Rectangle>());
Your co... |
66,010,763 | 66,010,819 | c++ opencv Mat Value | cv::Mat K(3, 3, cv::DataType<double>::type);
K.at<double>(0, 0) = 407.87327205;
K.at<double>(0, 1) = 0.0;
K.at<double>(0, 2) = 297.88672999;
K.at<double>(1, 0) = 0.0;
K.at<double>(1, 1) = 408.85701444;
K.at<double>(1, 2) = 217.4312281;
K.at<double>(2, 0) = 0.0;
K.at<double>(2, 1) = 0.0;
K.at<double>(2, 2) = 1.0;
C+... | Yes, use comma initialization:
cv::Mat K = (cv::Mat_<double>(3, 3) <<
407.87327205, 0.0 , 297.88672999,
0.0 , 408.85701444, 217.4312281 ,
0.0 , 0.0 , 1.0
);
This (ab)uses the little-used comma operator in the C++ language. The outer parentheses are necessary for it to work!
|
66,010,917 | 66,011,044 | How to create a method that compares an unknown number of strings in C++? | After some research I found that in C++ I can create a function with infinite variables in this way:
template<typename ... Args>
void func(Args... a) {
/* CODE */
}
I want to make a method that compares an unknown number of strings and gives a bool: true if are equal and false if are not equal.
I did something lik... | The term infinite variables is not correct. C++ can handle variable numbers of function arguments but not infinitely many ones.
If you can use C++17 a fold expression would be the easiest solution:
template<typename ... Ts>
bool cmp(const std::string& first, const std::string& second, const Ts&... rest) {
return (c... |
66,011,317 | 66,011,891 | Do we need locking if we are appending and reading data from vector simultaneously?(no-modification) | We know that if more than one thread operates on an object and there is a modification involved, we need some kind of locking(atomic/mutex). For my case only these operations are happening simultaneously for a std::vector:
1. Read
2. Append/Push
Will the vector need a lock in this case? and if yes, why? My program is ... | Yes you need locking, in general, because push_back can cause reallocation.
You can check the reference:
https://en.cppreference.com/w/cpp/container/vector/push_back says
If the new size() is greater than capacity() then all iterators and
references (including the past-the-end iterator) are invalidated.
Otherwise only... |
66,011,665 | 66,017,467 | Make a c++ program accepts command after started | I'm new to C++ and I'm trying to create a program that accepts command through command line.
So My program starts like ./program -f filename -m tablesize. I found that these arguments could be processed by passing arguments to the main() function, namely, by doing main(int argc, char** argv).
However, after the progra... | It's going to depend upon what your teacher means by "no STL". But let's take your teacher at face value. You have different ways of getting input.
You can use old-school the old-school C library. See this:
How to read a line from stdin, blocking until the newline is found?
You can also use C++ streams:
#include <iostr... |
66,011,716 | 66,011,843 | C++: How do I compose multiple concepts? | This title seems to receive a lot of criticism. However, I have found this notion to be difficult to search for. It is also relatively new in C++ land, where schools are still teaching C++11.
Motivation and Context to Avoid the XY-Problem
Right now, I am instrumenting out an embedded device project with concepts as p... | You can constrain foobar with a requires clause, or name the conjunction of concepts you desire.
template<typename PortInfo>
requires ExtensibleInstanceContext<PortInfo> && ExtensibleDeviceContext<PortInfo>
void foobar(
PortInfo port,
const char *portName,
bool optional,
const char *devName, ... |
66,011,800 | 66,013,257 | Marshalling safearray of safearray from VARIANT in C++ to C# | I'm trying to call a function in .NET from a native library, like this:
typedef int (WINAPI* TGetAllObjects)(int hModel, VARIANT& objects);
If you call it in the C++ client, the debugger shows that objects are a safearray of VARIANT, and each VARIANT is a safearray of BSTR.
I tried to implement as follows in C#:
publi... | Try :
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate int TGetAllObjects(int hModel, ref object objects);
and see EXACTLY what you receive. The objects variable is a VARIANT, not a SAFEARRAY. The VARIANT& objects contains the SAFEARRAY, it isn't a SAFEARRAY.
Then inside your code you can check its type... |
66,011,931 | 66,012,809 | C++: Why is my if-else statement not working? | so I have an assignment and I'm a newbie to programming.
My prof wants to have an output, that when I enter a number, the program will get the square root of that number, then if the answer is in whole number, it will + 1, and if its in a decimal number, it will -1. But the problem is, the if in whole number is working... | The way you are trying to check decimal number is incorrect. You might try something like this-
if(num - (floor(result) * floor(result)) !=0 ){
// result is a decimal number
}
But, sometime this approach will give the wrong answer. Because here we are working with
floating numbers and precision error is always a ... |
66,012,081 | 66,012,346 | Are functions with variadic arguments required to call va_start? | Is it safe to exit a function with variadic parameters early, before it begins using va_list?
#include <cstdarg>
int func(const char * format, ...){
if(format == NULL)
return 0; // <-- exits before acknowledging variadic parameters; is this okay?
va_list params;
va_start(params, format);
// fu... | Yes, this is legal. No, functions are not required to call va_start. From the C99 standard:
If access to the varying arguments is desired, the called function
shall declare an object ... having type va_list.
Notice two things here:
A va_list is a prerequisite to the va_start call.
A va_list is only necessary to have... |
66,012,203 | 66,012,397 | C++ vector of class objects and dynamic memory allocation - part 2 | This is a follow up on my previous question posted here (C++ vector of class objects and dynamic memory allocation).
Someclass is an oversimplified class for the sake of this example. Important to know that objects of this class are stored in a vector somewhere else.
Buffer is another class that has three types of memb... | This is because of a simple reason. When you erase an entry, the array needs to remove that "bubble" (which is the empty slot) and compact the array. Which means that it needs to move some stuff. So when moving, what they do is something like this,
// Form the MSVC xutility.h file.
for (; _First != _Last; ++_Dest, (voi... |
66,013,227 | 66,013,301 | different conditions in for loop in C++ | int main(){
int a=0;
for(;a<10 && a>4;a++){
cout << a <<endl;
}
}
In this situation, for loop prints nothing. What I actually expect is printing numbers from 5 to 9. Is it necessary to make the condition true to enter the loop? Or is the a++ statement work just if the conditions are true?... | that will never print anything because the condition to execute the loop is never met
a<10 && a>4
"do something while a is bigger than 4 and less than 10, and we begin with a = 0...."
so the loop never begins....
|
66,013,343 | 66,013,479 | How to enumerate default values of a structure in C++ | Problem:
I have a structure that represent RGB colors. I would like to define an enum to be able to directly assign the colors to a variable.
1) Desired enum of struct:
What I would like is to define an enum that directly maps a color name to its value, just like I would do with an integer parameter or a list of items.... | I would use inline constexpr variables and wrap them in a namespace. That would look like
namespace Default_colors
{
inline constexpr Color_3u8 RED{255,0,0};
inline constexpr Color_3u8 GREEN{0,255,0};
inline constexpr Color_3u8 BLUE{0,0,255};
}
and then you would use it like
Default_colors::RED
The reaso... |
66,013,536 | 66,013,792 | When does a unique_ptr returned by a function (via std::move) go out of scope | I am working with a large object that is stored in a shared memory region, and is returned by a getter. I was running into issues where returning the object by-value was blowing the stack due to the size of the object. To avoid this, I decided to return a unique_ptr to a copy of the object on the heap, which I want the... | The get() member function returns the pointer to the AbsoluteUnit object managed by the std::unique_ptr<AbsoluteUnit> that getAbsoluteUnit() returns.
That managed AbsoluteUnit object is then bound to the reference absUnit:
AbsoluteUnit& absUnit = *getAbsoluteUnit().get();
However, the std::unique_ptr ceases to exist j... |
66,014,169 | 66,014,819 | C++ Eigen Vector infer vector size at compile time for class | I'm trying to make a wrapper class for Eigen::Matrix. It should take in a pointer to a static size eigen vector (matrix with 1 row), and should return a copy when the getValue() function is called. This is what I currently have
template<std::size_t N>
class InputV
{
public:
InputV(const Eigen::Matrix<double, N, 1>... | If you're using C++17, you can use class template argument deduction (and deduction guides, but you don't need them in this case):
Eigen::Matrix<double, 10, 1> a;
auto x = InputV(&a);
InputV y(&a);
If you're using an older C++ version (i.e. C++11 or C++14), you can use a helper function. This works because functions ... |
66,014,453 | 66,014,599 | How does one manage a self-referring cross-scope lambda? | Assume that I have a functionality which I want to call whenever a timer finishes. I have put that piece of functionality in a lambda function. Furthermore, in that function, I may wish to set another timer to call that same lambda on another, later occasion.
void doSetupThingsInSomeDecoupledCodeOrWhatever() {
std:... | What you're looking for is a y-combinator, sometimes called a fixed-point combinator.
Either way, instead of using std::function at all (which adds needless overhead), you would write your callback like this:
auto semiRecursiveCallback = combinator([](auto self, float deltaT){
if (whatever()) {
// Do someth... |
66,014,487 | 66,014,668 | Complex function integration using trapezoidal rule in C++ | #include <complex>
complex<double> integral(complex<double> (*f)(complex<double> x), complex<double> l, complex<double> u, size_t n) {
complex<double> step = (u - l) / (double)n;
complex<double> area(0, 0);
for (size_t i = 0; i < n; i++) {
complex<double> inner = l + (i + 0.5) * step;
area = area... | integral's first parameter type
complex<double> (*f)(complex<double> x)
is wrong.
The complex form of std::cos takes its parameter by constant reference.
Change your first parameter to this and std::cos will be a match.
complex<double> (*f)(complex<double> const & x)
// ^^^^^^^
|
66,014,651 | 66,023,783 | How to read a file on Hololens with C++ | I am trying to read a file in a test/debug UWP application that is being deployed to Hololens. I can put the file on the device with the device portal, but am unable to find the correct path to open the file.
I am using the MSFT BasicXrApp_uwp example as a basis, and have included FileUtility which has a FindFileInAppF... | This is because the folder path which FindFileInAppFolder method returns is the InstalledLocation of the current package, but what you checked in the device portal is LocalFolder/LocalCacheFolder, for more information about what different between them please see: File access permissions.
how do I embed my file in the ... |
66,014,718 | 66,026,352 | Why does Visual Studio mark my CPP and Header files as Miscellaneous Files, leading them to not be affected by intelli sense | The problem
You probably already read the long title: My VS 2019 keeps flagging my header and CPP files as "Miscellaneous Files", leading them to be not affected by intelli sense. I have this problem for quite a while now, so I'd really appreciate help. I should maybe add that I am using CMake, which could, indeed, be ... | C++ traditional (non-modules) compiler compiles .cpp files into .o files, then the linker takes .o files and links them into a binary. The exact extension of these files is not fixed (you can convince a compiler to consume .foo source files and produce .bob object files).
You may note that .h files are not mentioned h... |
66,014,804 | 66,015,474 | Merge Sort algorithm Doesn't work(c++), facing problem getting no sense out of output | I was solving a problem and i was using the same recursive method as used in merge sort. But it didn't give the desired output so i decided to implement basic merge sort first, and i think i am missing something in my recursive algo
This is my merge sort, though i doubt there's anything wrong here but still if you need... | Well you have some bug in your code.
you should take element starting from lower index in merge function, in left halve:
L[x] = arr[l+x];
you need to it same for right halve too:
R[x] = arr[m+x +1];
you should complete scanning in case of different length of array, when they are comparing in merge function:
while(i ... |
66,014,879 | 66,014,999 | Error sum of two matrix in function By using 2d array | #include <iostream>
using namespace std;
int add(int x[3][3], int y[3][3],int z[3][3]);
int main()
{
int x[3][3],y[3][3],z[3][3];
cout<<"Enter value for x "<<endl;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cout<<"Enter the value of index "<<i<<","<<j<<" :";
... | The function add returns nothing though its return type is int.
So this statement
cout<<add(x[3][3],y[3][3]);
does not make a sense and moreover the function call has invalid arguments (the number of arguments and their types).
Maybe you mean
void add( const int x[3][3], const int y[3][3], int z[3][3]);
and
add( x, y... |
66,015,171 | 66,015,226 | Base Operand of -> has non-pointer type error when creating an array of classes | I would like to learn why the base operand -> works in some cases and not in others when used with a pointer.
I realize I need to use a . instead of a -> when I receive this error. I'm trying to understand why a . is needed when I reference my pointer as an array element as p[i].somefunct(), and -> is required when I r... | The difference is very simple. p[i] is exactly the same as *(p + i). Absolutely the same, to the point of i[p] being a valid (albeit super confusing) form of writing array subscription.
Because of that, when you use p[i] form, you already dereference the result, so you access members via . member access.
If you are usi... |
66,015,562 | 66,016,333 | I was solving a problem on leetcode. I did the code but I am receiving some runtime error saying reference binding to misaligned address | Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your... | You haven't asked any question, but I'll assume it's
"Why does this code trigger a runtime error?"
This code
while(s.top().first < T[i]) {
s.pop();
}
makes no effort to check whether s is empty.
When s.empty() is true, s.pop() will trigger Undefined Behavior.
Separately,
res[i] = s.top().second - i;
also doesn'... |
66,016,386 | 66,017,433 | explicit conversion operator and const-reference qualification | The following example compiles fine on godbolt with -std=c++17 with clang, but fails with msvc and gcc:
struct Foo
{
};
struct Bar
{
explicit operator Foo() // w/o explicit qualification all are happy
{
return Foo();
}
};
int main()
{
Bar b;
const Foo& foo = static_cast<const Foo&>(b); // ... | OP's example is not really minimal. A truly minimal example uses, instead of a static_cast and then an initialization, simply:
const Foo& foo(b);
This is what static_cast<const Foo&>(b) is supposed to do, anyway.
Here again, Clang accepts and GCC rejects [godbolt]. If this is changed to a copy-initialization (const Fo... |
66,016,638 | 66,029,768 | Integration of complex numbers using trapezoidal rule in C++ | #include <complex>
#include <iostream>
using namespace std;
complex<double> integral(complex<double> (*f)(complex<double> const &x), complex<double> l, complex<double> u, size_t n)
{
complex<double> step = (u - l) / (double) n;
complex<double> area(0, 0);
for (size_t i = 0; i < n; i++) {
complex<d... | As was commented, dividing by inner was an extraneous step.
complex<double> integral(complex<double> (*f)(complex<double> const &x), complex<double> l, complex<double> u, size_t n)
{
complex<double> step = (u - l) / (double) n;
complex<double> area(0, 0);
for (size_t i = 0; i < n; i++) {
complex<do... |
66,017,093 | 66,017,300 | String is not being directed to Output file (C++) | So I'm trying to direct the String that I get from a function to an output file. What's happening is that the buildTree function is creating a binary tree of vector strings and then after it has finished, it calls the printInorder function to print the function in order. It will correctly print out the tree if I replac... | Rather than a method that opens and closes the file, how about writing:
std::ostream &operator<<(std::ostream &str, const BST &) {
...
}
Then you have a generic print method that you can send to any output stream.
|
66,017,122 | 66,017,803 | How to properly create a derived class from this v8 class | So I have a class that is in v8 that I want my own class to derive from and then instantiate an instance of my own class.
In v8 there is the class with this signature:
class V8_EXPORT CodeEventHandler {
public:
/**
* Creates a new listener for the |isolate|. The isolate must be initialized.
* The listener obje... | (This is not a V8-specific question; it's plain C++.)
As @JosephLarson points out, you need a constructor with the right signature. Add this to your class:
explicit CodeEventHandler(Isolate* isolate)
: v8::CodeEventHandler(isolate) {
// any code you need to initialize your subclass instances...
}
|
66,017,185 | 66,017,809 | What is the position of an unmatched group in C++? | Let m be of type std::smatch . Suppose there is an unmatched group i. What is
m.position(i) ? For that matter, what is m[i]?
For example, consider
std::regex re {"^(a+)|(b+)"};
string target="aa";
std::smatch m;
std::regex_search(target,m,re);
cout<<"m[2] is: "<<m[2]<<" at position: "<<m.position(2);
I cannot figure o... | According to the C++17 Standard:
28.10 Class template match_results [ re.results ]
4 The sub_match object stored at index 0 represents sub-expression 0, i.e., the whole match. In this case the sub_match member matched is always true. The sub_match object stored at index n denotes what matched the marked sub-expression... |
66,017,515 | 66,018,442 | Call Timer methods / modify properties from other threads in C++ Builder | I'm trying to achieve the following: to call methods or to modify properties of a TTimer timer which was created in the main thread, from another threads.
Code looks like the following:
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm... |
Is it possible to call it like that, directly
It is not safe to do so. Always Synchronize when changing the state of VCL components being used in the main VCL thread from from a thread that is not the main VCL thread.
You can use the static TThread::Synchronize function from <System.Classes.hpp> with a lambda functio... |
66,017,788 | 66,038,641 | loop over map of vectors and get max across columns in c++ | I have a map defined as follows:
const map<int, vector<float> >& m = …;
I want to loop over the columns (size of the map.second: vector) and in every iteration I get the:
1- The max value of the column across the map.first: int
2- The value of the map.first: int at the which the max occurs
For example:
#0 I get 31, 1... | You need a function that accepts a column number and loops through each row calculating the maximum for that column.
You only need one loop because you can access whichever column you want by indexing the vector like an array (as long as you check that the vector has enough elements)
There are two ways to do this: the ... |
66,019,346 | 66,019,419 | Using enable_if on a defaulted template argument for a constexpr lambda | I'm trying to write a generic function that will always return a -1. I want the template argument list to default to int. I'm trying to use std::enable_if or std::enable_if_t to test if the type T is a valid arithmetic type by using std::is_arithmetic or std::is_arithmetic_v. I'm having syntax issues to be able to get ... | Use non-type optional template argument for sfinae. Your type needs to be a lambda type (not T) if you want to call it/pass it as a predicate. You can achieve this with automatic type deduction.
template<typename T = int, std::enable_if_t<std::is_arithmetic_v<T>, int> = 0>
static constexpr auto negative_one = [](){
... |
66,019,367 | 66,019,625 | Why is a binary operator selected over a unary operator? | For operators that act as both unary and binary, why is the binary one selected in an expression like a@b?
After a lot of thought and searching, I still haven't been able to answer why something like a+b is parsed as a binary expression instead of a(+b), which would obviously be gibberish.
I don't think a context free ... | Context-free doesn't mean "no state". A parser has a lot of state to keep track of what grammatical rules are possible given the tokens it's seen so far and to predict what tokens will come next. Because there's no rule that says that two expressions can appear directly adjacent to each other it'll never even consider ... |
66,019,780 | 66,019,929 | delete and insert in random position in std::list | I am trying to delete random position from stl::list. since List does not have random access iterator I was wondering how I could do this.
#include <iostream>
#include<vector>
#include <random>
#include <list>
#include <iterator>
int main()
{
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distr... | You can use std::advance or std::next to advance an iterator an arbitrary number of positions. For an iterator over a linked list, this will take time linear on the number of positions being advanced (so chances are pretty good that for a task like this, you shouldn't be using a linked list, but such is life).
using ... |
66,020,118 | 66,020,271 | C++ moving characters from one vector to another | I'm new to C++. I am trying to create a program that reads a file named symbols.txt, fill a vector with the symbols, then take chars that are in the range [d;p] and move them to the second vector while erasing them from the first vector.
int main(){
vector<char> sym1;
vector<char> sym2;
int p = 100, d = 80;... | In your implementation, the first thing you need to notice is that in your for loop, sym1.size() changes if you call sym1.erase(). Second, since your variable i increments every time, you skip some elements in the vector.
For example, the element at index 5 is erased, then the element at index 6 will move down to repla... |
66,020,172 | 66,023,641 | Why won't my servo motors stop spinning when trying to go forward? | I need to make this object following robot which uses 2 servo motors to move and a ultrasonic sensor to detect where objects are and where the Arduino should tell the servos to move. But, the problem seems to be that whenever the servo motors are trying to move forwards or backwards they just keep spinning. I've tried ... | As paddy already pointed out your movements take very long.
The nested for loops will call delay(15) 181*181 times. That's 32716 times 15 milliseconds. A total of 8.2 minutes.
Another problem with your code is that you expect the servo to return from 180° to 0° within 15ms which is not going to happen.
Also don't need ... |
66,020,260 | 66,020,376 | Is it possible to declare two variables For-Each Loop in C++? | I am trying to write a function which can check, If a two string has all characters with the same frequency. So in order to do that, I tried to make two Maps i.e unordered_map<char, int>. So in my next step, I just want to compare each value of each char on my map.
string A;
string B;
unordered_map<char, int> a;
unord... | Simple answer is no, you can not do that. This for loop is called for each loop, and structure goes like this:
for each ELEMENT in MAP/ARRAY/VECTOR
do something
If I am correct your intention is to have something like this
in loop
store each element of MAP_A into i and each element of MAP_B in j
It is not poss... |
66,020,609 | 66,020,835 | How pushing back R-value temporary objects to a vector works? | In this piece of code, I can't understand the meaning of Move {10} and move {20} syntax.
Is that the constructor pushed back? or a specific syntax for temporary objects?
I've searched a lot before posting this question. Can someone explain to me please?
P.S: The instructor provided this example in a video tutorial said... |
In this piece of code, I can't understand the meaning of Move {10} and move {20} syntax.
In C++ there are several ways you can create temporary (unnamed) objects. For example you can have a function that returns object of your class by value:
Move foobar();
Now when you call that function in your code result of that... |
66,020,741 | 66,308,073 | OR tools C++: solver.MutableObjective() returns null | I just inherited a piece of code, which solves a mixed integer programming problem using OR Tools. Integrating OR Tools into VS 2019 was a headache of its own (well, I'm not that used to C++). Now the program is running, but I am getting:
Access violation reading location 0x0000000000000020
According to the debugger,... | What I ended up doing is more of a workaround.
The ORTools library download comes with example programs and a Makefile. So, I replaced the contents of one of the sample files with the code I need, and used the supplied Makefile to compile/run the program.
This way, the exact same code I had is not showing errors anymor... |
66,020,796 | 66,020,855 | How can I make my program accept pointers? | I am trying to make my program accept pointers as part of a requirement to deallocate the heap space and kill the pointer. My program runs fine without the adjustments I attempted to make to accept pointers. I'm getting the following error
lab.cpp: In function 'int main()':
lab.cpp:21:19: error: request for member 'uni... | When accessing an pointer's members, you need to use the arrow (->) operator. But your methods input and output takes the cargo pointer. After accessing its member, you'll return the member, not the pointer. So by doing shipment.unit, your returning a string.
To fix it, lest just pass in the pointer.
void input(cargo *... |
66,021,074 | 66,021,290 | When is nested initializer_list ambiguous, and why do templates affect its behavior? | I encountered an interesting behavior where templates seem to affect whether a nested std::initializer_list is ambiguous or not. Consider the following example:
#include <initializer_list>
#include <iostream>
template <typename T = int>
void constructor_T(std::initializer_list<T> l) {
std::cout << "constructor_T 1... | constructor_int({}); // ambiguous, why?
You can construct both an initializer_list<int> and initializer_list<initializer_list<int>> with {}.
constructor_int({{}, {}}); // ambiguous, why?
You can construct both an initializer_list<int> and initializer_list<initializer_list<int>> with {{},{}}.
T... |
66,021,096 | 66,021,791 | Path tracing: how to ensure the new direction vector is a valid direction vector with respect to a BSDF? | Given the BSDF function and the Normal vector of the intersection point in world space, how can I generate a new direction vector wi that is valid? Does the method for generating valid wis change based on the BSDF?
Here's an example of what I'm thinking to do for ideal diffuse material the BSDF: I generate a new direct... | You are generating your wi in tangent space, with z pointing along the normal. It is neither world nor object space, and you will have to transform into world space or do all your calculations in tangent space (or shading space, they're both the same).
What you should be doing, as it will make your life much easier whe... |
66,021,217 | 66,021,257 | Traits of overloaded functions | I am trying to get the return type of a function with const/non const overloads.
struct TestClass {
const int* getPtr() const { return ptr; }
int* getPtr() { return ptr; }
private:
int* ptr;
};
using return_ptr_type = typename std::invoke_result<decltype(&TestClass::getPtr), TestClass>::type;
static_assert... | In decltype(&TestClass::getPtr) overload resolution won't happen; there're even no context for compilers to choose one.
You can get the return type by calling getPtr() on const or non-const object, to make overload resolution taking effect. e.g.
using return_ptr_type1 = decltype(std::declval<TestClass>().getPtr());
sta... |
66,021,672 | 66,021,869 | Need help using strncpy() in C++ | I am stuck for hours during my assignment. Specifically, on this part:
The constructor should take a const-qualified C-Style string as its argument. Use the strncpy() function from the <cstring> library to copy it into the underlying storage. Be sure to manually null-terminate the attribute after you copy to assure th... | First of all, your call to strncpy is wrong. Please check the reference regarding the strncpy from here.
According to the definition of strncpy :
char *strncpy(char *dest, const char *src, std::size_t count);
In your case, you are calling strncpy like this:
strncpy(StringWrapper::myString, myString, sizeof(myString));... |
66,021,838 | 66,026,245 | How to create .sln file using command line | I have a few .vcxproj files. One is Main.vcxproj which depends on other .vcxproj files. All are c++ projects.
What I want is to create a .sln file with those project files. Is there a way to achieve this using command line?
I am trying to create a batch file which will build the generated .sln file. I am able to build ... | As @paddy points out in the comments, this is a viable option.
https://github.com/microsoft/SlnGen
It's a command line tool.
Install via:
dotnet tool install --global Microsoft.VisualStudio.SlnGen.Tool
Navigate the root under which all projects you want to add to your solution, then run:
slngen
It'll search for *.*... |
66,022,458 | 66,030,321 | creating slider bar using pangolin | Is there any way to create slider using pangolin? small example of creating slider with min and max value, when user clicks on ok button then call a function.
| With some back Rand D i figured out a way to create a slider sort of thing: posting my answer incase if it can be of any ones help:
pangolin::Var<float> menubf("menu.bf:", 10, 100, 150 );
pangolin::Var<float> menuthDepth("menu.thDepth", 0, 0, 100 );
pangolin::Var<float> menudepthMapFactor("menu.depth Map Factor", 0, 0,... |
66,022,519 | 66,026,413 | Is it possible to pass data between MicroPython and C++ in ESP32? | We are working on a prototype using the ESP32-DevKitC-VE and e-paper.
The e-paper manufacturer provided C++ sample programs for Arduino and we were able to get the ESP32-DevKitC-VE and e-paper to work as expected.
We want to generate the data to be displayed on the e-paper in MicroPython.
Is it possible to somehow pass... | Just to be clear: C++ programs don't "exist" on the ESP32. Only the compiled code is running on the microcontroller. MicroPython, however, is an interpreted language and does "exist" in source on the controller.
To answer your question: Yes, it is possible to call specialized libraries (C++ source code) from MicroPytho... |
66,022,754 | 66,022,902 | cpp 17 , cannot instantiate abstract class , way Interface must be pointer? | i try to create an interface in c++ that enables me to use it as i want different types to implement it.
getting :
cannot instantiate abstract class
for example :
BB.h
class BB {
public:
BB() {}
};
ICC.h
class BB;
class ICC {
public:
virtual BB launch(std::map<std::string, std::string>& ops) = 0;
};... | The problem is in AA.h. You can not instantiate cc.Also getC1() is maybe not implemented as intended, it is causing slicing problems.
You can create instantiate only a pointer of ICC as it is pure virtual.
If you further work with Base-pointer objects you may also consider to make the destructor virtual. (Delete on Bas... |
66,022,795 | 66,022,938 | Checking and replacing a duplicate in a single for loop | So I have set up my code to be this (note I have my user input for the array and display of the results in another function and a beginner)
int main( )
{
using namespace std;
int a[8];
populateArray(a, 8);
cout<<"The array is: ";
displayArray(a, 8);
cout<<"\nThis array becomes: "<<sameElement... | I suppose you want to replace duplicate entries of an array in sameElement function. You're getting single integer because sameElement function returns single integer.
Instead of returning value in for loop, let the function run through. Also note that a[i+1] will go over limit of array a, so you have to change ending ... |
66,022,875 | 66,023,054 | I would like the int sum to count for me the number of time the function is being recursively called. Where should I place the sum and the output | I am trying to have some tools to count for me how many times this recursive function was called. So, I initiated the int sum and place above the line where the function is called recursively. I also printed a cout command to see if this is working. But it looks like my sum++ does not work properly.
| What you have done is you are always assigning 0 to sum that's why the output is always same. You can make sum as a global variable. Refer to the code below:
int sum=0;
int fact(int n)
{
if(n==1)
{
return 1;
}
else
{
sum++;
cout<<"Function is called "<<sum<<" times"<<endl;... |
66,023,831 | 66,372,206 | Xerces: How to create DOM document | I want to create a DOMDocument with xerces, but I get an error of null pointer
at this point:
DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(tempStr, 0);
The error is:
xercesc_3_2::domImplementation was nullptr
My code is this:
//
// Create a small document tree
//
{
XM... | xercesc_3_2::XMLPlatformUtils::Initialize();
xercesc_3_2::DOMDocument* domDocument = NULL;
xercesc_3_2::DOMDocumentType* doc_domDocument = NULL;
xercesc_3_2::DOMElement* root;
xercesc_3_2::DOMElement* child1;
xercesc_3_2::DOMElement* child2;
xercesc_3_2::DOMImplementation* domImplementation = N... |
66,024,052 | 66,024,868 | Self registering concrete implementations of a derived class to a std::map | I would like to generate an abstract class that contains information about parameters. Each concrete implementation for a specific parameter should then override a getName() and getDescription() method.
struct ParameterInterface {
virtual std::string getName() const = 0;
virtual std::string getDescription() const =... | First of all, yes, if you want to store objects of different derived types into a map, you'll have to use some sort of pointer. An std::unique_ptr would do fine here.
Now, I would suggest an std::unique_ptr, since they automatically take care of destructing the objects when required. However, that means you can't do re... |
66,024,928 | 66,027,704 | How to check conditions on a string literal at compile time passed inside a class? | I want to be able to pass a string literal to a class instance and also check at compile time for certain conditions on the string literal. But I want the string checking to be done by the class somehow. I have a sample code with roughly what I'm trying to achieve:
#include <type_traits>
#include <string>
#include <str... | The following works but I am unsure if it is what you want:
#include <type_traits>
#include <string_view>
template<const char *const t_name>
class TestString {
public:
static constexpr bool TestStringCondition(const char *name) noexcept {
return std::string_view(name).find('a') != std::string_view::npos;... |
66,025,120 | 66,025,295 | How does the nested class with override work? | I was wondering how can one explain this mechanism:
class Base{
class Other;
virtual void test() = 0;
};
class Other: Base{
virtual void test() override;
};
void Other::test(){ /*do something*/}
It looks like I have a base class called Base. It contains of a nested class which inherits from the Base. So if I cal... | The declaration of class Base::Other at line 2 in your first code example, has nothing to do with the declaration of class Other in line 5 of your first code example.
That is, the forward declaration of Base::Other does not match class Other.
There is benefit in having nested classes (for example, some implementations ... |
66,025,635 | 66,039,089 | C++ code run in debug console rather in terminal in vs-code | I wanted to execute code in terminal not in debugger
After downloading all the c/c++ extension in vs-code.
code
#include<iostream>
using namespace std;
int main()
{ int UserInputOccur;
cout<<"helloworld";
cin>>UserInputOccur;
cout<<UserInputOccur;
return 0;
}
All the compilation and debugging done i... | If you are using Linux you can write your code in a file, such as main.cpp.
Then you can open terminal -> go to the directory of the file -> run command g++ main.cpp -o main.
Now you can run your code on terminal with command ./main
|
66,025,998 | 66,026,748 | How to specify multiple configurations in a CMake CONFIG generator expression? | According to the documentation, the $<CONFIG:cfgs> generator expression evaluates to 1, if the current configuration is one of the entries in cfgs and 0 otherwise. But how do I add more than one configuration to the cfgs-list?
The following snippet generates an error ($<CONFIG> expression requires one or zero parameter... | Handling multiple configs in the $<CONFIG:cfg> generator expression has been introduced only recently with CMake 3.19. Versions before only accepted a single configuration argument to the generator expression.
|
66,026,264 | 66,029,299 | How to manipulate text file in C++ | I have a txt file with the following data (inputFile.txt):
Start
FX
FX
FX
FX
End
What I am trying to achieve is to have the FX replaced by TL and BQ so that I have both repeated equally 4 times as the number of FX. See below (expected result - outputFile.txt):
Start
TL
TL
TL
TL
BQ
BQ
BQ
BQ
End
However... | Here is how I edited your code so it works as I think you want:
string line;
string duplicateLine;
std::vector<string> toBeReplacedLines1;
std::vector<string> toBeReplacedLines2;
size_t len = toBeReplaced.length();
while (getline(inputStream, line))
{
if (line == "Start" || line == "End")
continue;
dup... |
66,026,569 | 66,026,746 | CRTP with abstract interface, dynamic_cast working but dynamic_pointer_cast does not | I'm considering the basic example of CRTP in Wikipedia
#include <memory>
// Base class has a pure virtual function for cloning
class AbstractShape {
public:
virtual ~AbstractShape() = default;
virtual std::unique_ptr<AbstractShape> clone() const = 0;
};
// This CRTP class implements clone() for Derived
template ... | std::shared_ptr<AbstractShape> sq2 = sq1.clone();
auto sq3 = std::dynamic_pointer_cast<Square>(sq2);
dynamic pointer cast converts shared ptrs. The template deduction that is failing is that of the cast function.
|
66,026,635 | 66,028,233 | Resized opencv image is not displayed correctly on QWidget C++ | I try to display OpenCV image of size 3000 * 4096 on QLabel. The image is resized before displaying. If the resize factor that the size is divisible (e.g 2, 4, 8, 16, 32), the image is displayed correctly. If the size is not divisible by the factor (e.g 3, 5, 7, 10), the image is not displayed correctly.
I also tried w... | So the problem is OpenCV’s step is a size_t, it needs to be cast to int when you convert the image into QImage. However, I still don't know why it works when the image size is divisible by the resize factor.
QImage img(qImageBuffer, mat.cols, mat.rows, static_cast<int>(mat.step), QImage::Format_RGB888);
|
66,026,988 | 66,029,147 | Animate QML Button component | main.qml
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.1
import QtQuick.Controls 2.1
import QtGraphicalEffects 1.0
Window
{
visible: true
width: 640
height: 480
title: qsTr("Hello World")
TT
{
MouseArea
{... | @splaytreez's answer works, and he's right to recommend getting rid of your buttonPressed property and the extraneous MouseArea. I wanted to offer an alternative solution because I often find states and transitions hard to follow as code grows and becomes more complicated. A more direct approach is to create animation ... |
66,027,203 | 66,027,546 | Leaf at same level in binary tree | Given a Binary Tree, check if all leaves are at same level or not.
Input:
10
/ \
20 30
/ \
10 15
Output: 0
Explanation:
Leaves 10, 15 and 30 are not at same level.
Approach: The height of left subtree and right subtree should be same for each node.
My Code:
int height(Node... | You are only checking that the deepest leaf to the left of root is at the same height as the deepest leaf to the right of root. You need to check the minimum height against the maximum height.
std::pair<int, int> heights(Node * node) {
if (node->left && node->right) {
auto [lmin, lmax] = heights(node->left)... |
66,027,236 | 66,031,364 | OpenClipboard crashes with CLIPBRD_E_CANT_OPEN | I have a problem with opening clipboard multiple times. It opens up fine on the first call, however, my program needs to access the clipboard several times, but shuts down on the second call of OpenClipboard(NULL) with the CLIPBRD_E_CANT_OPEN error).
This is a function that opens the clipboard
void Translator::proc... | When storing a memory block on the clipboard, the HANDLE given to SetClipboardData() must be allocated with the GMEM_MOVEABLE flag, per the SetClipboardData() documentation:
If the hMem parameter identifies a memory object, the object must have been allocated using the [GlobalAlloc] function with the GMEM_MOVEABLE fla... |
66,027,326 | 66,027,413 | Tuple of shared_ptr from variadic template? | Take the following snippet as a base:
template<typename Type1, typename Type2>
auto Foo() {
std::tuple<std::shared_ptr<Type1>, std::shared_ptr<Type2>> example;
}
How should I go about creating my tuple of shared pointers when using a variadic template?
template<typename... Types>
auto Foo() {
// How to create ... | Expand the pack:
#include <tuple>
#include <memory>
#include <type_traits>
template<typename... Types>
auto Foo() {
using tup = std::tuple<std::shared_ptr<Types>...>;
return tup{};
}
int main() {
auto f = Foo<int,double>();
static_assert( std::is_same_v< std::tuple<std::shared_ptr<int>,std::shared_ptr<doubl... |
66,027,364 | 66,027,408 | Basic practice of dynamic library C++ | I am trying dynamic-linking test.
mylib.cpp
#include<iostream>
#include<stdio.h>
using namespace std;
int hello(){
cout<<"Hello,World!"<<endl;
return 1;
}
then compile
g++ -shared -o libmylib.so mylib.cpp
Now there appears the libmylib.so
test.cpp
#include <iostream>
int hello();
int main() {
hello();
... |
Do I need to add some options
yes, link with the library.
g++ ... -lmylib
|
66,027,384 | 66,029,127 | Boost Process exit code of terminated process | What should be a return code of a terminated process? I run "bash -c \"while true; do true; done\"" and call terminate. In boost 1.65 it was 0, now in boost 1.71 it is 383.
| The documentation of exit_code() states:
The return value is without any meaning if the child wasn't waited for or if it was terminated.
So it seems exit_code() isn't supposed to be called if the process is terminated.
On Linux, an "exit code" of 383 (0x17F) means the process is still running. So it's worth trying to... |
66,027,913 | 66,028,007 | What happens when converting char * to string *? | char * ss = "abscd";
string * b = (string *) ss;
std::cout << ss << std::endl;
std::cout << *b << std::endl;
The output is:
abscd
//empty line
I thought it would be :
abscd
abscd
| You must have misunderstood something. First of all you miss a const here:
const char * ss = "abscd";
Next, std::string is meant to replace c-strings, like the one you have with ss. However, std::string is a string, while std::string* is a pointer to a string. As std::string is not related to char as far as conversion... |
66,028,484 | 66,028,733 | How to properly reroute output (away from std::cout)? | I have heard several times, that one should avoid plain writes to std::cout. (Is this correct?) However, I did not find good examples of how to achieve this. What I came up with so far is this:
#include <iostream>
class Logger {
std::ostream os;
auto RdBuffer( bool const decision ) { return decision ? std::c... |
I have heard several times, that one should avoid plain writes to std::cout. Is this correct?
No. It is accepted practice to write output to the standard output stream - unless you're in some embedded setting, or using an exotic OS where output is handled very differently.
The operating system and other processes wil... |
66,028,617 | 66,028,704 | declare a c++ vector that can contain all data types defined in a namespace | i have a file called "dtypes.h", that contains some definitions for some numerical data types.
namespace dtypes {
typedef signed short int int16;
// ... some other dtypes
}
i also have another file where i want to create a vector that can contain all this data types (and other vectors). I figured out somethi... | You don't necessarily need to make the list right there, but you need to make the list somewhere. There's no way avoiding writing the list explicitly.
Like one of the answers in the linked question suggests, you could use a vector of std::any to store objects of any type. With the obvious drawback of losing the feature... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.