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 |
|---|---|---|---|---|
62,454,934 | 62,455,119 | optional<reference_wrapper<T>> vs. optional<T>& - practical examples? | I have read about std::optional<std::reference_wrapper<T>> as a way to pass around optional references.
However, I'm unable to think of a practical example where I'd do that, instead of just using an optional<T>&.
For example, suppose I'm writing a function which needs to take an optional vector<int> by reference.
I co... | std::optional<T> & is a reference to an optional object that can own a T object. You can mutate a T (if one is contained) or you can clear the optional object that was passed in by reference, destroying the contained T.
std::optional<std::reference_wrapper<T>> is an optional object that can own a reference to a T, bu... |
62,455,045 | 62,483,545 | How to detect if painting last frame in buffered paint animation? | I'm using BeginBufferedAnimation() during WM_PAINT to animate a custom control (cross-fade).
I know when the first frame of the animation is painted; when I call EndBufferedAnimation() with fUpdateTarget = TRUE.
I can determine if the animation is in progress by checking the return value from BufferedPaintRenderAnimati... | I found a better solution to my problem.
See EDIT 3.
|
62,455,055 | 62,455,740 | Minimal swaps for insertion sort | I was solving a question in codeforces,which was about insertion sort,
the link:the problem
I am unable to solve the question the editorial says
old - 2 * (di, ai + dj, aj - di, aj - dj, ai) - 1
I am not understanding the solution kindly help!
here is the editorial link:
https://codeforces.com/blog/entry/958... | For an insertion sort into a linked list, the number of "swaps" is maximum of 2, if you consider inserting a new item as "swapping pointers". The minimal number would be zero, if the key already exists; otherwise you'll swap one pointer when inserting before the head or after the tail.
The concept of an insertion sort... |
62,455,194 | 62,456,376 | How to wrap user functions? | I have three functions that will be used in different classes in a project. The functions use (only read) common variables, but manipulate the input data in a different way than each other.
I am not sure how to wrap those functions. I practically don't want common read-only variables to be available to the user. I came... | If you want to have your functions in a header file (for example, as inline functions or templated functions), it is typical to use a detail namespace. Yes, users of your header can access it, but it is common practice to just ignore it (as it is an implementation detail)
So,
#ifndef FUNC_H
#define FUNC_H
namespace de... |
62,455,297 | 62,456,197 | Using C++20 ranges with istreambuf_iterator | I can't compile a (very contrived) C++ ranges example:
#include <ranges>
#include <fstream>
#include <vector>
template <typename R>
auto populate(R&& range)
{
return std::vector<char>(range.begin(), range.end());
}
int main(int argc, char* argv[]) {
auto stream = std::ifstream{"/etc/hosts"};
const auto i... | This makes me sad.
filter_view::iterator is specified as, from [range.filter.iterator]:
constexpr iterator& operator++();
constexpr void operator++(int);
constexpr iterator operator++(int) requires forward_range<V>;
Notably, a subrange of istreambuf_iterator<char> is not a forward_range - it is an input_range (becaus... |
62,456,336 | 62,471,648 | SFML library-NOTFOUND error during MinGW build | I'm trying to build a test SFML program the following way:
Windows 10, CLion, MinGW64, CMake, SFML-2.5.1
CmakeList.txt
cmake_minimum_required(VERSION 3.14)
project(Test_sfml_cmake_)
set(CMAKE_CXX_STANDARD 17)
cmake_minimum_required(VERSION 3.0)
set(SFML_DIR "SFML-2.5.1/lib/cmake/SFML")
find_package(SFML 2.5 COMPONEN... | Your full path to the SFML library contains brackets [ ]:
"D:/_Documents/Cpp Projects/Test_sfml[cmake]/SFML-2.5.1"
This is a problem for CMake (see this question), as square brackets are special characters used to denote bracket arguments and quotes.
Using square brackets in the path causes weird behavior in this cas... |
62,456,383 | 62,456,584 | Concatenate multiple range adaptors into one single ranges in C++20 | Consider the following case:
std::vector<int> v{0, 1, 2, 3, 4, 5};
// 0 1 2 3 4 5
auto rng1 = std::views::all(v);
// 5 4 3 2 1 0
auto rng2 = std::views::reverse(v);
// 4 2 0
auto rng3 = std::views::filter(rng2, [](int x){return x % 2 == 0;});
Is there a elegant way to concatenate those three adaptors into one single v... | Yes, what you wrote just in a different namespace - there's no concat in the Standard Library but there is one in range-v3:
auto final_rng = ranges::views::concat(rng1, rng2, rng3);
The fact that the ranges are different types doesn't pose a problem. You just have an iterator that's built up of a variant of the underl... |
62,456,453 | 62,466,014 | Equivalent of OpenCv c++ api Vec2f,norm, acos in emgucv csharp | Here are OpenCV api in c++.
Vec2f
norm
acos
Please suggest what will be c# equivalent api in emgucv?
Thanks in advance.
| Vec2f
Depending on your application, you can just use System.Drawing.PointF, a float precision 2D point to store I and J as X and Y. However that won't support some of the opencv functions you may like to use. In which case, Vec2f is simply a 1 by 2 matrix of float, for this you can use:
Matrix<float> myVec2F = new Mat... |
62,456,610 | 62,457,025 | Why std::shared_ptr considered to be "heavy" and "expensive", but std::array "same perfprmance as plain (c-style) arrays"? | I don't quite understand why std::shared_ptr considered to be "heavy" and "expensive", but std::array "same performance as plain (c-style) arrays"? As in shared-ptr we have pointer and two counters: for shared and weak references. And in std::array we have pointer to a data and it's size(basically same as a pointer's c... |
And in std::array we have pointer to a data and it's size
A std::array has no need to store its size anywhere, much less store it in every object. For a given type, the value of std::array::size() is known at compile-time. (Don't forget that std::array<int, 2> and std::array<int, 3> are different types.)
template < c... |
62,456,690 | 62,465,124 | CGAL: Using the type `Mark` while exploring a plane map | The CGAL online documentation about CGAL::Nef_polyhedron_2<T>::Topological_explorer (please see here) mentions a type Mark and a number of functions, which return a value of this type:
const Mark & mark (Vertex_const_handle v)
returns the mark of v.
const Mark & mark (Halfedge_const_handle e)
returns the... | When you want to explore a plane map, you need to traverse elements (halfedges and/or vertices and/or faces). You can for example use a depth search first algorithm as for graph traversal.
During such traversal, it is often necessary to test if an element is already discovered of not. This can be achieved thanks to a B... |
62,456,779 | 62,459,397 | Getting 'unregistered datatype' error in QML when Q_GADGET struct is in a separate header file | I have a custom struct which I use as a Q_PROPERTY type in a QMediaPlayer derived class. But here's the code:
struct VideoMeta
{
Q_GADGET
Q_PROPERTY(int width MEMBER width)
Q_PROPERTY(...)
....
public:
int width;
...
};
Q_DECLARE_METATYPE(VideoMeta)
class FrameProvider : public QMediaPlayer... | Q_GADGET main usage is to allow a non QObject type to have introspection.
The Q_GADGET macro is a lighter version of the Q_OBJECT macro for
classes that do not inherit from QObject but still want to use some of
the reflection capabilities offered by QMetaObject. Just like the
Q_OBJECT macro, it must appear in th... |
62,457,083 | 62,461,577 | Using MPI_Gather leads to failed to attach to a bootstrap queue error | I need to write code, that send columns of matrix from each processes to root process.
I have following code:
int task8(int argc, char* argv[])
{
int rank, size;
double matrix[100][150];
double result_matrix[100][150];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(... | MPI_Gather() is a collective operation and must be hence invoked (with compatible arguments) on all the ranks of the communicator.
In your program, rank 0 does not invoke MPI_Gather() so your program will either deadlock or abort.
|
62,457,465 | 62,457,595 | Polymorphism with smart pointer | As the answers pointed out, this is a dumb mistake I made that has nothing to do with polymorphism or smart pointer. The corrected version is in the accepted answer.
============== Original question ==================
I am trying to make smart pointer work with polymorphism. In the following prototype code, the impleme... | You have a couple of issues.
This DerivedWrap pDW1(); is a function declaration whose return
type is DerivedWrap. It is not calling its default constructor which you are expecting to. You need simply
DerivedWrap pDW1; // calls the default constructor
// or
// DerivedWrap pDW1{};
Secondly, the pDW1 is simply a Deri... |
62,457,773 | 62,498,502 | C++ wxWidgets: Set Font After Widget Creation | So basically I found out that you can only set font before the widget creation or font won't change, but I need to change the font after element creation so how can I do it?
void MyMain::makeBtnPanel()
{
btnPanel = new wxPanel(this, wxID_ANY);
wxGridSizer* grid = new wxGridSizer(5, 4, 2, 2);
// here is hid... | Omg, I'm so dumb. I couldn't change font because I was setting font to empty variables. I wrote else if instead of if and code didn't execute, it didn't set these variables.
|
62,457,844 | 62,457,958 | How to identify whether an item is a file or a folder in QT | I wanted to specify from a path, whether the item is a file or a folder. How can I implement such function which takes a path (QString based input) and tells whether it is a file or folder?
| You can use the method QFileInfo::isFile() or QFileInfo::isDir() to accomplish this.
Example:
QFileInfo fi("/your/path/string");
if (fi.exists() && fi.isFile())
{
//Do stuff...
}
|
62,458,225 | 62,458,380 | What is in reality "endl" (or any output manipulator)? How is it implemented and how does it work with operator<<? | What is actually endl? Of course, it prints a new line and flushes the ostream buffer. But what is it actually? Can such "entities" like endl be defined by the programer?
There are these "output manipulators" which can be accessed using the library iomanip but what is actually going on when executing a command such a... |
What is actually endl? Of course, it prints a new line and flushes the ostream buffer. But what is it actually?
std::endl is a function. It
Inserts a newline character into the output sequence os and flushes it
Can such "entities" like endl be defined by the programer?
Yes.
Here's a demo program.
#include <iostr... |
62,458,553 | 62,458,819 | How to create a random distribution with no specific definition? Is uniform_int_distribution inheriting from other class? | I want to create a piece of code that use a type called Number that may be a floating point number or any integer number (such uint64_t). I have the variable dist that is the distribution that should be used to generate random numbers, but it should be different in any of those cases, so i would like to do something li... |
But this is not working because we are trying to compile code that inits uniform_int_distribution with a type that may or may not be integer (and the same for the real distribution).
No, if constexpr is evaluated at compile time and only one of the branches is compiled, the other is discarded, e.g. not compiled. Some... |
62,458,871 | 62,459,553 | How to call a function method recursively in classes in c++? | So, I started learning and reading about OOP not so long ago, I've been implementing all the data structures I know using classes and objects just for overall practice and to get comfortable with using OOP in c++.
I'm implementing the tree data structure and I've been wondering how to call a method recursively(I'm awar... | In your design, a node refers to itself. Since it is the node object that is recursive, you could define the recursive method on node:
struct node
{
int data;
node* left;
node* right;
void preorder() {
//...
left->preorder();
right->preorder();
}
};
And then, tree::preorder... |
62,459,646 | 62,462,706 | Including a certain header file causes errors from SFML | I'm trying to use ChaiScript with SFML for my game engine. All the SFML stuff works fine, until I include chaiscript.hpp in my game object header file. My GameObject header file looks a little like this:
#include <a bunch of standard libraries>
#include "imgui.h"
struct Object {
std::string name;
void init();... | It sounds like something in ChaiScript is messing up something in SFML. Reversing the order that you include them may remove those errors (include SFML before ChaiScript, or vice versa).
|
62,459,667 | 62,459,776 | how to pass a parameter to char*? | As in the code below, I can't pass this parameter, how do I fix it?
E0167 The "const char *" type argument is incompatible with the "char *" type parameter
Code example:
#include <iostream>
using namespace std;
int PrintString(char* s)
{
cout << s << endl;
}
int main(int argc, char* argv[])
{
PrintString("T... | This literal "TESTEEEE" is of type char const[9]. When used as an argument to a function, it can decay to char const* but not to char*. Hence to use your function, you have to make the parameter fit to your argument or the opposite as follows
#include <iostream>
using namespace std;
int PrintString(const char* s)
{... |
62,459,773 | 62,459,821 | Does placing an object in a list move its location in memory? | For example,
struct MyStruct
{
MyStruct* myStruct;
};
MyStruct a;
MyStruct b;
a.myStruct = &b;
b.myStruct = &a;
std::list<MyStruct> myList;
myList.push_back(a);
MyStruct* listA = &myList.back();
myList.push_back(b);
MyStruct* listB = &myList.back();
Are &a and listA the same? Will a.myStruct still work as a p... |
Does placing an object in a list move its location in memory?
No, it creates a new object (a copy) at another location in memory.
All standard containers "own" their elements, and they do that by copying the things you give them (or moving them, where applicable).
Are a and listA the same?
No.
Will a->myStruct sti... |
62,459,803 | 62,460,046 | Why is my double array not initializing to 0? | I am creating a 2-D array. However, when I use a double for-loop to check the contents of my 2-D array, it is filled with random numbers. I know that I can use a double for-loop to manually fill my double array with 0's. However, I am confused on why it does not do this when it is initialized.
int arr[5][5];
for (int ... | In C and C++, variables of POD (plain old data) types, and arrays of such types, are normally not initialized unless you explicitly initialize them. The uninitialized values can be anything, can even be different from one run of your program to the next. You will have to initialize them yourself.
There are cases where ... |
62,459,807 | 62,459,979 | how to split and join files in c or rust? | how to split and join files in c or rust?.
I found the split, but saw nothing about joining the files.
I want to split files of various types, from text files to images
want in c or rust because i am using rust, so i can create rust module in c.
[Edit]
I'm making a program that divides files to send by tpc, so I need t... | In C++, you split files by reading the master and writing to one or more new files.
This technique works with the C language also.
Joining files depends if you want to merge or append. In the append case, the destination file is opened with the "append" and write attribute. The file pointer is set to the end of the... |
62,459,947 | 62,460,098 | Why am I getting a segmentation fault error whenever I'm trying to run this LinkedList delete function? | I am trying to create a program to delete a node at the N'th position of a linked list. According to the output, it should be:
George
Betty
Felix
Renee
George
Betty
Felix
George
Felix
Felix
When running on repl.it (my submission website), it brings up that I am getting a segmentation error. However, when I run it... | Your code for everything but LinkedList::remove manages the list via the first member variable. But LinkedList::remove references head, a suspiciously otherwise-unused global variable. I'm confident that shouldn't even be in the code at all.
Delete the global head, and change LinkedList::remove to be:
void LinkedList::... |
62,459,996 | 62,485,415 | CMake Error at modules/videoio/cmake/detect_ffmpeg.cmake:16 | I'm trying to build OpenCV with opencv-contrib modules as extra modules using CMake-gui in order to get Cuda DNN to work with my GPU, but I got this error :
CMake Error at modules/videoio/cmake/detect_ffmpeg.cmake:16 (include): include could not find load file: C:/opencv_4/build/3rdparty/ffmpeg/ffmpeg_version.cmake
How... | I solved this error by building and installing OpenCV 4.4.0-pre + OpenCV-contrib (cloned the projects from GitHub) and built using CMake GUI and Visual Studio 2019 (with VS 2017 as C++ toolset platform).
Open CMake GUI and choose the OpenCV sources and OpenCV build folder (output folder).
Click on Configure and choos... |
62,460,059 | 62,460,188 | How to define value for C++ preprocessor directives during compile time? | Suppose I have a following code:
int main() {
#ifdef NEWMETHOD
val = new_method("hello world!");
#else
val = old_method("hello world!");
#endif
return 0;
}
How can I define NEWMETHOD during compile time?
| You can either
Define it by inserting
#define NEWMETHOD
into the source code before using it or
Add -DNEWMETHOD to your compiler call (works with all popular compilers including GCC, clang and MSVC).
Depending on your build system you might want to add that to the CFLAGS (C) or CXXFLAGS (C++) environment variables.
|
62,460,231 | 62,460,780 | C++ Return a Variable of an object | I am learning c++ currently and i have run to this problem:
Error Message: This Code should be of type bool or should be converted to bool.
The main function must stay the same, so i was wondering, that i use the line [A] and actuall return an bool.
The method should compare two cubics with each other, if they are th... | To return a boolean, you make the function… return a boolean.
Right now, it is trying to return an object of type cubics:
cubics same(cubics cube)
^^^^^^
Instead:
bool same(cubics cube)
^^^^
And return true, or return false, as appropriate.
That's it!
Your bool var doesn't need to exist at all.
I'd also recommend you... |
62,460,254 | 62,642,124 | Undefined behavior in sorting with comparator | I need to parse numbers from a string and sort vector in ascending range for the first number and, if first numbers equals, by second numbers in alphabetic order like strings:
[1, 250; 2, 30; 4, 40; 1, 26] -> [1, 250; 1, 26; 2, 30; 4, 40].
As "250" < "26", array sorted like before.
There is algorithm:
#include<assert.h... | Maybe site www.codewars.com making something wrong as i wrote in comments because I also try it with clang compiler and there are no errors.
Thank you all for trying to help me with my question!
|
62,460,903 | 62,461,466 | SIM 808 TCP connection (Arduino library) | I AM WORKING WITH SIM808 for tcp connection, below is what my code looks like it is pretty much the basic tcp connection and i keep get fetch over and I can tell that is a problem with my content lenght but i feel if i have a better understanding that will be fine.
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h... | If you just open up the .h file in the library you will find that it is pretty well documented. Have a look at the declaration for the function you are asking about:
/** read data from socket
* @param socket socket
* @param buf buffer that will store the data read from socket
* @param len string... |
62,461,049 | 62,461,181 | How can I only allow a function A to be called only after function B is called? | Consider the following code class:
class A {
public:
int number;
vector<int> powers;
A () {
number = 5;
powers.resize(100);
}
long long getPower(int x) {
return powers[x];
}
void precompute() {
powers[0] = 1;
for (int i = 1; i <... | One solution to your problem would be to call the precompute function in the constructor of class A.
Alternatively, as has already been suggested in the comments section, you could make the function getPower check a flag which specifies whether precompute has already been called, and if not, either perform the call its... |
62,461,483 | 62,461,558 | CodeBlocks compile program for 32bit computer | I'm trying to compile my code for a 32 bit system using CodeBlock default MinGW compiler adding the -m32 parameter, but I'm getting a lot of errors:
||=== Build: Debug in cONfuSioN (compiler: GNU GCC Compiler) ===|
ld.exe||cannot find -lstdc++|
ld.exe||cannot find -lmingw32|
ld.exe||cannot find -lgcc|
ld.exe||cannot fi... | Most builds of mingw.org and mingw-w64 only support either 32-bit or 64-bit. There are entirely separate toolchain distributions for 32-bit target than for 64-bit target.
You can have two toolchains installed side by side, but not have one toolchain with target switches.
(I have heard of someone who did do a multi-t... |
62,461,564 | 62,461,631 | The method find of a set of none const values cannot be called with const values. Can const_cast be used to solve that problem? | Let us say that p below has to be a pointer to const X. Then it is not possible to call find for a set of pointers to X with my special compare class. Is that a shortcoming of 'set' and 'find'? Is it safe to solve it with const_cast as I have done?
struct X{
std::string key;
X(std::string s): key(s) {}
};
str... | This use of const_cast is safe, but any usage of const_cast is scary. const_cast is legal so long as you don't modify the object through the cast, which std::set::find does not do.
However, you don't need a const_cast here. If you make your comparator transparent, that opts into allowing find to search based on anythin... |
62,461,870 | 62,462,031 | Why can detached thread in C++11 execute even if the destructor has been called | I just read the doc about std::thread.detach() in C++11.
Here is my test:
#include <iostream>
#include <thread>
#include <chrono>
static int counter = 0;
void func()
{
while (true) {
std::cout<<"running..."<<std::endl;
std::cout<<counter++<<std::endl;
std::this_thread::sleep_for(std::c... | In C++, std::thread does not manage the thread of execution itself. C++ does not have controls for managing the thread of execution at all.
std::thread manages the thread handle - the identifier of a thread (thread_t in Posix world, which was largely a model for std::thread). Such identifier is used to communicate (as ... |
62,462,070 | 62,462,385 | How to detect implicit conversion losses integer precision on std::vector::emplace_back | I compiled the following code with -Wconversion compiler option to detect implicit conversion loses integer precision:
#include <vector>
#include <cstdint>
int main() {
std::vector<std::uint16_t> v;
std::uint32_t a = 0;
v.emplace_back(a); // no warning
v.push_back(a); // warning: implicit conversi... | There is no implicit conversion when you call v.emplace_back(a). There would be an implicit conversion if you called v.emplace_back<const std::uint16_t &>(a).
A key difference between push_back and emplace_back is that the latter is a template while the former is not. If you do not specify a template argument for empla... |
62,462,077 | 62,462,528 | A one line function to convert a hh:mm:ss.zzz time QString to milliseconds? | I'm using Qt and I have a time QString of format hh:mm:ss:zzz, such as 01:59:25.345. I am wondering if there is already some handy functions in Qt or c++ that can easily convert this to milliseconds. As to the QTime::fromMSecsSinceStartOfDay(12334).toString("hh:mm:ss.zzz"); for the other way around.
| I think your format of Qt::ISODateWithMs is considered valid ISO 8601. Just prepend an aribitrary date with a T delimiter between date a and time.
QString timestamp = "2020-01-01T01:59:25.345";
int milliseconds = QDateTime::fromString(timestamp, Qt::ISODateWithMs).time().msecsSinceStartOfDay();
Also, if the current d... |
62,462,080 | 62,462,252 | why array size information is available to `sizeof` operator and delete[] operator, but not when passing array as an argument into function | I was wondering how sizeof operator and delete[] got to know the actual size of the array they are operating on, but when I pass an array as an argument to functions, that size information is lost and the size information needs to be passed into the function explicitly by the programmer?
What is the internal mechanism ... | The reason the delete[] operator knows how much memory is associated with a particular pointer value is because it has a copy of that value saved in its internal data structure that was written when new[] was used. From strictly a language standpoint, it doesn't know how much memory a pointer points to.
There's also a... |
62,462,084 | 62,462,197 | Comprehending the walk through of a recursive code | If I keep my hand on each line of code as we go through, then when we hit a function call, my hand goes to the function which is called and that function begins to execute, after that my hand returns back to the line where the function was called. Now when it comes to recursion, when I keep calling the same function, h... | Think of the call stack like a tray of index cards. The stack starts out empty. The only things you can do are write down a new index card and put it on the top, or take whatever is on the top off.
There is some stuff in that tray put there by the runtime, but for the moment let's just pretend that the tray is empty wh... |
62,462,413 | 62,462,783 | C++ template specialization - unable to match function definition | I've been beating my head against the wall for a day and a half, trying to learn template specialization and std::enable_if(). I'm not getting something. I'm trying to allow the specification of a return type from a class method, based on the class type AND user specification at compile time. For example, if the cla... | Sam's comment is spot on - you can't partial specialize member function. The work around is to use enable_if_t in the class body. Something like this should work:
template <class T> class Test {
public:
Test(T val) { val_ = val; }
template <typename U>
std::enable_if_t<std::is_arithmetic<T>::value && st... |
62,462,873 | 62,462,929 | template and decltype for void f(int) | I am learning writing my own traits using C++11 borrowing only std::true_type and std::false_type.
I've created the following trait:
#include <iostream>
template <typename F>
struct is_farg1: std::false_type {};
template <typename R, typename A>
struct is_farg1<R (*)(A)> : std::true_type {};
Now consider a program i... | Becasue decltype(f) gives the exact function type (i.e. void(int)) but not the function pointer type (i.e. void(*)(int)). When decltype is used for entity,
If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, then decltype yields the type of the entity named by thi... |
62,462,992 | 62,463,340 | How to statically link to NATS C library using ExternalProject_Add | I am trying to include NATS C client as a dependency to my project. I prefer to link statically as my project is quite small and works as a standalone service, so shipping one single executable is more convenient.
ExternalProject_Add seems the most promising for its compatibility with a variety of build systems. But I ... | When you are linking it with the static NATS library, you also need to link to the dependencies of the NATS library. In this case, it looks like it may just be the pthread library. CMake has a cool way of linking to the pthread library (for CMake 3.1.0 or newer):
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads... |
62,463,334 | 62,463,350 | Trying to return string array and print contents but receiving error | I am trying to return a string array in a function and print the variables of it. I know that there is no way to actually return an array in c++ but you can pass its pointer. So I set up the function to return the pointer value and then print it from there but the pointer is not working. I am getting an exception that ... | You're trying to return a pointer pointing to a local (stack allocated) array, which will be destroyed when the function returns and the returned pointer is always dangled.
You can use std::vector or std::array instead. e.g.
std::vector<string> User::getPersonal() {
std::vector<string> arr = { FirstName, LastName, ... |
62,464,426 | 62,464,482 | Why does std::round(sin(pi/6)) not equal 1? | The cppreference documentation states that std::round will specifically round away from zero in "halfway cases." While this is true with the literal 0.5, it's not true with std::sin(pi/6). I thought this might be a floating point error, so I printed the value but it's exactly 0.5. After inspecting the binary representa... | The issue is that you're not printing the value with enough significant digits. When I increase precision with std::setprecision(20), I get: round(0.49999999999999994449) = 0.
You can see this for yourself by either changing the code or entering 3fdfffffffffffff into the bottom Hexadecimal field of this online calcula... |
62,464,656 | 62,464,724 | c++ friend function and the private constructor | #include <iostream>
using namespace std;
class A;
class B {
public:
A createA();
};
class A {
private:
A() {
cout << "A Object created" << endl;
}
friend A B::createA();
};
A B::createA() {
A a_obj;
return a_obj;
}
int main(int argc, char* argv[]) {
B b;
A a = b.createA();
}
This ... | This problematic part is the B::createA.
Here you are 'reaching into' type B to pull out its member function createA. In order to do that, you need to know the complete type B. Otherwise, how would the compiler know where to find that member function, or if it even exists?
For the purpose of declaring a friend member f... |
62,464,795 | 62,464,868 | Variable always empty | I'm having troubles initializing a global variable. My C++ is a bit rusty so I can't remember the reason why my code isn't working.
file.cpp
const char * write_path = &(std::string(getenv("FIFO_PATH")) + "/pythonread_fifo")[0];
int main(int argc, char**argv)
{
std::cout << "printing a string: ";
std::cout << (... | write_path is initialized as a pointer pointing to the 1st element of a temporary std::string, which will be destroyed immediately after the full expression, left write_path dangled, dereference on it leads to UB.
You can use std::string directly, or use a named std::string, then get the pointer from it.
std::string s ... |
62,464,818 | 62,464,951 | Equivalent operation to remainder operator for handling values below the minimal allowed | I have a set of indices in a loop from 0 to 5. If user specifies an index above 5, ex 7, index 7-6=1 should be returned. If an index is specified below 0, ex -2, index -2+6=4 should be returned.
In the first case we can use remainder operator to handle the values above 5:
int inputValue = 7;
int result = inputValue%6;... | If you mod a negative number by six, you’ll get back a negative number, but you can just add six to it to get your positive remainder:
int result = (inputValue % 6) + (inputValue < 0? 6 : 0);
Or, using the fact that adding six to a positive remainder leaves a number with the same remainder:
int result = ((inputValue %... |
62,465,062 | 62,559,865 | Best way to mark a pybind11-binding as deprecated | I have a C++ class with Python bindings using pybind11.
Now I want to mark the binding of one method as deprecated. Let's assume it looks something like this:
PYBIND11_MODULE(my_module, m)
{
pybind11::class_<Foobar>(m, "PyFoobar")
.def("old_foo", &Foobar::foo) // <-- this is deprecated in favour of "new_f... | Okay, here is my working example. I actually couldn't figure out to call the imported python function with a Python C Type, so I just went straight to the C API, which should perform better anyway
struct Foobar {
Foobar() {}
void foo(int32_t art) {}
};
PYBIND11_MODULE(example, m) {
pybind11::class_<Foobar>(m,... |
62,465,794 | 62,468,612 | getopt_long_only return -1 on second call | I was writing a C++ to tcl conversion for a proc that accept arguments. It uses getop_long_only. I was able to load the shared library created and run it the first time. However the second time I call, the getop_long_only always gives me -1 and this cause the proc to malfunction. The call snapshot is below. I also... | If we look at the documentation for getopt_long_only(), we see these key lines:
The variable optind is the index of the next element to be processed in argv. The system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector.
And also:
No... |
62,465,919 | 62,466,806 | How to check if filesystem is already mounted using C/C++ | Hi I am writing an application which mounts cgroup as shown below
mount("cgroup", "/sys/fs/cgroup", "tmpfs",0,NULL);
I am able to do this but I want to add a check to know if this is already mounted, how do I do that using C/C++?
Is there any API or system API to get mount information.
I do not want to use system() c... | You want to enumerate /proc/mounts using getmntent_r
|
62,466,467 | 62,466,573 | Why can't I pass std::vector<MyType> to this function with template template parameters? | I am new to C++ templates and I want to write a template function which, depending on its parameters, returns either a single object or a vector of objects.
I have a configuration class that holds key/value pairs. Say I have the key "parent.child.1", it should return a single object with id=1. If I have the key "parent... | The 2nd getParameter takes two template parameters, but getParameter<std::vector<MyObject>>(...) specifies only one template argument then it won't be selected.
I think just making the 2nd getParameter taking one template parameter should be fine. e.g.
template<template T>
void getParameter(const string& key, typename ... |
62,466,632 | 62,466,689 | Scope a variable on stack in c++ | Hi there i am new in c++ and my question is related to scope of a variable . Let me ask the quesion considering the code below
#include <iostream>
static int* fun(){
static int *ptr = new int(4);
return ptr;
}
static int * tun() noexcept{
int f = 111;
*(fun()) = f;
return fun();
}
static int *sun(){... | The variable f is gone, but its value has been stored in the int that the pointer returned by fun points to.
The code can be simplified to
#include <iostream>
int * tun() {
static int* ptr = new int;
int f = 111;
*ptr = f; // copy value of f
return ptr;
} ... |
62,466,745 | 62,508,630 | What's the proper way using GTest to repeat a multi-threaded test multiple times? | Using Google Test, I want to test the behaviour of a ClientListener.AcceptRequest method:
class ClientListener {
public:
// Clients can call this method, want to test that it works
Result AcceptRequest(const Request& request) {
queue_.Add(request);
... blocks waiting for result ...
retur... | Simple answer: use --gtest_repeat when executing tests would do the trick (default is 1).
Longer answer: unit tests shouldn't be used for this kind of tests. GTest is thread-safe by design (as stated in their README), but this doesn't mean it is a good tool to perform such tests. Maybe it is a good starting point to ac... |
62,467,026 | 62,467,190 | While loop going past limit | while (('\0' != *str1) && ('\0' != *str2) &&
(false == sensi) ? (std::toupper(*str1) == std::toupper(*str2)) : (*str1 == *str2)) {
++str1;
++str2;
}
This code keeps looping even past the NULL terminator.
There must be something incredibly obvious I am missing here, but I simply cannot see it.
If either one... | while (('\0' != *str1) && ('\0' != *str2) &&
(false == sensi) ? (std::toupper(*str1) == std::toupper(*str2)) : (*str1 == *str2))
The ternary operator ?: has lower precedence than nearly all other operators, including the logical AND &&. So, the &&s get applied first, and thus what you are saying here is:
if str1 ... |
62,467,622 | 62,467,711 | how to overload + and += operators as non-member functions? | I'm currently trying to refresh and improve my C++ skills and I'm reading a few books in parallel depending on the subject I need to dig into.
I'm currently spending time on The C++ Programming Language from Stroustrup. At page 61/62, there's an example of class for Complex numbers. It overloads a number of operators l... | In your example the operator + should either be made inline so that the linker knows that multiple obj files can contain the same function definition.
inline Complex operator+ (Complex a, Complex b) { return a += b; }
Or the header file should contain only the declaration
Complex operator+ (Complex a, Complex b);
and... |
62,467,910 | 62,475,155 | Executing code automatically at program start without violating ODR | I try to code a simple way to execute code at start of the program automatically (without using not portable attribute()).
I wrote the following code, and I'm asking if it does violate the ODR if the code written before main() is put in header files.
Or, does the inline function and variable prevent that?
Would there b... | Your solution should be ODR-safe. The C++ standard requires that there is only one instance of static data member auto_init_ for each distinct instantiation of execute_at_start<> class template and that it is initialized once.
Itanium C++ ABI (most compilers comply with it, apart from MSVC) requires guard variables for... |
62,467,942 | 62,483,658 | Why doesn't the c++ file run in visual studio | So I tried making a basic game on the console using screen buffers, I was able to create it and make a square move in the canvas, but for my next project I looked up a website with the ASCII characters and pasted a couple into a comment at the end of the c++ file, when I ran the file visual studio prompted:
I clicked ... | I fixed the error by deleting ComponentModelChache folder located at:
C:\Users\%userName%\AppData\Local\Microsoft\VisualStudio\15.0
15.0 is the version of your visual studio so it varies depending on the version you're using, %userName% is a replacement for the user you're logged in as
|
62,468,314 | 62,469,106 | C++ Read File being wiped at start of program using ofstream | I'm trying to read a text file and output the contents. It's just I can't seem to find the right method and the ones I've used (including this one), seems to wipe the text file. The code:
std::string Line;
std::ifstream File("Account.txt");
if (File.is_open()) {
while (getline(File, Line)) {
std::cout << Li... | Your file is being wiped by your file creating code.
std::ofstream File("Account.txt");
File.close();
To create a file without wiping existing contents try this
std::ofstream File("Account.txt", std::ios_base::app);
File.close();
|
62,468,531 | 62,470,167 | Linking to stdc++fs with C++20 still necessary when using filesystem? | I began using experimental::filesystem when it had just come out and I was advised to link in stdc++fs using target_link_libraries(MyTarget stdc++fs) in CMake. My programme builds either way but may I be breaking something/ doing something unnecessary if I leave out the extra link command?
This question here was asked ... | Lifted from my comment:
I guess it depends on your compiler version. From cppreference, At the very bottom of the File System Library page, you can find:
Using this library may require additional compiler/linker options. GNU
implementation prior to 9.1 requires linking with -lstdc++fs and LLVM
implementation prio... |
62,469,033 | 62,470,168 | Coin Change : Find number of ways to reproduce a given sum |
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make the change? The order of coins doesn’t matter.
For example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output shoul... | when you run your function after all of the for loop. you will have DP shown below.
1 0 0 -1 -1 -1
1 1 1 0 -1 -2
1 1 2 1 1 -1
-1 1 2 0 2 1
dp[3][5] = 1 that's why you are getting 1.
|
62,469,680 | 62,470,215 | Condition For Invalid Pointer | Invalid pointer is a pointer point to an address can't access by current program, if try to use invalid pointer, then OS will block it happen, in C++ Primer chapter 2 said
Using an invalid pointer as a condition or in a comparison is undefined
but I am just try to compare pointers, not dereference them, how to expla... | The primer says the behavior is undefined.
In most cases leaving the behavior undefined is done because saying anything else (as in comparing an invalid pointer returns false) would mean some performance cost (extra memory, an extra check). It doesn't mean that the comparison will not return a result. It means that the... |
62,470,225 | 62,470,502 | C++ parse text from .txt file to variables | what is the simplest way to parse data(C++) from my text file and store it to variables?
I have a parse_data.txt with this text:
{"song":"Holiday","artist":"Green Day","Album":"American Idiot","Service":"Spotify"}
I need store Holiday to song variable, Green Day to artist variable...
so QString song = Holiday...
Can s... | Can we assume that you are using QT? If so, there is an response here that can show you an example on how to use here
Here is how you can apply to your code
QString jsonString = [your json string represenation];
QJsonDocument jsonResponse = QJsonDocument::fromJson(jsonString.toUtf8());
QJsonObject jsonObject = jsonResp... |
62,470,415 | 62,470,480 | Why a member function cannot modify the local copy of the variable from the main function? | I'm trying to understand how a member function of a class behaves when creating a local copy of the
private variable. (Not when accessing it through reference)
So I have this code and my understanding is this:
Inside the member function get_name0() the vector "name" is a local copy of the private data member "name".
... | get_name() returns a copy of the member. Two different calls return two different copies of the member.
This will result in the expected output:
int main()
{
Name_pairs np0;
auto name = np0.get_name0();
name.push_back("m0");
cout << "\nnp0 object: ";
for (string s : name)
cout << s << " ";
... |
62,471,108 | 62,471,261 | Generalize a class' member from a specific container type (of pointers to itself) | Suppose you have the following class:
template<typename T>
class Node {
public:
T data;
std::vector<Node*> children;
};
I excluded its methods because I want to focus on a different point: the developer is constrained to use std::vector as a container for children.
In the context of programming to an abstracti... | You could add an additional template template parameter, like this:
template<template <typename...> typename Container, typename T>
class Node {
public:
T data;
Container<Node*> children;
};
and then instantiate Node with different containers:
Node<std::vector, int> n;
Node<std::set, int> m;
However, if you w... |
62,471,810 | 62,533,601 | Qt QTableView resize to fit content |
Hi, I have created MainWindow as shown above. I want to expand the first widget (plots) as much as possible so that the other two widgets fit content (or actually, I want to remove white empty space below tables).
I don't know how to do that.
Currently, both table vertical header size policy is set to FitToContent.
Al... | Ok, I figure it out.
Reimplementing the resizeEvent will do the trick.
def resizeEvent(self, event):
super(Table, self).resizeEvent(event)
height = self.horizontalHeader().height()
for row in range(self.model().rowCount()):
height += self.rowHeight(row)
if self.horizonta... |
62,472,520 | 62,473,010 | Is it possible to access variables and their values in a running program (c++) | Is it somehow possible to access variables which another program is using while its runnning using c++?
for example i have a program which always changes the variable a by 1, and i want to create another program and access the a variable and its value.
| Yes, it is possible to access variables in another program, provided:
The variable is not on the "stack".
The variable is not in a register.
The program is running at the same time as your program.
The memory page that the variable resides in is in memory and hasn't
been "paged out" to the hard drive (i.e. virtual m... |
62,472,737 | 62,472,931 | C++: pass shared ptr by reference without breaking the sharing? | Suppose I use smart pointers? Ok, great:
shared_ptr<whatever>(new whatever());
Instantly, I want to do the following rather than tangle with C++'s single-return item policy and the semantic mess therein:
void do_something(whatever *& A, whatever *& B){
auto Aptr = shared_ptr<whatever>(new whatever());
A = Aptr.get... | May be your problem can be solved by a structure with a constructor or two:
struct NoNeadachesWhatsoever {
shared_ptr<double> asp;
shared_ptr<int> bsp;
shared_ptr<T> csp;
NoNeadachesWhatsoever() {
// initialize members.
}
};
// ...
NoNeadachesWhatsoever no_headaches_whatsoever;
|
62,473,399 | 62,473,530 | Map error in the initialization with static functions | I tried to understand the error but no idea.
The map looks like this:
std::map<std::string, IOperand *(Factory::*)(const std::string &)> _func
And trying to give the value like this:
_func["int8"] = &Factory::createInt8;
And how is my class:
class Factory
{
public:
Factory();
~Factory();
static IOperand *... | The value type of the map is IOperand *(Factory::*)(const std::string &), which are non-static member functions of Factory. What you have in your class are static member functions. You can fix the problem by changing the value tpe of the map or by changing the functions.
Option 1
Change the value type.
std::map<std::st... |
62,473,492 | 62,473,661 | Difference in fRead methods | I am reviewing an old cpp program which reads data from a binary file. The code was written on Mac OS and for Mac OS. The author (who I am unable to contact) uses two variations of fread(). One with the second argument specified as sizeof(int) and one as sizeof(unsigned). Assuming that sizeof(int) == sizeof(unsinged) i... |
Assuming that sizeof(int) == sizeof(unsigned) is there any difference
in using these two methods?
No. The sizeof operator will resolve at compile time to a value of size_t type (itself typically unsigned long or unsigned long long) that is the number of bytes in those types (normally 4 or 8).
In fact, this C++ Draf... |
62,473,777 | 62,474,140 | Get console's cursor position | I am kinda new to C++ and i was wondering if is there any way to get the Console's Cursor position (x, y)?
For example, In C# i can use:
Console.CursorLeft for X and Console.CursorTop for Y
| If you are on Windows, you can do this (error handling omitted for brevity):
HANDLE hConsoleOutput = GetStdHandle (STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi = { };
BOOL ok = GetConsoleScreenBufferInfo (hConsoleOutput, &csbi);
The current cursor position should then be in csbi.dwCursorPosition;
Documentation ... |
62,474,250 | 62,474,670 | Partial template specialization for template class like std::function | I want to create a function overload to partially specialize a template class. How to make this code work?
template <typename T>
struct Foo;
template <typename Result, typename ... Args>
struct Foo<Result(Args...)>
{
Result Bar()
{
Result t;
return t;
}
};
template <typename ... Args>
void... | If it's just a single member function that should expose different behavior if Result=void, then use tag-dispatching:
#include <type_traits>
template <typename T>
struct Foo;
template <typename Result, typename... Args>
struct Foo<Result(Args...)>
{
Result Bar()
{
return Bar(std::is_void<Result>{});
... |
62,475,083 | 62,476,655 | Circular Queue That has a display function that displays even numbers only | hi so i have this circular queue c++ program i need its display function only displays even inserted numbers only can someone here help please here's the code
i need a way that this program only displays even numbers only i'v been trying to use the %2==0 on some location that might make sense but mostly i get them wron... | Here's a quick example using std::queue:
#include <iostream>
#include <queue>
int main()
{
// This deque is declared just to more easily instantiate the queue
std::deque<int> deck{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::queue<int> q{deck};
while (!q.empty()) {
if (q.front() % 2 == 0) {
std::cout << q.f... |
62,475,273 | 62,475,601 | Is this explicit linking against OpenMP::OpenMP_CXX still necessary with this CMake linking command? | I am using CMake and GNU's parallel algorithms and the following code snippet in my CMakeLists.txt:
if (OPENMP_FOUND)
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LI... | While the code:
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
will update your C++ compile flags with the proper -fopenmp option, this is an old antiquated approach.
By linking against the provided imported target OpenMP::OpenMP_CXX, you achieve the same effect because this target provides the -fopen... |
62,476,202 | 62,499,411 | Enumerate all device paths | I am trying to get paths of all devices with device interfaces, but when I call SetupDiEnumDeviceInterfaces I get ERROR_NO_MORE_ITEMS.
#include <windows.h>
#include <setupapi.h>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, const char **argv)
{
HDEVINFO hdevinfo = SetupDiGetClassDev... | we can retrieves a list of device instance IDs for the local computer's device instances with CM_Get_Device_ID_ListW function
then for every ID obtains a device instance handle to the device by CM_Locate_DevNodeW
and then retrieves a device instance property's with CM_Get_DevNode_PropertyW. for example DEVPKEY_NAME and... |
62,476,424 | 62,476,803 | How to access the IOMemoryBufferDescriptor in CompleteAsyncIO, which is sent through AsyncIO on Interrupt EP | I am trying to send request using AsyncIO for Interrupt EP, for AsyncIO I have created IOMemoryBufferDescriptor, once IOMemoryBufferDescriptor, Create is success I used GetAddressRange and stored Address in ivars structure of dext. For this request completion(CompleteAsyncIO) is called using action-> GetReference() I g... | The problem is on this line:
ivars->fCommPipeBuffer = (uint8_t*)&aRange.address;
This is saving the pointer to the address field of the IOAddressSegment struct variable, not the pointer to the buffer itself. You want:
ivars->fCommPipeBuffer = (uint8_t*)aRange.address;
or, less error-prone and more idiomatic C++:
ivar... |
62,476,645 | 62,476,824 | Can I in-place construct in Rust? | I like emplace()ing in C++ which allows to save on move construction and destruction: e.g. strings.push_back("abcd"s) means
construct, move, destruct the temporary
while
strings.emplace_back("abcd") is just "construct".
Can anything similar be achieved in Rust (maybe with compiler optimizations)? The usual vec.push(S... | I think emplace feature mostly backed by placement-new feature in C++ and similar unstable feature was removed couple years ago from Rust. Therefore no, it is not possible do the similar with high-level code.
Nevertheless you are still able to use ptr::write and achieve the same behavior in unsafe code.
|
62,476,662 | 62,477,672 | How do I retrieve the mimeData for a particular item in a QTreeWidget? | I am trying to programmatically "drop" an item onto a QTableWidget using QTableWidget::dropMimeData().
I know which item I want to drop and I know that QTreeWidget has a QTreeWidget::mimeData() function, but I can not use that mimeData() function because it is protected.
Basically, how can I "select" a QTreeWidgetIte... | I think you can't use QTableWidget::dropMimeData(row,col,mimeData,action) because it's protected.
In my opinion, you can use QVariant QTreeWidgetItem::data(int column, int role) const to get your tree node. After that, you could use QTableWidget::setItem(int row, int column, QTableWidgetItem *item) to insert a new item... |
62,476,750 | 62,477,066 | Cython: unable to assign to 2d vector | I have the following:
# distutils: language = c++
from libcpp.vector cimport vector
def foo():
cdef vector[vector[int]] matrix
matrix.reserve(100);
matrix[0] = [1,2,3]
print(matrix)
foo()
It prints out an empty list; I expected it to print out a vector with the first element being [1,2,3].
Setup.py ... | You should use matrix.resize(100) and not matrix.reserve(100). std::vector<>::reserve doesn't change the size of the vector - it only reserves the memory so no further (multiple) reallocations need to happen:
%%cython
...
matrix.reserve(100)
print(matrix.size()) # prints 0
matrix.resize(100)
print(matrix.size()) # pr... |
62,477,032 | 62,477,096 | aliasing access to individual array members | I have a set of ints that i need to access as an array and also have nice aliases for specifc ones.
I have
std::array<int,10> numbers;
I can clearly do
int n2 = numbers[2];
but numbers[2] represent (lets say) width of noodle
would be nice to be able to code
int twidth = width;
I know I can go
const WIDTH = 2;... | Just use a reference.
const auto& width = numbers[2];
// use width here for whatever you want as a read only value.
If you want to be able to change the value, then just drop the const so you have
auto& width = numbers[2];
If you want to provide names for all of the elements of the array, you can use a structured b... |
62,477,086 | 62,477,361 | Redirecting cmake output in C++ using CreateProcessW | I'm trying to redirect a program output in C++ on Windows using CreateProcessW.
When I try to use it to redirect the output of programs such as git it works fine but when I'm doing it with cmake I get the following message on the console instead:
Failed to create ConsoleBuf!
My code looks like that:
void Process::Star... | As Brecht Sanders said, changing the value of dwCreationFlags from 0 to CREATE_NEW_CONSOLE solved the issue.
|
62,477,238 | 62,477,317 | C++17 multiplying a list using reduce in conjunction with multiplies doesn't work | I'd like to multiply the elements of a float list using reduce in conjunction with multiplies:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <numeric>
using namespace std;
int main () {
vector<float>series{2, 1.91421, 2.06538, 2.25, 2.43607};
float result = reduce(series.begin(), series.en... | Note that the interface of reduce() is:
template<class InputIt, class T, class BinaryOp>
T reduce(InputIt first, InputIt last, T init, BinaryOp binary_op);
Notably, it deduces the type from the initial value and returns that type. You're passing in 1, which is an int. So this returns int and the internal accumulator i... |
62,478,011 | 62,484,879 | GLFW glfwCreateWindowSurface return -7 | I found this code on the internet, but I'm getting this error: VK_ERROR_EXTENSION_NOT_PRESENT(-7) on glfwCreateWindowSurface
result = glfwCreateWindowSurface(instance, window, nullptr, &surface);
std::cout << result; // -7
Code:
#include <iostream>
#define VK_USE_PLATFORM_WIN32_KHR
#define GLFW_INCLUDE_VULKAN
#include... | uint32_t amountOfGlfwExtensions = 0;
auto glfwExtensions = glfwGetRequiredInstanceExtensions(&amountOfExtensions);
Notice amountOfGlfwExtensions vs amountOfExtensions variable names. amountOfGlfwExtensions stays 0, and so when used with vkCreateInstance enables no extensions.
|
62,478,016 | 62,478,562 | How to call an .exe (C++) from windows console to create a folder in a different directory (or any directory)? | I have been researching a topic unsuccessfully for a couple of days. I'm a C ++ rookie, and as a practice i decided to make a basic (very very basic) copy of a version control system.
I have separated the project into steps. The first step (splited in activities) is:
The user searches, in the windows console, for the ... |
Calling to emi.exe (C:\ProgramFiles\emi\emi.exe) through the console from any directory (necessary to track any file in any folder).
For this you need to add the folder of your executable (i.e. C:\ProgramFiles\emi) to the system global variable called PATH (both Windows and Linux work this way, and must be MAC OS a... |
62,478,520 | 62,479,392 | How to solve the problem that program works in the same way in case of negative numbers? |
As a result, the program must display the 3 largest elements of the sequence. Elements must be displayed from small to large and not using array...
Examples
Input:
3 1 2 3
Work result:
1 2 3
Input:
5 2 -4 16 0 15
Work result:
2 15 16
Input:
3 0 -1 -2
Work result:
-2 -1 0
Here is my code:
#include <iostream>
i... | My five cents.:)
#include <iostream>
#include <utility>
int main()
{
size_t n = 0;
int max1, max2, max3;
std::cin >> n;
size_t i = 0;
for ( int number; n-- && std::cin >> number; i = i < 3 ? i + 1 : i )
{
if ( i == 0 )
{
max3 = number;
}
else
... |
62,478,533 | 62,510,511 | What C++ [[attributes]] are implemented by cheerp? | The C++11 specification defined [[attributes]] which can be used to specify/influence implementation-defined behavior. Cheerp supports this for specifying whether you're writing C++ code meant to be compiled into [[cheerp::genericjs]] or [[cheerp::wasm]] code. This results in your C++ code being compiled into the .js o... | The ones that are meant to be used by users are:
cheerp::genericjs: compile the associated item (class/struct definition, global, or function) to JavaScript, using the object memory model
cheerp::wasm: compile the associated item (class/struct definition, global, or function) to WebAssembli OR asm.js, using the linea... |
62,478,606 | 62,482,295 | Connection reset by peer socket error when the client terminate connection during write() | I have my server sending a large file to client(web browser) but when i refresh my page i am getting the conection reset by peer error and the program terminates. What i am expecting is server get a new connectiont.
while (true)
{
check((new_socket = accept(server_fd, (struct sockaddr *)&address,
... | Yes, you can use send() with MSG_NOSIGNAL or you can set SO_NOSIGPIPE socket option with setsockopt(). But with the minimal change in the existing code and for applying the settings to all the created sockets, You can do something like this:
From the man page of write()
EPIPE : fd is connected to a pipe or socket who... |
62,478,809 | 62,480,337 | Sub-quadratic algorithm for fitting a curve with two lines | The problem is to find the best fit of a real-valued 2D curve (given by the set of points) with a polyline consisting of two lines.
A brute-force approach would be to find the "left" and "right" linear fits for each point of the curve and pick the pair with minimum error. I can calculate the two linear fits incremental... | Disclaimer: I don't feel like figuring out how to do this in C++, so I will use Python (numpy) notation. The concepts are completely transferable, so you should have no trouble translating back to the language of your choice.
Let's say that you have a pair of arrays, x and y, containing the data points, and that x is m... |
62,479,026 | 62,544,226 | How can I link both C and C++ code, along with C and C++ runtime libraries (including STL) on android ndk? | I have a large code base with mixed C and C++ code. It is built into libraries, and then ultimately to an executable that runs on android based devices. This is an "external build system" that does not use gradle. After all compilation and libraries are built, the final link command is something like
armv7a-linux-an... | I was building for API 30 and running on an older target. I changed the link command to armv7a-linux-androideabi23-clang++ and it worked.
|
62,479,370 | 62,479,861 | Efficient algorithm to compute combinations with repetitions of an array adding up to given sum | So in a personal C++ project I am faced with a problem. I am rephrasing it as follows :
Given an array of n elements (e.g. [1, 3, 5], with n = 3 elements) where the number at the ith position denotes how many possible values the number at ith index can take (e.g here the first element can take 1 value which is 0; the s... | It's a pretty simple recursive task:
#include <bits/stdc++.h>
using namespace std;
int arr[] = {2, 2};
int n = 2;
int k = 2;
void gen(int pos, int sum, string s){
if(pos == n){
cout<<"["<<s<<" ]"<<endl;
return;
}
for(int i = 0; i < arr[pos]; i++){
if(sum + i > k) return;
... |
62,479,644 | 62,480,010 | C++ assign void pointer an string | I have the next problem. I have a function like this.
unsigned long FuncTest(void* name) { ... }
When I call FuncTest, I'll make of this form
int main()
{
void* test = NULL;
cout << "Value of test before to call Function: " << test << endl;
FuncTest(test);
cout << "Value of test after to call Functi... | If you are going to change the value of test then just pass the pointer of test as a parameter of FuncTest function.
FuncTest(&test);
And FuncTest needs to be changed like this
void FuncTest(void** name)
{
char* NewValue = _strdup("Hello!");
cout << "Value of name in FuncTest before change: " << name << endl;
... |
62,479,769 | 63,345,550 | Avoiding C++ virtual inheritance | I'm trying to inherit from a hierarchy of abstract base classes, using an equivalent hierarchies of implementation classes. The only way I've figured out how to do it is using virtual inheritance.
/* Foo Interface */
class IFoo
{
public:
virtual void foo() = 0;
virtual ~IFoo() = default;
};
/* Bar Interface ... | I came up with a solution that avoids virtual inheritance, but also gets rid of code duplication. I used a template parameter to specify the base class.
/* Foo Interface */
class IFoo
{
public:
virtual void foo() = 0;
virtual ~IFoo() = default;
};
/* Bar Interface */
class IBar : public IFoo
{
public:
vir... |
62,479,847 | 62,480,114 | Chained builder pattern in C++ | I am trying to create a a chained builder in C++ as follows:
#include <string>
#include <vector>
using std::string;
using std::vector;
class AbstractBuilder {
protected:
AbstractBuilder&
add_field(string name, string value) {
// blabla, add field to json structure
return *this;
}
};
cla... |
AFAIU the object returned from the add_field in the Event::Builder is going to be [...]
You are applying higher level reasoning. What is the compiler allowed to assume? It sees that add_field() returns AbstractBuilder& and you are trying to return that (from event() and payload()) as a Builder&. How can this be done?... |
62,479,992 | 62,480,083 | C++ Version of Python's "try: except:" | In Python, there is a way of executing code under "except" if there is an error performing the code under "try".
Example:
try:
import urllib
except ImportError:
import urllib2
I am quite new to C++, and I'm trying to clear the console, but the way to do it is different on Mac (system("clear")) and Windows (sy... | For your problem you could use macros
#include <stdio.h>
#include <stdlib.h>
#ifdef __linux__
#define SO "Linux"
#elif _WIN32
#define SO "Windows"
#elif _APPLE_
#define SO "Mac"
#endif
I'm not quite sure about the macro for mac try APPLE , OSX
More info in: https://developer.apple.com/library/mac/documentation/Porti... |
62,480,044 | 62,480,156 | Incorrect mathematical results calculating power series | #include <iostream>
#include <cmath>
using namespace std ;
int main ()
{
int n, sum=0 ;
cout<< "Input number of terms: " ;
cin>> n ;
for (int i=1; i<=n; i++)
{
int k = pow(10, i) - 1 ;
cout << k ;
if(i < n)
{
... | Here is the for loop without using the pow function:
int power = 10;
for (int i = 1; i < n-1; ++i)
{
const int k = power - 1 ;
cout << k;
if(i < n)
{
cout<< " + " ;
}
sum += k;
power *= 10; // This is important.
}
This should be more accurate than using pow because there is no conversions between ... |
62,480,150 | 62,480,600 | application failed to find Chromium-edge browser | I created a sample application to open a webpage on microsoft edge, by following below URL guidance.
https://learn.microsoft.com/en-us/microsoft-edge/webview2/gettingstarted/win32
I installed packages using NuGet packet manager as instructed. Everything worked fine on development machine.
Then I copied the exe of my sa... | What version of the SDK package are you using?
The way to find out the minimum version of the browser for a given SDK package is to look at the build numbers. For example:
SDK version 0.9.538 requires Edge n.n.538.n+
More details can be found here:
https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/vers... |
62,480,357 | 62,480,505 | How to Implement a C++ Plugin System for a Modular Application? | I am trying to design a modular application; one where developer's create plugins as dlls that get linked to the main application using loadlibrary() or dlopen(). My current thoughts on this are:
1: Both the application and plugin module include a core header with a pure virtual class IPlugin with a method run(). The ... | An API either uses C++ or C, there’s no middle ground. If you want to force plugin developers to use an ABI compatible compiler then you can have an interface that deals with classes and virtual methods and there’s no need for any “extern C” brouhaha.
Otherwise, you’re providing a C API and a C API only. Of course you ... |
62,480,364 | 62,480,483 | Universal reference l-value not copying object | Why these asserts work for the below code? The universal reference should bind to l-value reference run(T& a), and copy an object b from a. However both objects addresses "a" and "b" are the same in the run() function. Tested with C++11/14/17/2a gcc-9.2 and clang++-6.0. What part of the standard says this is valid? did... |
However both objects addresses "a" and "b" are the same in the run() function.
When being passed an lvalue, T is deduced as lvalue-reference, i.e. int&. (int& && collapses to int&, so the type of function parameter a is int&.) Then b is declared as a reference binding to a.
When being passed an rvalue, T is deduced a... |
62,480,429 | 62,480,585 | Is there a way to initialize all items in a 2d array with inputted dimensions without looping in C++? | Is there a way to initialize all items in a 2d array with console-inputted dimensions to a specified item without looping in C++?
For example, say I have two integers, x and y, and a 2d array called grid:
#include <iostream>
int main() {
int x, y;
std::cout << "Enter the dimensions of the array separated by a ... | Variable length arrays is not a standard C++ feature. Moreover even in C where vaeiable length arrays are included in the Standard nevertheless you may not initialize them in declaration.
In C++ you should use the standard class template std::vector.
For example
int x, y;
std::cout << "Enter the dimensions of the arra... |
62,480,700 | 62,480,776 | Casting from const char arr[] to char ** | So i have the following situation:
void func(char ** a)
{
// Do some stuff...
}
int main()
{
const char * arr[2] = { "foo" };
arr[1] = "bar";
// I want to Cast the arr from const char ** to char **
func(arr);
}
I think func(reinterpret_cast<char**>(arr)); is a way, but i don't know if it's the best ... | For starters this declaration
const char * arr[2] = "foo";
is incorrect. Arrays are aggregates and initializers of their elements shall be enclosed in braces.
const char * arr[2] = { "foo" };
Used in expressions the array (with rare exceptions) is converted to pointer of the type const char **.
This function
void fu... |
62,480,886 | 68,041,305 | How does std::async automatically join threads? | The c++ 11 std::async is a great thread abstraction, but every thread has to be joined so how does std::async join threads without exposing it to the user?
| std::async doesn't join threads. Instead, it initialized threads that are detatched from a thread object. These execution of these threads is independent of the process that created them and their resources are freed by the OS once they exit.
|
62,481,419 | 62,482,285 | How to remove groups from a folder view | Let's say the current Explorer folder view is grouped, and you want to remove the grouping. Is there a way to do that? IFolderView2::SetGroupBy doesn't accept a NULL or anything like that. I'm not sure if I'm overlooking some method or interface. Thank you for any help.
| You can call IFolderView2::SetGroupBy() with PKEY_Null to turn grouping off.
|
62,481,495 | 62,506,504 | Java JNA Linkedlist declaration | I need to access native C++ code .dll from Java application. native int function works well, but for Linkedlist Struct I cannot find any reference on the Internet how to declare the java interface
this C++ code
struct usb_relay_device_info
{
unsigned char *serial_number;
char *device_path;
usb_relay_device_... | You say "I cannot find any reference on the Internet how to declare the java interface" but there are plenty of references, including JNA's Overview, linked to the main project page.
There you will find that char * is a C String and should be mapped to Java's String.
The usb_relay_device_type mapping has to be referenc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.