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,946,319
62,946,885
Buffer Overflow Sample: Why is this code dangerous?
I'm fairly new to c and I'm reading a book regarding Software Vulnerabilities and I came across this buffer overflow sample, it mentions that this can cause a buffer overflow. I am trying to determine how this is the case. int handle_query_string(char *query_string) { struct keyval *qstring_values, *ent; char b...
A very big thing here is that you passed a pointer to a local variable to putenv. The buffer will cease to exist when handle_query_string returns. After that it will contain garbage variables. Note that what putenv does require that the string passed to it remains unchanged for the rest of the program. From the documen...
62,946,357
62,946,672
How to map string to a object member?
I have a class like this: class Test { double a; double b; double c; //there are quite a few variables here. } I want to do something like this: string input; Test test; if(input == "a") { return test.a; } else if(input == "b") { return test.b; } else if (input == "c") { return test.c; } Is there a way th...
If all of the members are the same type, then you can use a std::map of pointer-to-members, eg: class Test { double a; double b; double c; //there are quite a few variables here. } ... std::map<std::string, double Test::*> members; members["a"] = &Test::a; members["b"] = &Test::b; members["c"] = &Test::c; ......
62,946,538
62,946,600
Use of std::vector results in unknown output C++
I'm unable to figure out why the output I received isn't just "00110" but has other giberrish characters in it. Not sure what's wrong with my vector push_back.. It definitely makes sense to me. If I changed it to std::string implementation, it would give a correct output. But in this case, I would need to use vector fo...
You are filling the std::vector with char values and then constructing a std::string from the raw char data using the std::string constructor that takes a single const char* parameter. That constructor expects the char data to be null-terminated, but you are not pushing a null terminator into your vector, which is why...
62,946,658
62,946,813
how do I load a pure blackwhite image as qimage?
QImage qimg; qimg.load('blackWhite.jpg') This method changes pixels. I'm getting pixels like(1,1,1) or (3,3,3). But I expected only (0,0,0) and (255, 255, 255). I have also tried the following method: QImage image(bin.data, bin.cols, bin.rows, static_cast<int>(bin.step), QImage::Form...
You are loading a jpeg image, that format is a lossy compression format, meaning the pixels will be approximated but not necessary equal to the originals. So if you are in need to load the image from file, you should use a format like png, bmp, etc. (Any lossless format will do)
62,946,870
62,946,926
Function in source file already defined in another source file error
// file1.h #pragma once void public1(); // file1.cpp #include "file1.h" void privateFunc() {} void public1() {} // file2.h #pragma once void public2(); // file2.cpp #include "file2.h" void privateFunc() {} void public2() {} // main.cpp #include <iostream> #include "file1.h" #include "file2.h" int main() { std::...
To make a function private, you must declare it as static. Otherwise that symbol will be made available to the linker for resolving across multiple sources. static void privateFunc() {} Alternatively, you can declare it in an unnamed namespace: namespace { void privateFunc() {} } You can read more about unnamed ...
62,946,939
62,946,998
What is `#ifndef FUNCTIONS_H` in functions.h for?
In a header file functions.h, the first two statements are defining FUNCTIONS_H if not already defined. Can someone explain the reason for this action? #ifndef FUNCTIONS_H #define FUNCTIONS_H void print(); int factorial(int); int multiply(int, int); #endif
The article you linked isn't about Makefiles at all, it's about compiling multi source file code. Those are so called include guards. They prevent code from being included unnecessarily multiple times. If FUNCTIONS_H is not defined then include the content of the file and define this macro. Otherwise, it's defined so f...
62,947,107
62,969,865
Implementation of row by row matrices operation in OpenCL
I am a newbie in OpenCL, followed some basic tutorial of matrices operation in OpenCL, but I hardly understand on how to implement some loop operations in C++ into OpenCL. For a 2D array, the direct multiplication of matrix A x matrix A will be implemented as: __kernel void sum( __global const float *a, __global fl...
Firstly, the kernel in your example is not computing a standard matrix product. It appears to be doing a Hadamard product. However, a direct translation of the for loop code in CL may look something like this: __kernel void product(__global const float *Z, __global float *P) { const int size = get_global_size(0...
62,947,257
62,962,804
How to implement Geometry Shader in DirectX for a 3D object like Cylinder?
I need help on how to implement Geometry Shader on Cylinder and what is the value of [maxvertexcount()], and do we need to provide the values of vertices and indices in ModelClass?
The Geometry Shader stage of Direct3D is not intended for generating complete geometry like a cylinder, nor it is really designed for Tessellation. https://learn.microsoft.com/en-us/windows/uwp/graphics-concepts/geometry-shader-stage--gs- You can do some small amount of amplification, but generally the hardware impleme...
62,947,362
62,992,372
QT CQTDeployer Failed to run: config/controlScript.js
I'm trying to deploy an application,using the latest versions of Qt, OpenCV and CQTDeployer From QuasarApp, but when I run it I get this error: Project ERROR: Failed to run: config/controlScript.js -ts config/ru.ts I'm using the administrator account, already checked my permissions just in case, also checked the...
if you want create windows executable file from your application only with cqtdeployer then this is impossible because CQtDeployer it is utility for deploying for already exists application files. First one, you need to build your application for windows platform uses cross platform competitors. For example I am use th...
62,947,395
62,947,507
Segmentation Fault while searching a node in BST
I have written a search function in Binary Search Tree. While the function works properly and does what it should when the key is present in the tree but gives a segmentation fault when it isn't. Also is it right to print "yes" or "no" or should this function return a pointer to node? template<class T> class Node{ publ...
You are not checking if the node is null and hence are trying to access members (m_data, m_left, m_right) on a potentially empty node. Adding just a check is what you need. Use this: void searchkey(T data) { if (this->root == nullptr) { // <-- check if root is null in this function not std::cout << "E...
62,947,815
62,948,546
Change return value of a mock function when another mock function is called
Suppose I have the following mock enum class State { IDLE, BUSY, ERROR1, ERROR2 }; class MockActuator : public ActuatorInterface { public: MOCK_METHOD0(doAction, void()); MOCK_METHOD0(getState, State()); }; The module I am testing makes the assumption that if doAction() is called,...
You can see an example of how to do this in the docs. Following your classes. First a fake class that mimics the original: enum class State { IDLE, BUSY, ERROR1, ERROR2 }; class FakeActuator : public ActuatorInterface { public: virtual void doAction () { _state = BUSY; } virtual Sta...
62,948,401
62,948,692
fwrite/fread for complex datatype numbers giving zero as result
I've tried fwrite/fread for int, char and complex datatypes. They all worked well except complex. The read values of both the real and imaginary parts are all zero. Code: int main() { typedef complex<float> cf; FILE *stream; stream = fopen("fread.out", "w+t"); unsigned int n1 = 6; char *c1...
You've got a problem here: fread(&c2, sizeof(char), strlen(c2), stream); strlen(c2) gives you garbage, because c2 is not initialized. You should change c2 to c1 in this strlen function to make this example work. For production ready code one should choose a more complex serialization technique, probably one of the ex...
62,948,584
62,948,745
Why is this not printing the final output of sum?
Given an array of N integers. My task is to print the sum of all of the integers. Input: First line of input file contains a single integer T which denotes the number of test cases. For each test case, there will be two lines. First line contains N which denotes number of elements in an array, and second line contains ...
There is n in your final loop for(int i=0; i<n; i++){ cout<<sum[i]<<endl; } which is become 0 in while(n--) that is why it is not print anything
62,948,786
62,953,103
A better way to update C++ application for windows
I'm trying to develop C++ application for a client. So far, i have added the basic functionalities and it works as expected but i will likely to gradually grow the application in future (i.e. adding more feature to it) and the client will likely to update those feature in their app. Now my questions are the following: ...
@Vasilij way is the way to go. If you update only de DLL, how you application will know that there are new functions to call? You have to dynamically adapt your menus and so on. Just create an exe stub that runs the real application (may be in a subprocess it can kill) and update the whole app (not the stub) and DLLs w...
62,948,890
62,949,024
std::string difference in output when use c+=expression and c=c+expression
In the below code #include<iostream> #include<string> using namespace std; int main() { string a,c="!"; cin>>a; int l=a.size(); for(int i=0;i<l;i++) { c=c+"#"+a[i]; } cout<<c; } If I replace c=c+"#"+a[i] with c+="#"+a[i] i get unexpected output. Output in the second case is !b...
Given c+="#"+a[i];, "#"+a[i] is evaluated at first. "#" is of type const char[2] and could decay to pointer as const char*, a[i] is of type char which is an integral type, then "#"+a[i] just performs pointer arithmetic and won't concatenate strings as you expected. (And the result of pointer arithmetic might get out of...
62,949,341
62,950,697
What does 'if((mask | u)==u)' mean?
This is the recurrence relation of maximum sum subset problem. The complete code is: if ((mask | u) == u) dp[u] = max(max(0, dp[u ^ mask] + array[I], dp[u]); What does exactly mean the following if-statement? if((mask | u) == u) Thank you in advance!
Binary OR for binary values A, B evaluates as (1) if either A = 1 or B = 1. These bitwise operations extend to strings of binary digits. In C/C++, that's most commonly expressed as integral types. OR | A = 0 | A = 1 | ----------------------- B = 0 | (0) | (1) | ----------------------- B = 1 | (1) | (1) | ---...
62,949,757
62,949,964
Please help me to convert C++ algorithm code to Python
Can someone help me to fix the re-writing code from C++ to Python: Initial code is smth like this: vector<int> b = a; unordered_map<int,int> m; sort(a.begin(),a.end()); for(int i = 0; i < a.size(); i++){ m[a[i]] = i + 1; } vector<int> ans; for(int i = 0; i < b.size(); i++){ ...
you forgot to sort the input array, also when u sorrting array a and you have assigned the array a to b, then b automatically sorted and same as a, ssoo u need to create a deep copy of a or assign new list to b of a by appending all element def func(a): b =list(a) m ={} a.sort() ...
62,950,529
62,950,940
Return pair of vector iterators from a const method
I try to return a pair of vector iterators from a const method. pair<vector<double>::iterator, vector<double>::iterator> Matrix::GetColumn(int j) const { return pair<vector<double>::iterator, vector<double>::iterator>(values_.begin() + j * height_, val...
A const function can't mutate the state of the class, so it can only return a const_iterator. If it were to return a non-const iterator that would have the side effect of allowing the outer scope (calling code) to mutate the class's state. This would mean that the const function allowed modification of the class's stat...
62,950,689
62,951,273
what does error code "5" mean in winsock2?
I'm making a simple client-server application using winsock2 library, but I get a "5" error code when I try to open a socket, but the first error code in the documentation is "6". The thing is, I don't understand what causes the program to exit. int sockfd; if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) { per...
The error codes returned from WSAGetLastError are a subset of the error codes returned by GetLastError. Since GetLastError is a superset of all the errors returned by WSAGetLastError, calling GetLastError will yield the same error values as calling WSAGetLastError, plus any errors that are not Winsock-related. A 5 retu...
62,950,755
62,951,124
Shall using introduce a new member function or just an alias?
The following minimal example compiles fine with MSVC 17 but produces a compilation error on GCC 8.2. Which compiler is right? Is this code correct in C++17? #include <iostream> class A { public: A() = default; protected: void foo(int x) { std::cout << x << std::endl; } }; class B : private A { usi...
This is interesting. Per the current rules*, it appears that the intent is for foo to remain a member of the base, rather than introducing an actual member of B. That's despite the fact that overload resolution can now find the member in B: [namespace.udecl/15]: [Note: For the purpose of forming a set of candidates du...
62,950,767
62,951,877
getting ASCII tilemaps from a text file?
I'm trying to write a map reader for Nitemare 3D, each map block is 2 bytes(1 for the tile and 1 for the item on the tile) each map is 64*64 blocks, the map file file itself contains several maps, I've loaded the map and dumped it into a textfile but it comes out mangled Edit: for those seeking the answer, I forgot to ...
You are using Windows and you are not writing the file in binary mode. Each time you write a newline - \n - 0x0A - it gets converted to a CR + newline - \r\n - 0x0D then 0x0A. This adds an extra byte which makes the files not match up. To fix this, use std::ios::binary in the output stream as well.
62,950,900
62,951,054
Converting uint16_t * array to std::vector
I am having trouble converting a pointer array of uint16_t to std::vector<uint16_t> because of integer size issues. auto *arr = static_cast<const uint16_t *>(some_method.getArray()); std::vector<uint16_t> vec(arr, sizeof arr / sizeof arr[0]); In the first line I obtain a const uint16_t* array. In the s...
uint16_t* arr; is not an array, but is a pointer to array located in memory. The sizeof of this pointer is an integer containing an address, always equals 4. Or something else depending on architecture. But always the same constant, not the size of the array. cout<< sizeof(arr)<< endl; // the output is 4 And sizeof(ar...
62,951,201
62,951,285
QMessage::question(),,the dialog should be modal but it's not somtimes,the dialog was showed under the MainWindow
//QMessageBox dialog is modal by default,but the dialog was showed under the mainwindow int res = QMessageBox::question(NULL, tr("Question"), tr("Are you sure to delete this rules?"), QMessageBox::Yes | QMessageBox::Cancel); if (QMessageBox::Yes == res) { QStringList result; for (int i = selectedrowset.size() ...
A QDialog is modal to its parent(s), but are giving no parent at all, since you're using NULL. As shown in the documentation examples: int ret = QMessageBox::warning(this, tr("My Application"), tr("The document has been modified.\n" "Do you want to save y...
62,951,569
63,140,103
meson doesn't link library
I'm tring to a fix a meson build not picking up on a link library. The meson.build file has tz_dep = dependency( 'date', default_options : [ 'use_system_tzdb=true' ], fallback: [ 'date', 'tz_dep' ] ) # ... executable( 'waybar', src_files, dependencies: [ # ... tz_dep ], ...
i am wrinting an ebuild (gentoo package) for waybar right now and had the same issue you are describing. The solution is in your meson.build file, it specified the date dependency incomplete. This is the patch i apply, and then it works (i have no clue about meson and stuff, but this seems makes waybar compile): diff -...
62,951,629
62,952,217
Program akes only 1 alphabet input and exits while leaving remaining code unexecuted, why?
when user input a character and press enters to take next input, output window asks to press any key and exit, please help me out to get remaining code working, Here is the code char r, R; char c; int channels; int resedential() { // float channelscost = costperchannel*channels; // float Bill = channelscost+...
One thing I recognise, is that your if statement doesn't do what you think it does. Right now you aren't checking if c is equal to R. Fixed Code: if(c == r || c == R) { cout << "Enter Customer Type " << endl; cin >> c; } Also check that there are actual values in r and R. So it doesn't compare to a constant (c...
62,951,642
62,952,556
How to instantiate shared pointer with JNI to call java implementation
I'm new in JNI and C++. I have to call lib function with shared pointer. My code: JNIEXPORT jint JNICALL Java_com_test_NativeClient_subscribe(JNIEnv* env, jobject thisObj, jobject handler) { jclass handlerClass = env->GetObjectClass(handler); jmethodID starts = env->GetMethodID(handlerClass, "starts", "(I)V"); jmethodI...
All you need to do is store a global reference to the jobject and write some wrapper code: class JavaWrapperHandler : public some::lib::callback { jobject java_handler; public: JavaWrapperHandler(jobject handler) { JNIEnv *env = nullptr; vm->GetEnv(&env, JNI_VERSION_1_6); java_handler =...
62,952,504
62,952,575
push_back iterator in vector?
I tried to store the number 1,4,7...97 into a vector. if I use std::out << i; the for loop is working. but the push_back gives an error: base of member reference is a function perhaps you meant to call it with no arguments. i googled it and couldn't find a answer which helped me. The only thing I found was this: "In C+...
std::vector<int>rock(); is a .. function declaration. use std::vector<int>rock; or std::vector<int>rock{}; instead.
62,952,668
62,977,949
Unset define in cppcheck analyze from cmake generated command
I have project which i check with cppcheck 1.90, but i want to unset few defines, because it takes a lot of time to check with all defines. Example: tests.cpp: int main() { int x,y; #ifdef A x = 5; #else x = 10; #endif #ifdef B y = 5; #else y = 10; #endif #ifdef C y = 5*x; #else y = 10*x; #endif int ...
You have an option to edit the CMakeLists file only once and pass arguments as needed, To achieve this you should In the CMakeLists file add: set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} *hard_coded_flags*") Command line : When calling cmake from command line you add CMAKE_CXX_FLAGS = -UB=1 (or any other cppcheck flag),...
62,952,931
62,953,045
Array return function definition
I've a basic question I've got a fucntion which looks like this. Instead of void, I need to return an array (array of double with size 3 - array<double, 3>). How do I modify the function declaration and definition in Qt? .h void MainWindow:: fucntion(DATA_T *sample); // how to modify this .cpp void MainWindow:: fu...
#include <array> //.h class MainWindow { public: std::array<double,3> function(DATA_T *sample) const; } //.cpp std::array<double,3> MainWindow:: function(DATA_T *sample) const { return {sample->a1, sample->a2, sample->a3}; }
62,952,941
62,953,308
Calling detach() at the end of the thread
I have a working thread similar to the following code. In begin_work, it will check whether the working thread is executing before creating a new working thread. However, begin_work will never create the next working thread when the current thread is exited until I call end_work. I have tried to call detach at the end ...
I have tried to call detach at the end of the thread and it works fine There's data race in the access to worker - it's undefined behaviour. When begin_work tests worker.joinable(), do_work might be detaching it at the same time (the call to worker.detach()). You can instead detach the immediately when creating it: w...
62,953,385
62,953,645
Why do i get compile error while using template function
I have a base class. #include <string.h> class Channel { private: std::string stdstrName; public: Channel() : stdstrName("CHANNEL"){ } Channel(std::string name) : stdstrName(name){ } void PrintName() { std::cout << stdstrName << std::endl; } }; which is inherited by Position class. class PositionC...
In you GetChannel call, &chn argument is of type PositionChannel**, but the type of Director::GetChannel parameter is Channel**. These two types are not convertible; see, for example this question: Conversion of pointer-to-pointer between derived and base classes?. I am not sure what are your intentions since the code ...
62,953,642
62,953,968
How to create uniform interface to build for builders in builder patterns, if one of concrete builders take extra argument?
class Builder { public: virtual void Build(int a) = 0; }; class ConcreteBuilder1 : public Builder { public: void Build(int a); }; class ConcreteBuilder2 : public Builder { public: void Build(int a. struct A* a); }; So My question is how to design Build() method to take both parameters(int, struct* ...
Builder usually builds an object of another class. You may try something similar to this: class ToBuild { //some code here }; class Builder { public: virtual ToBuild * build() = 0; }; class ConcreteBuilder : public Builder { int _valA; int _valB; public: ToBuild * build() override { To...
62,953,736
63,018,274
libv8_libplatform.a: error adding symbols: Malformed archive
I have built and linked against v8 successfully on Windows and Mac, but with Ubuntu 18.04, I get the following error when I try to link against libv8_libplatform.a that was built: ../../lib/Linux/libv8_libplatform.a: error adding symbols: Malformed archive clang: error: linker command failed with exit code 1 (use -v to...
The error still exists, but I found that when building on Ubuntu, you seemingly do not need to link against libv8_libplatform.a in order to build, so the error can be avoided.
62,954,221
62,955,285
C++ print chrono::time_point<chrono::high_resolution_clock> to be readable
I have the number of nanoseconds since Epoch and I'd like to print this to be readable. The examples I found online printing time_point were using system_clock and then converting to a std::time_t. However, I am using high_resolution_clock (because of the nanoseconds), hence struggling to understand how I can print thi...
high_resolution_clock does not have a portable epoch. It might be 1970. It might be whenever your device booted up. Thus when printing its time_point, the best that can be done is to print the underlying duration. system_clock can represent nanoseconds even if system_clock::time_point does not. The trick is to use ...
62,954,286
62,955,752
set a flag in int variable from different context on bare metal controller
For avr 8 bit micro controller a single bit ( flag ) must be set or cleared in some 8 bit integer variable. This set/clear function can be called from normal context ( main ) and also from interrupt handler ( Isr() ). As this, the variable must be made volatile to prevent it from reordering or keeping it somewhere in r...
The rationale is that compound assignments or pre-post incrementations or decrementations are not atomic even on a volatile variable, while a programmer could see it as a single operation. Moreover, the standard says that E1 op= E2 is the same as E1 = E1 op E2 except that E1 is evaluated only once. That means that non ...
62,954,340
62,966,443
Optimal Binary Search Tree for Successful and Unsuccessful Search
I am studying Dynamic Programming Algorithms for optimizing Binary Search Tree in C++ language. I have built my own program but I do not know whether my program finds out the correct answer or not. I have made an attempt to find sample code on the internet but I just found sample one for Successful search, therefore, I...
From what I can see the 2 algorithms differ when calculating the cost of the new candidate sub-root E_{i,j} = E_{i,r-1} + E_{r+1,j} + W_{i,j} Your code is not adding the left sub-tree value when k = 1 and not adding the right sub-tree value when k=j. temp = 0; if (k > i) temp += Cost[i][k - ...
62,954,634
62,956,562
Tensorflow 2.3 unresolved external symbols in machine-generated files when building C++ project on Windows
I was wondering if anyone has had success linking against Tensorflow 2.3 DLL on Windows. I am trying to integrate some tensorflow functionality in a tiny VS2019 test project to see if I can use tensorflow C++ API at all. I managed to build tensorflow with MSVC 14.16.27023 and followed the instructions given in the off...
The folder containing dynamic library tensorflow_cc.dll and import library tensorflow_cc.dll.if.lib has also two files: tensorflow_filtered_def_file.def : contains import symbols tensorflow_cc.dll-2.params : has all built libraries now if you have some unresolved symbols when building your app, all you have to do is ...
62,954,662
62,954,883
Search Function Implementation in Binary Search Tree
I have implemented a function "searchkey" in order to return a node in a binary search tree if the key is present but it is returning the root node. I have added a minimal reproducible code. While the same iterative method works. Also which would be the better way to implement this recursive or iterative. template<clas...
It seems you are missing a few return statements in your search function. Also, the test for data == node->m_data isn't needed. The fallback return at the end of the function means that a match is found if you return when doing the recursive calls. Node<T>* searchkey(T data, Node<T> *node) { if (node == nullptr) { ...
62,954,701
62,955,626
QT C++ Project (Creating Login with XML)
I have question about my internship project. They want me to create a basic Login page(ID, Password). I create a XML file for Username and Password. The program should check the XML file for username and password*. If they are correct it will direct to a second window. I'm stuck on processing XML file for username and ...
As @JarMan said, I would recommend the QXmlStreamReader. You can fill it with a file (QIODevice), QString, QByteArray, etc... Parsing a value could e.g. look like that xml.attributes().value( attribute ).toString(); if attribute is a QString and xml is the QXmlStreamReader. See the doc https://doc.qt.io/qt-5/qxmlstrea...
62,955,806
62,956,123
What is the Starting address of the stack Memory?
Hi i had one of the interview question they were asked what is the starting address of the stack memory. Please i don't know the address can you please help how to find the starting address of the stack memory. Thanks & Regards, Gunasekaran J
There's no guarantees in C++ that there even is a stack. Even if, in practice, there's one, the place it is in memory varies by compiler implementation, platform, environment, etc... There's OS features like address randomization that will even force the address to change from run to run. You can't try to determine it ...
62,956,034
62,956,447
Recursive algorithm complexity analysis
I am trying to analyze the complexity of this algorithm but I am not sure if its recurrence equation is T (n / 2) + 2n, could you help me? size of v > 100 bool pareado(int v[], int left, int right) { bool b; if (left >= right) b = true; else { int m = (left + right) / 2; bool baux = ...
Your pareado function has complexity O(n) [ for n = right-left ] before recursing. Given that on each recursion step you partition your input range, and handle them separately, you still have to iterate over the entire range once (for any iteration depth) in the worst case. How many recursion depths are there? In the w...
62,956,147
67,226,725
Encoding animated gif with WIC Imaging Component -> Infinite loop
I have a std::vector<> of IWICBitmapSource and trying to create an animated gif: void SaveGif() { CComPtr<IWICBitmapEncoder> wicBitmapEncoder; auto hr = fact->CreateEncoder( GUID_ContainerFormatGif, nullptr, // No preferred codec vendor. &wicBitmapEncoder )...
Using the links in Simon Mourier's comment, I came up with this snippet and it seems to be working (for my single testcase): CComPtr<IWICMetadataQueryWriter> meta; // Get a metadata writer wicBitmapEncoder->GetMetadataQueryWriter(&meta); PROPVARIANT app = { 0 }; PROPVARIANT data = { 0 }; const char *appext = "NETSCAPE2...
62,957,115
62,957,642
Error: no match for 'operator+' (operand types are 'std::__cxx11::list<int>' and 'int')|
I'm trying to take an even integer array and odd integer list, and then try to merge them in a vector, using the merge algorithm available in STL of C++. The task requires specifically to use the merge algorithm, and I'm getting stuck in error at line 43 , right of which I've commented that that's the error point. #inc...
You can't add something to a std::list like you can do with arrays. Also it's better to be explicit about iterators and use std::end to get the past-the-end-iterator, since you want to use the whole array anyway. Also std::merge() expects iterators but the last parameter is vec1, which is a std::vector. The correct ver...
62,957,225
62,957,274
C++ find first element in vector satisfying a condition using the std library
I have a vector containing objects, and each object has a method that returns a boolean. I would like to find the first element whose method returns true. I know I could simply iterate over the vector using a for loop, but I'm looking for a solution that uses the std library. Googling I found nothing, just the find and...
What you are looking for is std::ranges::find_if and you'll use it like auto iterator = std::ranges::find_if(vector, lambda); This does require C++20 support. If you don't have that, then use the plain old std::find_if like auto iterator = std::find_if(vector.begin(), vector.end(), lambda);
62,957,466
62,957,579
unable to replace raw loop in function template
A very fundamental problem while I am learning templates. I am writing a function template returns the sum of array elements. Here is my snippets. #include <iostream> template<class T> T sum(T *pArr, int length) { T ret = pArr[0]; for (int i = 1; i < length; i ++) ret += pArr[i]; return ret; }...
If you pass array by reference (or object as std::span), you might use for range: template <class T, std::size_t N> T sum(const T (&arr)[N]) { T ret{}; for (auto& e : arr) { ret += e; } return ret; } or template <class T, std::size_t Size> auto sum(const std::span<T, Size>& arr) { std::rem...
62,957,572
62,957,652
CppCoreGuidelines: What are hot int copies?
I've been reading CppCoreGuidelines F.15 and I don't understand the following sentences from the table of parameter passing: "Cheap" ≈ a handful of hot int copies "Moderate cost" ≈ memcpy hot/contiguous ~1KB and no allocation What does "hot int copy" mean?
"Hot" in this case likely refers to the likelihood of being cached. A particular piece of memory is "cold" if it is likely not in the cache, due to not having been touched recently within this thread of execution. Conversely, a piece of memory is "hot" if it likely has been touched recently, or is contiguous with memor...
62,957,833
62,957,925
Why for loop is not stopping?
I have a for loop in my program that is not stopping: vector<int> v; int k = 1; v.push_back(1); for(int i=v.size()-1; i>=(v.size()-k); i--){ cout << i << " " << v.size() - k << endl; } When I execute the above program, it keeps running inside the for loop. The output of the for loop is as below: 0 0 -1 0 -2 0 -3 ...
You are checking if i is greater than or equal to zero. But since size() returns an unsigned, you are comparing i to an unsigned zero. To do the comparison, i is converted to the same unsigned type that size() returns. Well, every unsigned integral value is greater than or equal to zero. So whatever value i has, the co...
62,958,060
62,958,118
Find element in vector of pair and output c++
I have a vector of pair: typedef pair<string,int> is; vector<is> v; I push some values to the vector. v.push_back(make_pair("One",1)); v.push_back(make_pair("Two",2)); v.push_back(make_pair("Three",3)); v.push_back(make_pair("Four",4)); I need to ask the user to input a name and search the vector , find that name and...
std::binary_search will only give you a bool result, so it doesn't give sufficient information to get the value of the pair you're looking for. The idiomatic way to do this is with std::lower_bound, which returns an iterator to the pair you're looking for, like this: if (auto i = std::lower_bound(v.begin(), v.end(), ...
62,958,243
62,999,768
C++ Unexpected behavior with istream, getline, binary file, regex and strings
I'm working with a file that combines text and binary formats (and sometimes just plain text). So I decided to open the file as binary and give it a try. However, I'm getting unexpected behaviors when I later use regular expressions (the kind of issues that indicate memory corruption): (Edited to have a minimum example...
There are two things to consider: In text mode, \n is handled as the native EOL combination (so it would be \r\n on Windows). In binary mode no such thing is done, so \n is always the newline feed character and nothing else. You ask to read as much text as possible until \n, which on Windows leaves you with \r at the e...
62,958,394
62,958,687
Using cin with arrays
I'm trying to get user input for two arrays. I'm getting the error no operator matches these operands. Why isn't my cin function working? #include <iostream> using namespace std; int main() { string canadates[5]; int votes[5]; double percent[5]; int i; while (i <= 5) { cin<< canadates << vot...
There's quite a few issues with your code. First, cin uses different operator than cout. cin >> canadates >> votes; Second, also part of the compiler error - you cannot read into whole array. You need into read into single element of an array. How do you access single array element? cin >> canadates[i] >> votes[i]; T...
62,958,456
62,958,562
Is it possible to return the current object if it is an r-value reference?
I have recently learned about r-value references. In order to more thoroughly experiment I decided to write a simple DenseMatrix class. My question is is it possible to write any function ( Transpose for this example ) such that for auto A = B.Transpose() separate matrix is returned, but for auto A = (B + C).Transpose(...
Yes, you can overload the Transpose member function on the ref-qualification of the object it's being called on: class DenseMatrix { DenseMatrix Transpose() const & { // #1 called on l-values auto copy = *this; // transpose copy return copy; } DenseMatrix&& Transpose() && { // #2 called on r-v...
62,958,884
62,961,376
Getting around the 8192 byte var limit in NSIS?
I'm supplying a c++ .dll to a user who is writing an installer via an NSIS script. Using System.dll, the user can call my .dll as such: System::Call 'my.dll::GetJson(v) t .r0' DetailPrint $0 The return value of GetJson() gets stored in $0. This is all working correctly, though GetJson() may return a json blob whose le...
If the user needs to edit a very long string you basically have two options: Use the system plug-in to fill a text field on a nsDialogs custom page. You can't use the registers to store the string, you need to use ...func()p.r0 to get the raw address of the string from your plug-in and use Sendmesage to fill the text f...
62,959,007
62,959,100
size() and capacity() of c++ vectors
I've just started with C++'s standard library and the first thing I started with is std::vector. I've a bit of confusion with the capacity() in a vector. I know that after each push_back(), the capacity of the vector changes in exponential powers, but in the below output the capacity remains the same value sometimes, ...
I know that after each push_back() the capacity of the vector changes in exponential powers but in the above OUTPUT the capacity is still remaining same sometimes even after insertion. When capacity is greater than the size after insertion, the capacity doesn't need to, and is guaranteed not to change. This strategy ...
62,959,225
62,960,116
Inserting std::unique_ptr into std::set
What is the best way to insert a std::unique_ptr made with std::make_unique() into a std::set? Both insert() and emplace() work, but which one is better?
The way unique_ptr was implemented ( move-only, not copy ) it prevents that this scenario you are concerned. But create others: s.insert( std::make_unique<X>(1) ); // SAFE auto p2 = std::make_unique<X>(2); s.insert( std::move(p2) ); // also safe auto p3 = std::make_unique<X>(3); //s.insert( p3 ); // unsafe, compiler...
62,959,262
62,959,336
Are basic mathematical functions optimized?
Does a function such as int GetSize(int type){ switch(type){ case 0: return 15 * 16 + 17 / 2; case 1: return 25 * 6 + 7 / 42; } } get optimized? I have a function such as this that will be called 100s of times per second but the return values for each case are always the same. I...
Does a function such as [...] get optimized? Yes, heavily:
62,959,452
62,960,180
How to make a HEAD request in c++ using libevent
I want to use the Libevent Library to make an HTTP HEAD request to a website just to get its status code. How would I go about doing that? I've been looking at this: https://github.com/libevent/libevent/blob/master/sample/https-client.c, but I don't know how to make a HEAD request.
Per the documentation, you can use EVHTTP_REQ_HEAD instead of EVHTTP_REQ_GET when calling evhttp_make_request().
62,959,570
62,959,659
Making shared_ptr from the raw pointer of another shared_ptr
Say, I have a shared_ptr<A> ptrFirst, that is initialized and is pointing to some object in memory. Now, I define a new shared_ptr like this: shared_ptr<A> ptrSecond = make_shared<A>(ptrFirst.get()); I know that I could use simple assignment to prevent any issues. But I wonder if I define ptrSecond this way, will I ha...
Unless you have a constructor that takes A* as only argument, your line won't event compile. If you do have a constructor A::A(A*), then make_shared will create a new object - this is fine. If you would use std::shared_ptr constructor instead: std::shared_ptr<A> ptrSecond = std::shared_ptr<A>(ptrFirst.get()); then it ...
62,959,720
62,960,142
Installing libzippp library with cmake not working
Trying to install libzippp library in this project is not working for some reason, here is my project's CMakeLists.txt: CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(startProject) set(Leptonica_DIR /Users/alejandrocamba/Documents/leptonica/build) find_package(OpenCV REQUIRED) find_package(Leptonica REQ...
Need more p: the proper target name for link with is libzippp::libzippp. The project's README wrongly suggests to use libzipp::libzipp.
62,959,857
62,959,983
C++, function that can take either ifstream or istringstream
I have a function do_something that reads unsigned characters from a stream. The stream can be created from a file given the file name. Or it can be created from the given string by considering it as data. I would like to reuse the function in both cases. The code below gives an error in the second case: "error C2664: ...
Your code is experiencing something called a vexing parse. The line: std::basic_istringstream<unsigned char> str(std::basic_string<unsigned char>(in)); is interpreted as a function declaration. str here is a function that returns a std::istringstream and takes as its parameter a variable of type std::string called in....
62,960,082
62,960,149
C++ STD::List: Trouble Iterating Through List
When running my code, it compiles fine, but I don't understand why it isn't iterating and printing out my list. I have a sub class Games and super classes: play_ball and statistics. The goal is to have the player play through the games, tracking how many attempts it takes them to win. At the end of each play, it will k...
The argument 'sts' is being passed in by value instead of by reference. When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller's variable. When a parameter is passed by value, the call...
62,960,176
62,960,427
How to work with integer limits in C++. The number "-91283472332" is out of the range of a 32-bit signed integer
**Some problems in code. I must convert a string to an integer. But have limited, 32-bit signed integer. I used the `stoi() function, and did not remember about spaces in string, however using big numbers are impossible. ** My code: #include <iostream> #include <string> #include <limits.h> using namespace std; int myA...
Get the help of stoll() which converts a std::string object into long long type integer: void printLongNumber(std::string str) { auto number = stoll(str); std::cout << number << std::endl; }
62,960,281
62,980,602
Creating a common slot for multiple instances of QDoubleSpinBox
I am trying to create a custom slot that can receive an int and pass it as a double to QDoubleSpinBox.SetValue(double); But I have a bunch of spinboxes in my UI so I would like to have a single slot that can have a DoubleSpinBox pointer as a parameter like so: void MainWindow::ConvertSetSpinBoxValue(int value, QDoubleS...
As the others pointed out using the (new) Qt5 signals and slots (using function pointers and lambda functions) should solve your problem. Different methods exist: Using lambda function: connect(ui->horizontalSlider, &QSlider::valueChanged, this /*context*/, [this] (int value) {ui->doubleSpinBox->setValue(value);}); N...
62,960,540
62,964,292
converting an RGB image to 1d Array using opencv
I am trying to read an RGB image and convert it to 1D array. When printing the values, I understand that the logic I have written for conversion is not correct. Can someone help me with this please? Also, when I am trying to define image_array, it is giving me an error. Expression must have constant value. I have pos...
If the array does not have a fixed-size, like in your example, you should use dynamically allocated array. Declaring uchar* image_array = new uchar[img_rev.total() * img_rev.channels()] can be a solution but you need to delete it manually to free memory when it is used no more. In order not to deal with keeping track o...
62,960,736
62,960,791
vector of references and ability to resize
The following code is similar to this answer Why can't I make a vector of references? class A { public: A(int x) : _x(x) { std::cout << "A : ctor\n"; } void func() { std::cout << "I am func \n"; } int getval() { return _x; } private: int _x; }; ...
error: no matching function for call to ‘std::reference_wrapper::reference_wrapper()’ That says wrapper's default constructor was not found. It does not have one because references must always be initialized. std::vector<T>::resize uses this default constructor to initialize new elements. Think about it, what should th...
62,960,784
62,961,158
Getting the average of numbers with anticipating wrong user inputs
#include <iostream> #include <string> using namespace std; int main(void) { float sum, counter = 0, num; string d; bool t = true; while (t) { cin >> num; sum = sum + num; counter += 1; while (cin.fail()) { cin.clear(); cin.ignore(); ...
If you want to handle bad input, I suggest reading the inputs into a string, and then further process the string. That will make the loop itself much simpler: std::string d; float sum = 0; int counter = 0; while (std::cin >> d) { if (d == "done") { break; } try { sum += std::stof(d); ...
62,960,998
62,961,091
Why my program does not do a proper diagonal difference (C++)?
for some reason my program does not give me the correct diagonal difference.for example in the input of (11 2 4) (4 5 6) (10 8 -12) its supposed to give me 15 by adding (11+5+(-12)) and (4+5+10) then doing abs difference of two, but gives me 6 for some reason. Here is my function for the code: int diagonalDifference(ve...
Well, you are accessing every element of the matrix, you only need the diagonals. So, from here, in spite of having a few more mistakes, they do not matter much. This is probably the code you want (I haven't done any debugging). I hope it is right. int diagonalDifference(const vector<vector<int>>& M) { const int ...
62,961,148
62,961,321
Is it always good for performance to create a thread?
I've recently started trying to use threads with std::thread, and I was wondering if there are any downsides to using threads (specifically, in c++). Are there situations where adding more threads would decrease performance? For example, if I'm creating multiple new threads that are meant to each run a server object li...
Creating a thread can be expensive. If you have very small amounts of work to do, it might not be worth it. This article's measurements show that creating a thread may take ~milliseconds. Threads are an abstraction over CPU cores, and while you can basically create as many threads as you want, the number of available...
62,961,457
62,961,539
C++ while switch case make a loop inside default
I have a problem about using while switch cases ı have a code like this and I wanted to see if the user wrote other than 1,2,3,4,5, then I wanted to just print "Please enter option" and asked for new input which means I don't want to go back to the choice menu, I know it looks like quite easy and I tried to use a bool...
while (true) I can see that you are not using brackets after the while loop, so how are you expecting it to loop properly. It will only execute the immediate next line of code if there are no brackets. So, encapsulate your code inside of the while(true) Apart from that, you are never breaking from the while loop, ...
62,962,503
62,962,835
Container iterator operating on component's attribute
Having following class class Foo { int element1; bool element2; Bar *ptr_element; } I've put it in vector and I'd like to iterate over it using iterator. std::vector<Foo*> fooVec; //... What I'd need to do to have iterator return directly Bar *ptr_elemnt attribute of an instance instead of instance of Foo? A...
There is no way to make a std::vector<Foo*>::iterator return anything other than a Foo* when dereferenced. However, you can wrap the iterator inside another type that exposes what you need, eg: class Foo { public: int element1; bool element2; Bar *ptr_element; }; struct FooAdapter { using iterator = s...
62,962,713
62,963,131
How to check if a class if explicitly constructible from multiple arguments?
Is there a good way to evaluate an explicit constructor exists for multiple arguments? This is very similar to this question, except that std::is_convertible won't work for this case because we have multiple arguments being passed to the constructor we're testing for. For example: #include <iostream> #include <type_tra...
Unfortunately, I believe you'd have to make your own version where you pass {args} to the pretend function instead of arg (live example): // Can we call this function with {args}? template<typename To> void conversion_test(To); // If passing {From...} as an arg to conversion_test<To> fails, return false. template<type...
62,962,969
62,964,322
Doesn't using directives work with c++20 concepts?
Does using directives not work with concepts? why? The example below doesn't work and I get a compiler error saying that it expected a type. #include <concepts> namespace A::X { struct BaseA {}; template < typename AType > concept DerivedFromA = std::derived_from < AType, BaseA >; } namespace A { using ...
Does using directives not work with concepts? why? Because the way you're employing using declares a type alias. And concepts are not type templates. What you intend to do is to make a name from one namespace available in a different one. That looks like this: namespace A { using X::DerivedFromA; } This works on a...
62,963,256
62,963,321
class with external linkage has base with internal linkage
#include "X.h" namespace { class B { /* ... */ }; } class D : public B { X myx; D(); }; D::D() { /* ... */ } D (with external linkage) derives from B (with internal linkage). (Real scenario: B is the base of all test classes, and D is a test for X. The leaf classes are friends of the classes they are designed ...
The question you're asking is about the implementation details of a toolchain. The Standard does not prescribe that compilers "emit symbols", but merely that the implementation has some means of resolving external entity references during the final phase of translation. Since it's not possible for any other translation...
62,963,278
63,003,842
Insufficient permission to read system memory
I am using a code to scan a the program memory, I use a code to scan the notepad.exe and the program can scan without any problem, but when I want to scan some system process (ex: dwm.exe, Registry) I don't have enough permission, the program can't scan, what can I do? I already tried to run as an administrator. char* ...
Important system processes are protected, first thing you should do is elevate permissions with SeDebugPrivelage: bool SetDebugPrivilege() { HANDLE hToken{ nullptr }; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken)) return false; TOKEN_PRIVILEGES TokenPriv...
62,963,592
62,963,685
error: cannot convert ‘std::__cxx11::basic_string<char>::iterator’
I am writing a program to check if an input phrase is a palindrome. Compiled using Xcode on MacBook Pro works fine. Complied on zyBooks website returns an error. How can update my code to address this issue? My code is: #include <iostream> #include <string> #include <cctype> using namespace std; int main() { strin...
The remove() function without including the algorithm.h library works to delete the existing files in the system. The function signature of this function looks like: int remove(const char *_Filename) In the other hand, after using algorithm.h, you could now use the remove() for iterators: _FIter remove<_FIter, _Tp>(_F...
62,963,632
62,986,308
Member Valiable losing value on Tick (c++)
I'm currently with a problem when trying to use tick to decide if I should or not do something based on a member variable boolean value. Currently, I have a BindAction on my Player Character class, that when a given key is pressed, set the value of my member variable bTriggerPulled to True: void AShooterCharacter::Setu...
So, I discover what was the problem, it's a silly one, but I will swallow my pride and share here anyways. My class AShooterCharacter is inherited in a blueprint, and that blueprint is placed N times on my level, the enemies. When I was debugging, my IDE don't necessarily differed from the instances of that specific cl...
62,963,907
62,963,920
0-1 Knapsack C++ not returning proper value
#include<bits/stdc++.h> using namespace std; int knapsackTab(int val[],int wt[], int W, int n) { int dp[n+1][W+1]; for(int i=0;i<n+1;i++){ for(int j=0;j<W+1;j++){ if(i==0||j==0) dp[i][j]=0; if(wt[i-1]<=j) dp[i][j] = max(val[i-1] + dp[i-1][j-wt[i...
You forgot else after the i==0||j==0 check, so out-of-range values are read. if(i==0||j==0) dp[i][j]=0; else if(wt[i-1]<=j) // add "else" here dp[i][j] = max(val[i-1] + dp[i-1][j-wt[i-1]],dp[i-1][j]); else dp[i][j] = dp[i-1][j];
62,963,984
62,969,775
Gmock how to mock a one line function which doesn't take parameters?
So I have a class which is calling method from other class, but eventually it will return a string or so This is my class: Person.cpp Person::Person(){} std::string Person::getName(void) { return namespaceX::namespaceY::StringVal; } This is my mock / test class: class MockPerson : public Person{ public: typede...
First, compiling your example with g++ gives me the following error: error: 'using element_type = class testing::StrictMock<Person>' {aka 'class testing::StrictMock<Person>'} has no member named 'gmock_getName' This can be fixed by passing MockPerson as the template parameter for StrictMock, instead of passing Person:...
62,964,064
62,964,082
How to append string from a loop in C++?
I am new. I am learning C++. I am trying to append specific item form a string to another string using for loop. But I am unable to do it. I found nothing helpful searching on the internet. My code: #include <bits/stdc++.h> using namespace std; int main() { string statement, newStatement = ""; cin >> statement...
You can use std::string::push_back to append one character to a string. #include <bits/stdc++.h> using namespace std; int main() { string statement, newStatement = ""; cin >> statement; for (int i = 0; i < statement.length(); i = i + 2) { newStatement.push_back(statement[i]); // use push_back i...
62,964,370
62,964,469
Reference to a dictionary value to reduce lookups
If I an have unordered_map std::unordered_map<int, myClass> dic; and I want to do a lot of assignments to a given element, would it be a good practice to use a reference to the object, so that I just search the dictionary once?. That is: myClass& ref= dic[mykey]; ref.myval0=0; ref.myval1=0; ref.myval2=0; ref.myval3=0; ...
A better idiom would be to use iterators: if (auto const it = dic.find(mykey); it != dic.end()) { it->second.myval1 = 0; it->second.myval1 = 1; // ... } This has the benefit that you add a check for whether the value actually exists. In case you actually want to insert a new key-value pair, unordered_map has an ...
62,964,643
62,965,308
Checking the size of hashes in C++
As one would do with a blockchain, I want to check if a hash satisfies a size requirement. This is fairly easy in Python, but I am having some difficulty implementing the same system in C++. To be clear about what I am after, this first example is the python implementation: difficulty = 25 hash = "0000004fbbc4261dc66...
Your basic need is to compute how many zero bits exist before the first non-zero bit. This has nothing to do with multi-precision really, it can be reformulated into a simple counting problem: // takes hexadecimal ASCII [0-9a-fA-F] inline int count_zeros(char ch) { if (ch < '1') return 4; if (ch < '2') return ...
62,964,807
62,965,397
calling constructor of a class in another class
I have two classes named info and i2 in qt. info is a c++ class and i2 is a Qt designer from class. I want to use i2 as an environment for testing my info class. I included info.h in the header of i2.my info class has two constructor like below: info(); info(const void *ip, const char* pw, const void *hostName); now...
Use a braced-init-list: info inf{"172.30.6.91", "mypw", "heydari.f"};
62,964,864
62,964,915
How to make project from github
I am downloading a library from the github ///////////////////// https://github.com/ossrs/srs /////////////////////////// The steps which i follow are Create a folder Run power shell and point to the folder Git clone the source The issue i am facing is the Make command in the step 2 of installation The power shell do...
Make is an UNIX command for the UNIX make utility. To compile it on Windows, you can use Visual Studio, by running the Developer Command Prompt for VS, and using Microsoft's version of this tool - nmake: nmake -f Makefile However, it looks like the configure script in /src of the package can only run on UNIX, so if you...
62,965,040
62,965,218
When I made a do/while loop in C++ in order to allow a player to play the game again, the game only loops once, how do I fix this?
char playAgain; do { srand(static_cast<unsigned int>(time(0))); random_shuffle(words.begin(), words.end()); const string THE_WORD = words[0]; //word to guess int wrong = 0; //number of incorrect guesses string soFar(THE_WORD.size(), '-'); //word guessed so far string used ...
The only way I see that the loop won't work is if you have characters in the buffer that you haven't read yet, so clear the line with cin.ignore(). You need to #include <limits> for this to work: ... cout << "\nPlay again? < Y , N >\n"; cin.ignore(numeric_limits<streamsize>::max(), '\n'); if(!(cin >> pl...
62,965,594
62,965,620
Copying dynamically allocated array in C++
I am writing a DynamicArray class and got stuck with resize() function. It works as expected when I remove line delete[] temp. But when I don't it seems copying only the last 2 elements. Am I missing something here?? #include <iostream> #include <initializer_list> template <typename T, int N> class DynamicArray { pr...
You are deleteing the memory you just allocated. Resize should work by allocating new memory copying elements from the old memory and then deleteing the old. Something like this void resize() { T *temp = new T[m_capacity / sizeof(T) * GROWTH_FACTOR]; std::copy(m_array, m_capacity / sizeof(T) + m_array, temp); ...
62,965,694
62,969,898
How to construct tuple types of class template based on template parameter pack of sizt_t... Ints?
In the context of c++17, how to construct the following tuple types (how to implement TypeMaker)? template <size_t M, size_t N> class A { // ... } template <size_t M> class B { // ... } template <size_t... Ints> struct TypeMaker { // here is the question // using typeA = ... // using typeB = ... } typeA and ty...
Something along these lines, perhaps: template <size_t... Ints> struct TypeMaker { private: using Numbers = std::tuple<std::integral_constant<size_t, Ints>...>; template <size_t N> static constexpr size_t Number = std::tuple_element_t<N, Numbers>::value; template <size_t... Indexes> static std::tuple<A<Numbe...
62,965,739
62,965,810
The benefit of declaring the capacity of an array as a variable of it's own in a class?
I came across these codes and explanation about how we should create a class in C++. The example class was about a bag, with an array for it to keep integers and a variable to count how many integers were in it : class Bag { public: //... private: int data[20]; size_t count; //... } then it gave another code ...
As shown, it's not really more flexible. The benefit would come if you used CAPACITY for a second purpose, such as defining a the range of a loop. Then if you changed CAPACITY from, say, 20 to 30 you'd only need to make the change in one place. That said, it would generally be much more flexible (at a very slight perfo...
62,966,423
62,966,501
Returning by const value and assigning to a non const variable compiles
I don't understand why the following code is allowed to use the non const version of foo. I would like to forbid a const Array variable to provide a non const ArrayView. #include <iostream> struct ArrayView { ArrayView() = default; ArrayView(const ArrayView&) = delete; ArrayView(ArrayView&&) = delete; ...
The rule of type deduction for auto is same as template argument deduction; view is declared as non-reference and the const part of the return value of createView is ignored. As the result the type of view is ArrayView, not const ArrayView. On the other hand, if you call foo on the return value directly, the const vers...
62,966,597
62,966,900
Why I am getting error no match for ">>" operator?
error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'std::vector<char>') #include <bits/stdc++.h> using namespace std; int main() { int n; vector<char> b[n], g[n]; cin >> n; for (int i = 0; i < n; i++) cin >> b[i]; for (int j = 0; j < n; j...
You seem to be confused between [n] and (n). Using vector<char> b[n] tries to create an array of vectors while you most probably want a vector<char> having n elements. Also you are passing uninitialized n to vector<char> constructor (wait, it wasn't a constructor in your case, but if you just made a fix keeping my abov...
62,966,603
62,968,924
C++ Constructor not been called
I was pretty sure the calling of B(A()) will call the defined constructor of B in my code. But I was surprised to find out that it didn't call to my constructor B and of course didn't print "Constructor B". So, to which constructor this code is calling (what is the signature of this constructor that it's calling to)? s...
It doesn't construct an object with type B as you expected, then no constructor is called. When declaring variables we can add (unnecessary) parentheses around the variable name, i.e. int (a); has the same effect as int a;. Similarly, B(A()); is same as B A();, which declares a function named A, which takes no paramete...
62,966,629
62,974,997
No speed up with openmp for emplace_back a vector in a loop
I'm trying to emplace_back a vector in a loop with openmp. I took my inspiration from this post : C++ OpenMP Parallel For Loop - Alternatives to std::vector. So I write a test code : // Example program #include <iostream> #include <string> #include <vector> #include <random> #include <chrono> #include <omp.h> int mai...
The current code is ill-formed regarding the documentation (since the parallelized code contains mostly-implicit dependencies). As a result, an OpenMP implementation is free to generate a fast but completely "wrong" program or a slow "correct" one. To get a correct implementation and a not-too-bad speedup using OpenMP,...
62,966,845
62,966,876
Set Iterators in C++
Can iterator be subtracted for set stl in c++? Like it is possible in vector... int32_t main() { set<int> s = {1, 3, 0, 23}; vector<int> v = {1, 3, 0, 23}; int vind = find(v.begin(), v.end(), 1) - v.begin(); //This is ok with no error int sind = find(s.begin(), s.end(), 1) - s.begin(); //But this giv...
The iterator of std::set is BidirectionalIterator, which doesn't support operator- between iterators. (The iterator of std::vector is RandomAccessIterator, which supports that.) You can use std::distance instead. (Note that the complexity is linear for InputIterator including BidirectionalIterator.) int sind = std::dis...
62,966,985
62,974,855
Multiple Eigen::Matrix initializations with OMP: segmentation faults
In the following minimal example, I am trying to create a few Eigen::Matrix in a for loop parallelized by OMP. Each matrix is contained within the loop, so there is no data sharing or race conditions among the threads. The code works perfectly when number of threads equals one, otherwise I get a segmentation fault. Wha...
The problem is coming from fixed sizes and the limited stack size. Indeed, Matrix<double,SIZE,SIZE> is allocated on the stack and since SIZE is quite big, it should allocate 2.7 MiB on most systems while the stack size is usually set to few MiB (set by default 2 MiB on most Linux platforms). You should use Dynamic matr...
62,967,176
62,967,206
Segmentation fault when using copy constructor C++
Everything seems to be copying fine, but when I call array2.print(), it shows segmentation fault. What am I doing wrong? #include <iostream> #include <initializer_list> template <typename T> class DynamicArray { private: const int GROWTH_FACTOR = 2; const int INITIAL_CAPACITY = 5; T *m_array; int m_c...
The error is here T *m_array = new T[m_capacity]; It should be m_array = new T[m_capacity]; By declaring a new variable called m_array you hid the class member variable that you wanted to assign to. The technical name for this is shadowing, a good compiler would warn you about this.
62,967,201
62,967,237
Why this copy-initialization (with two implicit conversions) does not work in GCC/Clang?
Please consider the following code: #include <string.h> class cstring { public: cstring(const char* str) : begin_(str), end_(str ? str + strlen(str) : 0) { } size_t size() const { return (size_t)(end_ - begin_); } const char* data() const { return begin_; } privat...
Gcc and clang are correct, only one user-defined conversion is allowed in implicit conversion sequence. Implicit conversion sequence consists of the following, in this order: zero or one standard conversion sequence; zero or one user-defined conversion; zero or one standard conversion sequence. You could change ...
62,967,918
63,001,249
Unable to retrieve data from a SQLite database & display on QT GUI
I'm trying to create a login system whereby if a person logs in, it should display their name on the Qt GUI that follows the login GUI. I've tried using the code below however, the label is just blank, so I'm assuming the issue is from the database. All help will be appreciated, thank you. #include "TaxiCoZa.h" TaxiCo...
I managed to fix the problem by using the first() function from the QSqlQuery class Kindly see the code below for changes void TaxiCoZa::on_loginButton_clicked() { QString emailInput = ui.emailEdit1->text(); QString passwordInput = ui.passwordEdit1->text(); QSqlQuery query; query.prepare("SELECT * FROM riders WHERE e...
62,968,016
62,968,115
Why am I able to increment a pointer pointing at a single new int location? and the surprisingly it works well
What's going on here it is working but it is still ambiguous. Can anyone tell me more on this or atleast point me to some relevant Sources to know more about it #include <iostream> #include <string> int main() { std::string br="\n"; long *a=new long; *++a=121; *++a=545454; *++a=232; std::cout<<*...
This is working because a is a long pointer pointing to a memory location in heap. Heap consists of a huge chunk of memory to be used at run time. In short, While incrementing a, a points to the memory location next(may not be contiguous) to the one allocated by new. Some References: https://stackoverflow.com/a/4482297...
62,968,406
62,969,635
SFINAE and sizeof vs constexpr
Sometimes people write something like the following (source): template<typename T> class is_class { typedef char yes[1]; typedef char no [2]; template<typename C> static yes& test(int C::*); // selected if C is a class type template<typename C> static no& test(...); // selected otherwise public:...
Both options would work. But the difference between them is that the first one doesn't require C++11 while the second one does. And if you are free to use at least C++11 - there is no need to use any of them, there is already std::is_class in the standard library. So if you see such code in some project then either thi...
62,968,704
62,968,736
Passing a pointer as a function argument
I am passing a pointer to a function with intent of modifying the data kept at the original address. #include<bits/stdc++.h> using namespace std; void square(int **x) { **x = **x + 2; cout<<**x<<" "; } int main() { int y = 5; int *x = &y; cout<<*x<<" "; square(&x); cout<<*x<<" "; return ...
You can make it pass-by-reference, if you just want to perform modification on the argument through the parameter in the function. void square(int& x) { x = x + 2; cout<<x<<" "; } int main() { int y = 5; cout<<y<<" "; square(y); cout<<y<<" "; return 0; } If you only have the pointer, you ca...
62,968,904
62,969,036
Selection Sort | c++
Hi I'm new to c++ I've written a selection sorting program can you help me and say in swap function why we put the stars(*), and in selectionSort we should use & in <<swap(&arr[min], &arr[i]);>> i mean cant we just say: int newint = a; a = b; b = newint; instead of: int newint = *a; *a = *b; *b = newint; mai...
Pointers are passed by reference, that means, that if you change it in a function, it will be changed after the function call, too. Like: int a=5; setTo6(&a);//Implementation: *a=6 //a=6 On the other hand, all other parameters, that are not pointers are passed by value. This means, if you change them in the function, ...
62,968,907
62,971,036
Understanding C++ Code written with templates and class inheritance
I came across the below piece of code in a header file. template <int x, template <typename T> class Car, typename DOC, typename COMMON, typename filter = imp::Filter> class CurrentClass : public imp::base< x, Car, DOC, CurrentClass<x, Car, DOC, COMMON>, Filter> { public: C...
There is a lot of noise in this code and as mentioned, it is quite advanced, but google the points I note below. There are several distinct things I can point out: 1. template <int x, template <typename T> class Car, typename DOC, typename COMMON, typename filter = imp::Filter> The "int x" part require tha...