question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
65,818,064 | 65,818,100 | compile error with char * as template parameter | Can someone tell me what's wrong with this code?
template <typename T>
class Base
{
public:
virtual void foo(const T & t) = 0;
virtual ~Base() {}
};
struct Derived : Base<char *> {
void foo(const char * & t) override {};
};
I get compile error
void Derived::foo(const char*&)’ marked ‘override’, but does... | When you have
virtual void foo(const T & t) = 0;
and T is a char *, then the function type is not const char *. The const applies to T, so what you really have is a char * const. That means your overriding function would need to be
void foo(char* const& t) override {};
|
65,818,179 | 65,818,613 | "Component not found" error when I try to load a PNG texture (Direct3D 11) | I am trying to load a texture from a .GLB model in Direct3D 11. The image data is encoded as PNG (I checked the buffer and I could see the file signature in the first 4 bytes). When I try to execute my code, there is an HRESULT returning a WIC "component not found" error (0x88982F50). This is when I try to use WIC from... | I found what was wrong. Besides the fact that I was not calling CoInitialize (which I should), I was not referencing the buffer right.
Instead of:
ThrowIfFailed(pIWICStream->InitializeFromMemory(reinterpret_cast<BYTE*>(&imageBuffer), static_cast<DWORD>(imageBuffer.size())));
I should have done:
ThrowIfFailed(pIWICStre... |
65,818,269 | 65,818,589 | Set icon for Qt application built in Visual Studio | I have a Qt application that I've made in Visual Studio however I can't figure out how to create the executable (on windows) with a specific icon instead of the default windows executable icon. Anyone know the simplest way to do this using visual studio or something else?
Edit -
In addition to the answer below this is ... | I don't know whether this is the Qt-offical way of doing things but this is what works for me:
Create a *.ico file of whatever you want to use as a logo. I called mine favicon.ico.
Create a file named yourapplication.rc.
Add the following line to yourapplication.rc: IDI_ICON1 ICON DISCARDABLE "favicon.ico".
Add the *.... |
65,818,329 | 65,818,918 | How do I create a std::filesystem::exists() compatible path from a Windows::Storage::StorageFile? | I am using a FileOpenPicker to get a file (StorageFile^) in a Windows Universal App. That seems to work fine, and if I output the StorageFile->Path->Data(), it returns the expected file path (C:...\MyFile.txt).
When I try to open it and dump the contents to a string things go wrong (the string receives nothing), so as ... | The key things to remember about StorageFile in the Windows Runtime (using C++/CX or C++/WinRT) is that (a) it's not necessarily a file on disk, and (b) even if it is a file on disk you don't necessary have permissions to open it directly.
The only 'generally safe' pattern you can use for doing traditional file I/O ope... |
65,818,563 | 65,818,835 | Why are some programmers using string as an input and then converting it? | I've recently came across this code in C++:
int main(){
std::string a='0'; //I missed the quotes here anyways that wasn't
//really necessary for the question ... | There's more than one way to take this kind of input, and believe me, there are a multitude of weird, bizarre, if not just plain wrong ways to do it.
Reading into a std::string means you can do your own validation and surface errors where the conversion failed, or if the input was unexpectedly long or short.
If you rea... |
65,819,156 | 65,820,498 | Would initializing a variable in (e.g) a loop be less efficient than just using one already defined? | So guys I am having a bit of trouble understanding how memory is allocated on the stack. First let me show you the code I am going to talk about:
#include <iostream>
int main() {
int testing{};
for (int i{}; i < 15; ++i) {
int j{i};
testing = j;
}
std::cout << testing << '\n';
... | A trivial type you don't take the address of has no real existence.
Compilers will extract side effects, and ignore you copying it around.
Compilers don't have to, but they are also free to do a+b as a loop.
When you do a debug build it will sometimes brainlessly make extra steps and copies to allow you to create point... |
65,819,723 | 65,819,843 | Use If statement / conditional to output data to one file or another file C++ | New to C++. I have a #define variable (global variable? Not sure what these are called in C++) which I can set to a 1 or a 0. If it is == 1, I want my code to output my data to "File_A.txt". If it == 0, I want my code to output the data to "File_B.txt".
I tried to use an if statement when initializing the output file:
... | Here's a code fragment, based on Sam Varshavchik's comment:
std::ofstream fout; // Don't assign to a file yet.
//...
char const * p_filename = nullptr;
switch (value)
{
case 0: p_filename = "File_B.txt"; break;
case 1: p_filename = "File_A.txt"; break;
}
fout.open(p_filename);
In the above example, the... |
65,820,055 | 65,825,635 | split a range of numbers into several ranges with ranges-v3 | I have a certain amount of points and some tetrahedra in space and, for each point, I compute in which tetrahedron it is. Point that are not in a tetrahedron are discarded.
auto samplerIdAndCoarseTetra = mcSamplers
ranges::views::transform([&coarseAABBTree](const auto &mcSampler) {
return coarseAABBTree.an... | You don't want split, but group_by:
auto same_tetra = [](auto& lhs, auto& rhs){ return std::get<1>(lhs) == std::get<1>(rhs); };
// vec, your range of tuples.
auto groups = vec | ranges::view::group_by(same_tetra);
Demo
|
65,820,126 | 65,835,875 | How to convert a OpenCV 2D matrix into a 1D array in C++? | I have some difficulties converting a Mat OpenCV matrix (2D) into a 1D array in OpenCV. I am implementing my code in C++ with Visual Studio and my environment is Windows 10.
This is my code
include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/opencv.hp... | Try looping through the matrix using pointer arithmetic. First, we create a random BGR matrix of size 9, to test the procedure. The data type stored in the mat are BGR pixels represented as cv::Scalars:
//Create random test mat:
cv::Mat3b randomMat(3,3);
cv::randu( randomMat, cv::Scalar(0,0,0), cv::Scalar(256,256,256) ... |
65,821,164 | 65,821,589 | Why is C++ WMI Not Fetching Data? Error: 0xC0000005 | I'm quite new to WMI, I'm following this guide here.
So I pasted that code in the guide and ran it without any issues using the provided query. But when I changed the query to SELECT State FROM Win32_Service I get no data, just the error code 0xC0000005, which I believe is a permissions error?
That same query above wor... | I missed this line of code
hr = pclsObj->Get(L"State", 0, &vtProp, 0, 0);
Change the first argument to the property whose value you'd like to retrieve.
|
65,821,361 | 65,838,268 | fmtlib: shortcut for user-defined types with no parsing options? | I am using the {fmt} C++ library. I have written many fmt::formatter specializations for my own types. Most of these take no formatting options, so each class has a boilerplate implementation of parse(format_parse_context):
constexpr auto parse(format_parse_context& ctx)
{
auto it = ctx.begin(), end = ctx.end();
... | The implementation of parse can be much simpler:
constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
You can also reuse existing formatter specializations via inheritance or composition.
|
65,822,201 | 65,822,481 | Is there any way to parallel such functions with openMP? | I have a code line that I think I can parallel somehow, e.g:
int f1(a,b){
.....
}
int f2(a1,b1,a2,b2){
//here we are calling f1 function twice
int k = f1(a1,b1) * f1(a2,b2);
.....
return k;
}
int main(){
int result = f2(.....);
}
Is there any way how to use "#pragma omp parallel" to call these f1 ... | Provided that f1() has no bad side effects, e.g., doesn't change some global state without properly locking it, you may simply split the expression in two and use the sections construct to run each part in parallel:
int f2(a1, b1, a2, b2) {
int k11, k22;
#pragma omp parallel sections
{
#pragma omp secti... |
65,822,379 | 65,823,516 | Passing in an SDL_Event* into a method | I want to time text input in SDL2 to not spam it at 1000 key presses per second, rather the standard which is like ~33kps.
main.cpp
#include <iostream>
#include <SDL2/SDL.h>
#include "main.h"
void Main::Init()
{
std::cout << "Main Init called\n";
SDL_Init(SDL_INIT_VIDEO);
Get_Instance().window = SDL_Cr... | Your problem is
SDL_PollEvent(&event);
SDL_PollEvent returns 0 if there are no more events in the queue, but in that case it doesn't write anything into passed event structure. Since you no longer check return value of PollEvent, you operate on stale data left by last event you've had. At the very least do som... |
65,822,569 | 65,822,723 | How to call implicitly constructor of value wrapped in shared_ptr which is placed in std::map collection | I'm working with code generator where I can't obtain directly classname of the value which is wrapped in shared_ptr and placed in std::map.
I came to a situation where I need to create new map object but without access to classname I can't perform a valid object constructor call. I tried with the map operator at[], whi... | You can use the member types of std::map and std::shared_ptr to get the type of the element.
Something like
using type = typename std::map<int, std::shared_ptr<A>>::mapped_type::element_type;
mapIntToAptr[1] = std::make_shared<type>();
|
65,822,676 | 65,823,188 | Is it possible to create an array of constructors in C++? | I'm trying to get better at writing C++ code and wanted to know if something like this is possible:
I have 256 instructions in an instruction set.
They all have completely different behaviour but with common properties, so I thought about making 256 specific classes that would inherit a common class called Instruction.... |
Is it possible to create an array of constructors in C++?
No. A constructor is not an object, so it cannot be element of an array.
It is also not possible to point to a constructor with a function pointer, so an array of function pointers won't be useful. Besides, each constructor would have a different signature, an... |
65,822,708 | 65,822,860 | Can someone explain to me whats happening in this code step by step, c++ | I mean only main function. I dont understand int(c) when(when is not part of the code) c is char. How doeas it work?
#include <iostream>
using namespace std;
int main()
{
char c;
cout << "Enter a character: ";
cin >> c;
cout << "ASCII Value of " << c << " is " << int(c);
return 0;
}
| There is a table(the ASCII table), which stores a map from int to char(this is how chars are represented). The ASCII value of a char is actually the int key of that char in this table. Casting a char into int - int(c) - gives you this int key(ASCII Value of c).
|
65,822,886 | 65,823,085 | can i use printf to print element of c++ array of strings | #include <iostream>
using namespace std;
int main()
{
string s[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int a, b;
cin >> a >> b;
for (int i = a; i <= b; i++)
(i >= 1 && i <= 9) ? printf("%d\n", s[i - 1]) : i % 2 ? printf("odd\n") : printf("even\n");
retu... | You can use cout. Like so:
#include <iostream>
int main()
{
std::string s[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
int a, b;
std::cin >> a >> b;
for (int i = a; i <= b; i++)
std::cout << ((i >= 1 && i <= 9) ? s[i-1]: (i % 2) ? "odd": "even") << "\n";
re... |
65,823,601 | 65,825,781 | QT C++ How to return QImage from QThread and display it on QLabel in QMainWindow? | I am trying to process some image using OpenCV Library inside a thread, because the process operation takes some time before it's done.
So the problem is QThread always returning a Null QImage to the Slot in QMainWindow.
I get this Exception error:
Exception thrown at 0x00007FFE01962F6D (Qt5Guid.dll) in QtWidgetsApplic... | I think the problem is in creating an object image in the DetectFaceThread thread. When the run () function is executed, all data in run () will be destroyed.
I suggest creating an object image in the main thread and performing image processing in DetectFace. And use movetothread, but not the run override method.
worki... |
65,823,772 | 65,824,073 | How to convert inline assembly in msbuild to gcc | My code which uses inline assembly is executes complatly in visual studio 2019.
I want to execute this code in GCC enviroment. But, I don`t have any idea to do
How can I do that?
this is my code
int a, b;
cin >> a >> b;
__asm {
cmp b, 30;
jl bunder30;
jge bup30;
bunder30 :
add a, - 1;
add b, 60;
bu... | Inline assembler is standardized in C++, so try to follow the C++ standard (see this) instead of using non-standard extensions. That is, use this syntax:
asm ( string_literal ) ;
GCC-Inline-Assembly-HOWTO for details and alternative (non-standard) ways.
|
65,823,848 | 65,824,385 | std::ostream object in class is "not accessible through a pointer or object" | I use several functions in a class, which are passed an ostream via the function interface, which in turn can be used to output error messages. I had hoped to be able to bind all ostreams to a single object that I then redirect to a file if necessary.
The relevant parts of my code look something like this:
#include <io... | std::ostream is not default constructible, you probably want reference/pointer instead:
class Example
{
public:
Example(std::ostream& out = std::cout) : out(out) {}
void DoSomething() { FunctionWithOstream(out); }
private:
std::ostream& out;
void FunctionWithOstream(std::ostream& os) { os << "Somethi... |
65,824,317 | 65,826,386 | sophisticated summation of elements in objects residing in a std:tuple | Consider a tuple t of n objects with similar interface (like all have the same base class); n is known during compilation. I need to make a sum as following
std::get<0>(t).foo(vec_0) + std::get<1>(t).foo(vec_1) + ... + std::get<n>(t).foo(vec_n)
I know to add elements of a tuple of numbers, like here, and even variabl... | You just need extra std::index_sequence usage for the inner elements, something like:
template <std::size_t ... Is, typename Tuple, typename Vec>
auto helper(std::index_sequence<Is...>, const Tuple& t, const Vec& vec)
{
constexpr auto N = sizeof...(Is);
constexpr auto Size = std::tuple_size<Tuple>::value;
... |
65,824,554 | 65,824,555 | C++: std::vector<std::vector<T>> comes back as a vector of empty vectors when passed into a fill function by reference | Stripped down to a minimal reproducible example, the code I'm having the issue with is as follows:
#include <iostream>
#include <vector>
using namespace std;
void fill_vector_of_vectors(vector<vector<char>>& data) // I gave up on trying to think up a proper name for this
{
data.clear();
data.resize(4);
fo... | The reason the changes to the child vectors made in the filler function did not reflect in the context outside of it was the misuse of the iterating for statement. In this line,
for (vector<char> subarray : data)
subarray is actually the copy of the child vector of the vector the reference whichof has been passed to t... |
65,824,829 | 65,826,461 | How to modify the drop-down box length of QCombobox while keeping the original box length unchanged? | enter image description here
How to get the top half of the image, but not the bottom half?
int width = ui->comboBox->minimumSizeHint().width();
ui->comboBox->setMinimumWidth(width);
This method will change the length of the original box together.
| Everything is achievable via the stylesheet in this way:
ui->comboBox->setStyleSheet("QComboBox QAbstractItemView {min-width: 1000px;}");
This code changes only the minumum width of the down list.
QComboBox Modified
|
65,825,328 | 65,878,184 | Viewing double bit pattern in Visual Studio C++ Debugger | I'm working with IEEE-754 doubles, and I'd like to verify that the bit patterns match between different platforms. For this reason I would like to see the bit pattern of a double in the Visual Studio C++ Debugger.
I've tried format specifiers, but they don't seem to allow me to format a double as anything which would a... | To view the exact binary floating-point value you should print the it as hexadecimal with %a/%A or std::hexfloat instead of examining its bit pattern
printf("Hexadecimal: %a %A\n", 1.5, 1.5);
std::out << std::hexfloat << 1.5 << '\n';
However if you really need to view the actual bit pattern then you just need to reint... |
65,825,521 | 65,826,107 | Problem with shared_ptr. I cannot create my struct without mistakes | Please help find a mistake in my custom shared pointer class SharedPtr<T>. I cannot find it. But code works with leaks.
I think that mistakes in reset method or in operator= method. Probably without call these methods code works. I think so because of valgrind shows no leaks and mistakes. But with calling these methods... | The problem is in operator =. You should release the previous value if any and increment the count. And you should take case of the special case where the old and assigned pointed object are the same.
As you already have a swap, you should just use the copy and swap idiom which is known to be robust to the possible cor... |
65,825,951 | 65,826,581 | Why can i change value of int* in const int** type when getting memory from heap | have some issues with const qualifier.
I tried to do smth like this:
int a{ 3 };
int *p{ &a };
//const int **pp{ &p }; // FIXME: Compiler demands that p must have a const int *type
const int *const* pp{ &p }; // works here but it means, that I have a pointer to the const pointer to the const value
*pp = nullptr; // doe... | There are cases where this site https://cdecl.org/ for C syntax can also help with C++. For this:
const int *const* pp
it tells me:
declare pp as pointer to const pointer to const int
For this:
const int **pp1
it tells me:
declare pp1 as pointer to pointer to const int
Let's use that....
*pp = ... // ERROR !
Wh... |
65,826,133 | 65,826,311 | pybind11 access private class member via reference | I am given a class with a private variable locked_. This variable can be accessed via the methods bool& locked(); and bool locked() const;
class Test {
bool& locked();
bool locked() const;
private:
bool locked_{true};
};
I am not allowed to alter class Test, yet I must write a pybind11 interface that... | I still don't know pybind but I am starting to learn from your questions and I remember that def accepts lambdas. You can wrap the call to the member like this:
auto locker = [](Test& t, bool lock) { t.locked() = lock; };
I am not sure if you need to do something extra to make def work with your custom Test, so I supp... |
65,826,180 | 65,826,636 | Is Function call with less no of provided arguments, than needed in the function possible? | I'm making a single function, which can add up to 4 integers. everything will work fine if I pass 4 int arguments to the function and the function will add them. but if I pass less number of arguments the compiler gives an error.
So I want to ask is there any possible method by which we can give less number of argument... | To just give another answer, if the number of arguments shall be fixed (i.e. 4 in your case), you can also use something like
int sum(int a, int b = 0, int c = 0, int d = 0) {
return a + b + c + d;
}
The arguments b, c, d are then considered to be "variable". In fact, this function initializes these arguments as ... |
65,826,355 | 65,830,277 | shared_lock implemented with std::atomic | I can't afford to hold shared_lock due to its weight. Instead I implemented what I think is shared_lock but with atomic value. Will this code work, or have I missed something?
update: I added RAII classes around atomic mutex.
namespace atm {
static const unsigned int g_unlocked = 0;
static const unsigned int g_exclusiv... | For correctness I think this looks reasonable, I don't see a problem. I might have missed something, but a seq_cst CAS is more than sufficient for acquiring a lock. It looks like you're avoiding integer wrap-around by using the max value as something special.
The mutex=0 unlock only needs to be release, not seq_cst. ... |
65,826,533 | 65,827,017 | Very large array in initializer list | I need to initialize large conversion table as data member in my class:
CFoo::CFoo() :
member_one(123),
member_two(456),
member_large_table({
{"huge", "2D"},
{"array", "of"},
{"data", "..."},
.....
What is good practice to do this? Placing it in initialization array adds compila... | Let table_t be the type of member_large_table. Then you can do the following:
class CFoo {
static auto make_member_large_table() -> table_t {
return table_t{{"huge", "2D"},{"array", "of"},{"data", "..."},...};
}
public:
CFoo::CFoo() :
member_one(123),
member_two(456),
member... |
65,826,671 | 65,826,924 | Calculating the amount of Dollar-Cents combinations in C++ | Im writing a program that asks the user to enter an amount of money in the format of dollars and remaining cents which is aimed to calculate and print the minimum number of coins (quarters, dimes, nickels and pennies) that are equivalent to the given amount.
The following is the code that I have, I h... | You can rather follow this logic, multiply the dollars by 100 rather then dividing the cents by 100, by doing this you will work with cents only, it is lot easier to calculate and you will get rid of precision error problem
#include <iostream>
using namespace std;
int main() {
int dollars, cents;
int leftover... |
65,826,914 | 65,827,111 | Printing a double with plus or minus sign with a QString | I want to print a double with a QString.
Example if the double is -45, it has to print -045.0, if the value is +45 it has to print +045.0.
I tried using sprintf using the format "%05.1f" but when the double changes value I get printed : +-45.0.
My function:
Function(double value)
{
QString string;
if (value > 0)
... | The format to display the '+' sign in printf is %+...
So your function would be:
void Function(double value)
{
QString string;
string.sprintf("%+06.1f", value);
}
|
65,827,753 | 65,829,936 | Program Get Stuck After Opening a Program Using System in c++ | I want to open a program (that has terminal like CMD) with a C++ code, but when I try System() and that program opens, my C++ code get stuck until I close the program and the rest of the code will execute. I want to open a program that is a terminal and after opening, I want to send some commandS to program to execute ... | The system function in Windows C runtime library is "blocking". That means that the system command does not return until the program you are running with it exits. If you must open a program from within your C++ code, you'll need to start a new process for it so that your code can continue running (see this answer for... |
65,827,845 | 66,459,070 | KDevelop semantic analyser getting crazy with std::variant. How to deal with it? | While using KDevelop, I reached some code where the Semantic Analyser get crazy: it mostly consider the full header as semantically wrong with ugly red highlighting everywhere.
I simplified to the maximum the code and this is the result:
In case, for testing MyClass.hpp:
#pragma once
#include <memory>
#include <varia... | In KDevelop, you need to set the parser language version. This is done in Project -> Open configuration -> Language support -> C++ Parser. Then you'll be able to select C++17 as the language version for the parser.
|
65,828,224 | 65,828,778 | How to use std::max or std::min as function parameter | I like to pass std::max or std::min into a function. One can write code like this
Definition of the function
void foo (std::function<double(double, double)> extreme) {
...
const double e = extreme(rhs, lhs);
...
}
On can call the function using a lambda
foo([](const double rhs, const double lhs) { return s... | The following works:
void foo (std::function<double const&(double const&, double const&)>) {}
void foo2 (double const&(double const&, double const&)){}
int main () {
foo((double const&(*)(double const&, double const&))(std::max<double>));
foo2(std::max<double>);
}
Note that we always need to use std::max<doub... |
65,828,452 | 65,828,980 | Removing corners from 2D Matrix | I wan't to highlight the corners of a 2D Matrix in an effizient way so i can remove them later.
Im doing this in C++ but advice in any language is welcomed.
Given 2D Matrix:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[... | This python code, based on this SO answer, will produce the requisite result:
import numpy as np
a = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 7, 0, 0, 0, ... |
65,828,746 | 65,829,293 | How do I return a class object from a thread and create a vector of returned objects? | I want to use C++11 std::thread. I am writing a code to parse JSON files and the parsing is not dependent on each other. I have 900 files and to increase the speed of execution I want to create as many threads and make the execution parallel.
My problem is at the moment the function I want to pass to the std::thread is... | Using std::async seems like a good approach, since it return a std::future from which you can get the returned value.
Here is a short example that you could use as an idea to get going.
#include <iostream>
#include <future>
#include <vector>
int doWork(int i) {
return i*2;
}
int main()
{
std::vector<int> resu... |
65,829,375 | 65,831,371 | Is there a way to get filter out of Arrow::Array and some predicate? | Assume that I have an Arrow::Array (or Dataframe or ChunkedArray, not important) and I have some predicate. I want to compute a new Arrow::BooleanArray which just stores result of this predicate applied to each of the array element.
My case is that I have two sorted arrays of date32 and I want to return a mask which te... | This sounds like you need the is_in compute function:
std::shared_ptr<arrow::BooleanArray> getDatesMask(
const std::shared_ptr<arrow::Array>& haystack,
const std::shared_ptr<arrow::Array>& needles)
{
arrow::Datum mask = arrow::compute::IsIn(haystack, needles).ValueOrDie();
return std::static_pointer_cast<ar... |
65,829,441 | 65,829,647 | C2676 Compiling Error while implementing a list of structs | I am trying to check if there is already an element with same value inside a list of structs so if there isnt I push back to the list a new struct.Consider it like a system with accounts and if there is already an account I dont want to add it on the list again.
Here is my code in main:
accounts test;
test.bal = 0;
tes... | The reason is pretty simple. When you use std::find, what happens under the hood is something like this,
for(iterator i = begin; i != end; i++)
if(*i == check) return i;
Looking at this, you can see that when we pass in your list, the iterator type is std::list<accounts>::iterator but what you check against is acc... |
65,830,104 | 65,830,203 | Saving timestamp in C++11 | I am trying to get a timestamp at the start of my run, another one at the end of my run and print both at the end of the run. However, apparently both timestamps are the same: the timestamps of the end. This is my code:
#include <iostream>
#include <chrono>
#include <thread>
int main(){
std::time_t now = std::time(... | Look at asctime():
Return value
Pointer to a static null-terminated character string holding the
textual representation of date and time. The string may be shared
between std::asctime and std::ctime, and may be overwritten on each
invocation of any of those functions.
You're printing the same string twice. To correct... |
65,830,621 | 65,830,819 | QTextEdit how to clear the text when user typed in somethin Qt c++ | I'm building gui for address ip and broadcast address calculator. And i have 3 objects in my mainwindow.ui - textEdit (you type your ip address into it), textEdit_2 (you type your subnet mask address into it), plainTextEdit (just a welcome box). This is my mainwindow.cpp.
#include "mainwindow.h"
#include "ui_mainwindow... | You're looking for the placeholderText property, but you're using the wrong widget :) Use QLineEdit instead for those address inputs. placeholderText is the hint you want shown before user begins their input.
QTextEdit is a widget meant for general multi-line text editing, and what you're trying to do is a single-line ... |
65,830,652 | 65,887,798 | What TAB completion is triggering the insertion of the include statement for bits/stdc++.h? How can I prevent it? | Sometimes, after some hour of coding, in which I've certainly mashed TAB, I find out some file containing #include <bits/stdc++.h> (which I don't want to use), which means that some TAB-completion triggered that.
Since I discover this after a long time coding (typically when qualifying the change) I don't know which co... | I've been lucky today while working near the top of a source file. The header <bits/stdc++.h> gets included when I Tab-complete std::size_t.
|
65,830,676 | 65,830,748 | No output when running program in c++ | I wrote a program of Insertion sort in c++ but output screen does not showing any Statement.I am facing this problem in few another program.
This is the code:
#include<iostream>
using namespace std;
int main()
{
int n;
int arr[n];
cout<<"Enter the number of the element of the Array:";
cin>>n;
cou... | You are using the value of n before it has a value. Change your code to this
int n; // n does not have a value
cout<<"Enter the number of the element of the Array:";
cin>>n; // n gets value here
int arr[n]; // n is used here
You cannot use any variable before it has a value. That's a fundamental r... |
65,831,030 | 65,831,725 | How to create arrow array of dates using ArrayFromJSON | Basically, I want to create array of date32 type using nice ArrayFromJSON function which is super handy for writing unit tests.
I've tried:
auto dateArray = arrow::ArrayFromJSON(arrow::date32(), R"(["2017-11-01"])");
But this doesn't work at least for arrow version is 1.0. Could not find something similar in unit test... | Parsing date32 from timestamps is not currently supported by ArayFromJSON; only the integral values are currently accepted:
auto dateArray = arrow::ArrayFromJSON(arrow::date32(), "[17471000]");
Alternatively, you could construct a timestamp array then cast to date32 (but this cast may not be supported in your version ... |
65,831,093 | 65,831,812 | bubble sort in descending order | int main()
{
int a[7] = {4,33,11,8,12,123,2}, temp;
for (int i = 7; i >= 0; i--)
{
for (int j = 7; j > 7 - i; j--)
{
if (a[j] > a[j - 1])
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
... | Your program has undefined behavior because within the loops you are trying to access memory beyond the array.
That is in the inner loop
for (int j = 7; j > 7 - i; j--)
{
if (a[j] > a[j - 1])
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
th... |
65,831,174 | 65,831,917 | Effect of endianness on network byte order when doing reinterpret_cast | I am trying to convert a string representation of an IP address to its byte representation and back. For simplicity let's just talk about IPv4 addresses since endianness would affect both kinds of IP addresses in the same way.
Given a string in the form "168.212.226.204", I create an array of length 4, storing each byt... |
Is my code correct?
No, but the problem is not the endianness.
First, with regard to endianness, the 32-bit value you load through the casted pointer will be in network byte order. Since you don't interpret or convert it and simply store it to another location, that stored value will still be in network byte order su... |
65,831,210 | 65,831,518 | invalid conversion from 'int' to 'const char*' [-fpermissive]| (beginner) | When I try to compile my code this error pops out:
invalid conversion from 'int' to 'const char*'
My task is to write a program that calculates the sum of numbers with odd index.
Please don't roast me (I'm learning how to code in c++), and give some tips how to fix it and get my code working.
#include <bits/stdc++.h>
... | Your for loop is incorrect because at the first try it starts at out of range index and increases farther. here :
#include <iostream>
using namespace std;
int main()
{
string text;
cin >> text;
int len = text.length(), sum = 0, number = 0, a = 0;
for (int i = 0; i < len; i++) {
a = text[i];
... |
65,831,632 | 65,834,347 | Copy constructor called endlessly from lambda capture group | I wrote the following class to create values of any type which are either fixed or recalculated everytime the call operator is used on them:
template <typename T>
class DynamicValue {
private:
std::variant<T, std::function<T()>> getter;
public:
DynamicValue(const T& constant) : getter(constant){};
... | Some important pieces of this code:
A lambda captures a DynamicValue object by value (copy).
The lambda is used to initialize a std::variant as a std::function alternative.
There is no explicit move constructor for DynamicValue, so the template for invocable objects is used as the move constructor.
The problematic co... |
65,832,122 | 65,846,148 | How to share objects in c++ across libraries | Suppose I have a program like this:
File main.cpp
#include "something.hpp"
int main(int argc, char* argv[]) {
some = new Something();
return 0;
}
which will be linked to a .so library consisting of following files:
File logger.hpp
#include <iostream>
class Logger {
public:
Logger();
void ... | First approach: Singleton
As discussed in the comments, you could use the Singleton design pattern
to acheive this. However, remember that this pattern has several drawbacks,
two of which are:
Singletons allow global access.
Singletons are hard to unit test.
Which are true problems when writing quality software. Also... |
65,832,587 | 65,833,304 | shift cyclically second row in 2D array c++ 98 | Hi guys i was looking around some old threads but i can't find anything that works for me. I need to shift second row in my array with cpp 98 from this
int mat[4][4] = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
to this
int mat[4][4] = {{1, 2,... | One very easy method is this, first create a temporary array to store the initial values,
int temp[4] = { mat[2][3], mat[2][0], mat[2][1], mat[2][2] };
Then use std::memcpy to copy the data into mat[2],
std::memcpy(mat[2], temp, sizeof(int) * 4);
Bonus: You can use a scope to save some memory. It would be like this,
... |
65,833,022 | 65,834,757 | Inherited synthesized comparison operator produces warning/error: ISO C++20 considers use of overloaded operator '!=' | In the following code snippet clang 11.0.1 generates a warning
template <class T>
struct iterator_facade
{
template<class S>
bool operator==(const S &other) const noexcept
{
return static_cast<const T &>(*this).equal_to(other);
}
};
struct iterator : public iterator_facade<iterator>
{
bool ... | The issue is we have this comparison operator:
template<class T>
struct iterator_facade
{
template <class S>
bool operator==(const S &other) const noexcept;
};
So when we try to compare two iterators, we have these two candidates:
bool operator==(iterator_facade<iterator> const&, iterator const&); // the membe... |
65,833,061 | 65,833,450 | Simplest example of parallel run using OpenMP | Consider the following code construct,
int n = 0;
#pragma omp parallel for collapse(2)
for (int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++)
n++;
Now the above is the simplest possible demo of a similar thing I am trying to implement in a code that takes a large amount of time. So, the main objective... |
I guess, the loops are trying to access the same memory location
simultaneuouly.
TL,DR : Yes, you have a race-condition during the updates of the variable n. One way of solving that is using the OpenMP reduction clause.
I am new to OpenMP, just know some commands and that's all. Now in the
code I have written above,... |
65,833,230 | 65,833,445 | Stringify a template numeric argument | I have the following piece of code:
template<int maxRegNum> void f(MuliInstr instr);
template<> void f<0>(MuliInstr instr)
{
if (instr.regA == 0) asm volatile ("mov r4, r0");
}
template<int maxRegNum> void f(MuliInstr instr)
{
if (instr.regA == maxRegNum) asm volatile ("mov r4, r" ???);
f<maxRegNum - 1>(in... | Unfortunately, you probably require a string literal to be given asm, which you can't build with templates.
You can use BOOST_PP_REPEAT_FROM_TO to do it easily with macros though:
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#define F_DEFINITION(_, maxRegNum, __) \
temp... |
65,833,326 | 65,835,627 | Struct union packing, unpacking and storing | I recently started to play with C++'s advanced data types, pretty new to this data type. And I have not mastered bit shifting either, so please take this question with grain of salt.
I want to use unions in my new project to store variables in a single MySQL field.
e.g. rather than having multiple fields for each parts... | Alright, after a little bit more research I decided to go with storing as BLOB approach.
Here is a working example of what I did:
// Data Structure
enum EPlayerParts
{
PLAYER_PART_HEAD,
PLAYER_PART_ARMOR,
PLAYER_PART_WEAPON,
// ...
PLAYER_PART_MAX_NUM,
};
typedef struct SPlayerData
{
//...
... |
65,833,357 | 65,833,593 | Char outputting random characters at the end of the sentence | #include <iostream>
#include <string.h>
using namespace std;
void crypt(char* sMsg)
{
cout << "Original Message: '" << sMsg << "'" << endl;
int length = strlen(sMsg);
char sMsg_Crypt[3][length];
/* sMsg_Cryp[3]
[0] CRYPT LETTERS, ASCII + 3
[1] INVERT CHAR
[2] HALF+ OF SENTENC... | For starters variable length arrays like this
int length = strlen(sMsg);
char sMsg_Crypt[3][length];
is not a standard C++ feature.
You could use at least an array of objects of the type std::string like for example
std::string sMsg_Crypt[3];
Nevertheless the problem is that the array sMsg_Crypt[0] dies not contain a... |
65,835,198 | 65,835,261 | How can I pass a value into a variadic template function that forwards the value into a function that receives the value by copy? | Suppose I have this scenario:
#include <iostream>
#include <string>
void printStringsAndID(const int id, const std::string& value1, const std::string& value2) {
std::cout << id << ": " << value1 << ", " << value2 << '\n';
}
void printIntegerAndID(const int id, const int value) {
std::cout << id << ": " << val... | Issue with
template<typename... Args>
void callWithID(void(&function)(int, Args...), Args&&... args) {
static int id{ 0 };
++id;
function(id, std::forward<Args>(args)...);
}
is that Args is deduced from two places (and they should not conflict).
Possible solution is to use two template parameters:
template... |
65,835,537 | 65,835,858 | Copy constructor and assignment operators with polymorphism | Just failed an interview because of this, and I'm still confused:
class A
{
public:
A(int a) : a_(a) {}
// Copy constructor
// Assignment operator
private:
int a_;
};
class B : public A
{
public:
B(int a, int b) : A(a), b_(b) {
}
// Copy constructor
// Assignme... |
How do you implement the copy constr/assignment op
Trick question, I think. In this case the best option is to do absolutely nothing. Neither class contains (and owns) any resources requiring more than the default special member functions. Observe the Rule of Zero.
Some style guides recommend explicitly defaulting sp... |
65,835,578 | 65,836,440 | HRESULT 0x8876086c D3DERR_INVALIDCALL with DirectX9 pretty much following the documentation example | So i wanna draw an overlay over another window, but im getting no real runtime error the visual Studio debugging tools tell me that the result of
HRESULT res = object->CreateDeviceEx(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWND, D3DCREATE_HARDWARE_VERTEXPROCESSING, ¶ms, NULL, &device);
is 0x8876086c. So here are the s... | D3DPRESENT_PARAMETERS params = {};
// Use Win32 BOOL "TRUE" instead of C++ "true"
params.Windowed = TRUE;
params.hDeviceWindow = m_window;
// params.BackBufferWidth, BackBufferHeight are ignored for Windowed = TRUE
// For Windowed = TRUE, use params.BackBufferFormat = D3DFMT_UNKNOWN, which is zero.
// For params.Ba... |
65,836,748 | 65,836,975 | left rotation operation in c++ | int main()
{
int newposition, shiftSteps;
int numbers[10], numberscopy[10];
cin >> shiftSteps;
for (int i = 0; i < 10; i++)
cin >> numbers[i];
for (int i = 0; i < 10; i++)
numberscopy[i] = numbers[i];
//------------------------------------
for (int i = 9; i >= 0; i--)
... | The problem is that newposition = i - shiftSteps + 10; results in a negative value for shiftSteps == 15 and i < 5. This results in an out-of-bounds access.
You need to ensure that the rotation amount is below the number of elements of the array, which can be achieved with a modulus operator.
shiftSteps = shiftSteps... |
65,836,914 | 65,836,955 | Is it pointless to concatenate C-style cast operations? | At work I found this code in my codebase, where chars are casted twice:
constexpr unsigned int foo(char ch0, char ch1, char ch2, char ch3)
{
return ((unsigned int)(unsigned char)(ch0)
| ((unsigned int)(unsigned char)(ch1) << 8)
| ((unsigned int)(unsigned char)(ch2) << 16)
| ((un... | Yes, there is a difference. Consider if one of the char's has the value of -1. When you do
(unsigned int)(unsigned char)-1
you get 255 for a 8 bit char since you first do the conversion modulo 2^8. If you instead used
(unsigned int)-1
then you would get 4294967295 for a 32 bit int since you are now doing the conve... |
65,837,640 | 65,838,250 | Understand fmt formatter parse function | I'm trying to under the parse function for creating a formatter for a custom type in fmt. In their documentation (https://fmt.dev/dev/api.html) there is this line that has some sort of loop construct I haven't seen before:
auto it = ctx.begin(), end = ctx.end();
if (it != end && (*it == 'f' || *it == 'e')) presentation... | The formatter::parse function takes a parse context ctx and checks if the range [ctx.begin(), ctx.end()) contains format specifiers f or e in this example.
if (it != end && (*it == 'f' || *it == 'e')) presentation = *it++;
^ ^ ^
check if the check if the first
range is empty ... |
65,837,710 | 65,838,457 | Is it possible to overload delete operator to set the pointer to null? | What I want to do is overload the delete operator for my class to automatically set the pointer to null after deleting it so I can safe delete it inside a member function, like that:
# include <iostream>
class Buddy
{
public:
Buddy(void) : _hp(100) { }
~Buddy(void) { std::cout << "Buddy is dead!" << std::... | With smart ptr abuse, you might do:
class Buddy
{
Buddy() = default;
Buddy(const Buddy&) = delete;
Buddy& operator=(const Buddy&) = delete;
public:
~Buddy() { std::cout << "Buddy is dead!" << std::endl; }
void getDamage(int amount)
{
_hp -= amount;
if (_hp <= 0)
sel... |
65,838,228 | 65,838,354 | deallocation order of the static member and detached thread itself | There is a global function that initializes and cleans up some resources.
But those 2 function must be called when no other thread is running.(like curl_global_init)
Initializer must be manually called, but I don't want the cleaner to be called manually.
So I do the following.
class GLOBAL_WRAPPER {
public:
static v... | The C++ standard specifies (in so many words) that returning from main is equivalent to calling std::exit.
main function [basic.start.main]
A return statement in main has the effect of leaving the main function
(destroying any objects with automatic storage duration) and calling
std::exit with the return value as the ... |
65,838,498 | 65,839,421 | How can use specific Void functions in an if statement | #include <iostream>
using namespace std;
class Vehicles
{
public:
void wheels () {
cout << "Enter number of wheels: ";
int wh;
cin >> wh;
if (wh == 2) {
cout << "You chose a Motorcycle!\n";
} else if (wh == 3) {
cout << "You chose a Tricycle!\n";
} else if (wh == 4) {
cout << "You chose a Car!\n";
}
}
}... | There are many ways to interact with variables between different classes and different functions. As @TheUndeadFish mentioned, return values are a good place to start. If you have your heart set on using void functions one option would be to use a public variable within your Vehicles class that you set in your wheels f... |
65,838,546 | 65,838,691 | How to ensure #include doesn't recursively add (only adds unique files once) | I have this file main.h and this file events.h, the file events.h needs to include main.h as the singleton of my Events class requires my singleton of my Main class in order to declare Main as a friend class, so it can access Events private members/methods.
Conversely, Main also needs to include Events to call its meth... | This is a linker and header file problem, you just need to add #pragma once at the top of each header files, the compiler will add the content of each header files only one time, but you must ensure that you just declare methods in your header files and write the content of those methods in other .cpp files to prevent ... |
65,838,599 | 65,838,695 | Why compiler like GCC can not do dead code elimination on vector? | After trying, I'm wondering why GCC is able to do DCE on unused malloc or new buffer but not on unused vector?
malloc case: https://godbolt.org/z/xKx5Y1
void fun() {
int *x = (int *)malloc(sizeof(int) * 100);
}
Resulting assembly:
fun():
ret
new case: https://godbolt.org/z/66drKr
void fun() {
int *x =... | Since C++14, from new#Allocation:
New-expressions are allowed to elide or combine allocations made through replaceable allocation functions. In case of elision, the storage may be provided by the compiler without making the call to an allocation function (this also permits optimizing out unused new-expression). [..]
N... |
65,838,909 | 65,846,204 | Cannot apply blending to cube located behind half-transparent textured surface | Following the tutorial from learnopengl.com about rendering half-transparent windows glasses using blending, I tried to apply that principle to my simple scene (where we can navigate the scene using the mouse) containing:
Cube: 6 faces, each having 2 triangles, constructed using two attributes (position and color) def... | Your blend function function depends on the target's alpha channel (GL_ONE_MINUS_DST_ALPHA):
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA);
dest = src * src_alpha + dest * (1-dest_alpha)
If the alpha channel of the cube is 0.0, the color of the cube is not mixed with the color of the window.
The traditional a... |
65,839,370 | 65,839,532 | C++ Read numbers from a file with characters | I want to be able to add all of the numbers from the input file to find the sum, but I am not sure how to really go about this? I could use a few pointers.
This is what the input text file contains:
Mark Cyprus 21
Elizabeth Monroe 45
Tom McLaugh 82
Laura Fairs 3
Paul Dantas 102
This is what my code is so far
#include ... | There is a problem in:
while(std::getline (file,line)){
if (! isblank(line)){
// now the variable string "line" contains the line content
file >> first_name;
file >> last_name;
file >> age;
}
Once you complete the getline you ... |
65,839,869 | 65,840,465 | Right rotation operation | int main()
{
int shiftSteps, newposition;
int numbers[10], numberscopy[10];
cin >> shiftSteps;
for (int i = 0; i < 10; i++)
cin >> numbers[i];
for (int i = 0; i < 10; i++)
numberscopy[i] = numbers[i];
//----------------------------------------
for (int i = 0; i < 10; i++)... | Without auxiliary array, you can make use of reversal algorithm to rotate array by "shiftSteps".
It involves following three steps,
reversing array from 0 to sizeOfArray-1
reversing array from 0 to shiftSteps-1
reversing array from shiftSteps to sizeOfArray-1
Here's final code,
void reverseArray(int numbers[], int be... |
65,840,021 | 65,841,159 | how to get the third friday for a month in c++? | i think date handling is a little complex.
so, i want to know if there is any elegant algorithm that i can get any dates in my condition like the third friday's date in sep 2020?
let's specify two method i want:
int get_date(int month, int weekday, int no) { // for example: get_date(202009, 3, 3)
// should retur... | This is trivial using either the c++20 date support or Howard Hinnants implementation:
#include <chrono>
#include <iostream>
using namespace std::chrono;
int main()
{
constexpr year_month_day date {year(2020)/September/Friday[3]};
std::cout << date;
}
or
#include "date.h"
#include <iostream>
using namespace... |
65,840,730 | 65,840,828 | Bad access of memory - exception (C++) | I get EXC_BAD_ACCESS (code=1, address=0x0) on the 3rd last line where I return a *Bitvector. As you can see in the main I try to flip the 10'th index to 1. I highly suspect the way I manage my memory is the cause, but can't figure out where and how. (Note that the BinTree is not completed, I'm using a mac, and I use vs... | EXC_BAD_ACCESS happens when you try to access memory which isn't allocated by the application; which the application has no access privilege to.
I suppose the error is because your not adding nodes to your tree. Your just calling them. And over here: if (t==NULL), t->b.get_bitvector()->at(g) is called only if the node... |
65,840,770 | 65,840,854 | How can I store 'space' character into a list | I have declared this vector
vector<char> germat{ SekuencaEfjaleve.begin(), SekuencaEfjaleve.end() };
where SekuencaEfjaleve is a string that i get as an input from the user. The input always contains a space in the middle, so the user inputs something like this 423 fgfh=, and when I print out the list it stops at 3 it ... | Why not you use string rather then using character type vector, like this way, it is lot easier to use.
string germat;
getline(cin, germat); // used C++ builtin function `getline()` for taking string input with spaces
// now you can access by `germat[index]`
or you can take your SekuencaEfjaleve string with getline... |
65,840,904 | 65,841,453 | Implementing numpy.tensordot code in C++ for arrays having different dimensions | I'm trying to implement numpy.tensordot like summation of product for two different matrices in C++. Although I understand the implementation for arrays of same dimension, I'm unable to figure out the method to use for multiplying a 2-D array of size 3 * 3 with an array of size 3 * 600 * 600. The resultant array should... | In [129]: R = np.arange(9).reshape(3,3)
...: XYZ = np.arange(3*600*600).reshape(3, 600, 600)
tensordot has 2 styles of axes, the scalar and the tuple:
In [130]: result = np.tensordot(R, XYZ, axes=1)
In [131]: result.shape
Out[131]: (3, 600, 600)
The einsum equivalent is:
In [132]: res1 = np.einsum('ij,jkl->ikl',... |
65,841,160 | 65,841,294 | Is there a way to convert an integer to a string? | #include <iostream>
using namespace std;
class Vehicles
{
public:
int wh;
void wheels () {
cout << "Enter number of wheels: ";
cin >> wh;
if (wh == 2) {
cout << "You chose a Motorcycle!\n";
} else if (wh == 3) {
cout << "You chose a Tricycle!\n";
} else if (wh == 4) {
cout << "You chose a Car!\n";
}
}... | You can represent as a vehicle type by selecting a suitable string via the integer.
#include <iostream>
#include <vector>
using namespace std;
vector<string> types {"Weird vehicle", "monocyle", "bike", "tricycle", "car"};
class Vehicles
{
public:
int wh;
void wheels ()
{
cout << "Enter number of ... |
65,841,372 | 65,841,603 | Why can't I deduce one of the class template arguments? | I have some code here
template<typename T, std::size_t size, typename funcType>
struct foo
{
public:
foo(const funcType& func) : m_func(func) {}
~foo() {}
void m_call() { m_func(); }
private:
const funcType& m_func;
T x[size];
};
void printString() { std::cout << "some string\n"; }
I can c... | According to cppreference:
Class template argument deduction is only performed if no template
argument list is present. If a template argument list is specified,
deduction does not take place.
which your last experiment confirms. To deduce funcType you also need to provide other templated types in constructor to not ... |
65,841,540 | 65,841,595 | Using #define to a string in C++ | While trying to upload an image with cURL, I am confused because of the code below.
#define UPLOAD_FILE_AS "testImage.jpg"
static const char buf_1 [] = "RNFR " UPLOAD_FILE_AS;
What I want to understand is,
exact type of defined UPLOAD_FILE_AS : array of char / string / or something else?
exact operation performed in... |
The definition of the macro is preprocessor-style, it is just the sequence of characters, which happen to be within "". There is no type. The macro is expanded before the compiler (with its notion of types) starts the actual compilation.
C++ will always concatenate all character-sequences-within-"". "A" "B" will alw... |
65,841,810 | 65,841,956 | Expression: cannot increment value-initialized iterator (Error in Debug, but not in Release mode - Visual Studio) | I have the problem that some parts of my code run in the Release mode without a problem, but errors appear in the Debug mode.
Setup:
c++ 17 -
Visual Studio 2019
To show the difference I wrote a little testcode:
int main()
{
//Vector containing 20 lists with length of 10 each. Every Element = 10
std::vector<std::l... | The problem is not so much that it doesn't work in debug, as it is that it appears to work in release - the code is equally broken in both, but the debug version of the library has some extra error-checking code.
The error message is a bit cryptic, but what it's trying to say is that you're attempting to increment an i... |
65,842,020 | 65,842,504 | C++ program to develop a text based calculator where you can do addition, subtraction, multiplication and division | So the issue i'm having is that when I run the program, it asks for the first input but after i give the operator, the output screen just stops and i have to force quit the output screen. I am using while loops to have the user input as many numbers as they want and when they enter = symbol it should end the program an... | the while do loop is an endless loop. The breaks inside the switch-case statement end the switch-case. They dont effect the while loop. One possiblity to solve the problem is to move the 'std::cin >>op;' in the inner loop.
void calci::input(char op, double no)
{
out = 0.0;
std::cout << "Enter the first numbe... |
65,842,659 | 66,027,419 | Replacing OpenSSL v1.1.1f with v1.0.2 on Ubuntu 20.04 | I need my application to run in FIPS compliant mode. At the moment the only supported OpenSSL version with FIPS compliance is v1.0.2. On the other side default OpenSSL version on Ubuntu 20.04 is 1.1.1f.
If my understanding is correct, some applications from official repository that depends on OpenSSL ( like OpenSSH, cm... | In order for your application to be FIPs compliant, you need not only OpenSSL, but you also need complient OS. As I know at least for now, FIPS variant for Ubuntu 20.04 is not still available. So even if you solve it technically, your application will not be FIPs compliant unless you certify the Ubuntu 20.04 by yoursel... |
65,842,710 | 65,842,745 | Why does initialization happen in the following case? | I was going through the book: "C++: The Complete Reference", 4e. In the topic of copy constructors, the following is written:
It is important to understand that C++ defines two distinct types of situations in which the value of one object is given to another. The first is an assignment. The second is an initialization... | The temporary object needs to be initialized, so that y can be assigned its value.
|
65,842,878 | 65,843,317 | How do I pass a function from another class while calling std::async from a function of different class? | I have two classes, CameraToBEV and BEVTest. The CameraToBEV contains the function process().
class CameraToBEV :
{
public:
CameraToBEV(std::vector<Point2f>, cv::Point2f, cv::Point2f);
/*
process(json Object, ROI Bounding box, Output Dimensions, Input Dimensions)
*/
cv::... | As per the comment if the member function you want to run using std::async is CameraToBEV::process then the parameter passed immediately after &CameraToBEV::process should be a pointer to a valid CameraToBEV instance.
In addition, std::async will, by default, pass parameters by value. However the function you're calli... |
65,843,593 | 65,843,959 | Can I get typeid from variadic template types without passing args? | I have a system that saves typeid.name() data in a vector from various class instances,
and another system that creates bitset signatures for required combinations of classes. This signature system has no need to any class instances passed in.
I know how to get typeid.name() from non-variadic template
template<class T>... | I believe this is what you want:
template<class... T>
std::vector<const char*> getTypeNames() {
return {typeid(T).name()...};
}
|
65,843,652 | 65,843,792 | Why isn't glDrawElements drawing my circle? | I'm learning opengl and trying to draw an indexed circle using glDrawEmelents, but for some reason it does not work. However when I draw a triangle using glDrawElements (see the commented code) it draws the triangle just fine. I think it has something to do with my elements/indices, but what I don't know.
SDL_GL_SetAtt... | The type argument of glDrawElements has to correspond to the data type of the indices.
GL_UNSIGNED_INT corresponds to GLuint. If the data type is GLushort the type argument must be GL_UNSIGNED_USHORT.
|
65,843,688 | 65,844,164 | Undefined symbols using WxWidgets and Conan | I am trying to adopt the Conan C++ package manager. I have followed along with the getting started have managed to get it working with most projects. However I am having linking issues with WxWidgets that I can't seem to fix.
linker error:
[ 23%] Linking CXX executable ../bin/wx_sample
Undefined symbols for architectur... | EDIT:
You were right on the CONAN_LIBS global. Your CMake structure looks fine. You could try to call conan_basic_setup() from the src CMakeLists.txt.
If that doesn't work the issue might be in your conanfile.py.
https://github.com/bincrafters/conan-wxwidgets/commit/37b6669229ec0e68593065a700c360d23a914bac
|
65,844,544 | 67,980,796 | Exemple using BCryptDeriveKeyPBKDF2 from MSDN | I don't find some simple exemple using BCryptDeriveKeyPBKDF2 function.
I need to get key with PBKDF2 algorithm. I think it is symple action but i find very diffucult ways. I using CryptoApi Windows and i need get key.
Show me please how can i use this function to get key BCryptDeriveKeyPBKDF2 ?
https://learn.microsoft.... | I also had a hard time finding a simple example. I was finally able to create this:
#pragma comment(lib, "bcrypt.lib")
#include <Windows.h>
#include <string>
#include <iostream>
int main()
{
std::string password = "This is the password that will be encrypted";
std::string salt = "EncryptionSalt";
NTSTATUS... |
65,845,086 | 65,845,534 | P/Invoke and .NET Target Framework | This issue is driving me up the wall... Just saying.
My company has a legacy C++ library and I have been tasked to create a .NET wrapper.
I have no experience of C++ or P/Invoke so to start with I am trying a simple method.
I have read the official documentation and I have also found a nice tutorial.
However, I have di... | Now that I know it is a string issue I did a little searching and I found this SO question.
So in the end I used the BSTR approach.
BSTR SayHello() {
return ::SysAllocString(L"Hello");
}
[DllImport("DBReplicator.Lib.dll")]
[return: MarshalAs(UnmanagedType.BStr)]
public static extern string ... |
65,845,103 | 65,845,209 | Why doesn't this trigger a stack overflow on Ubuntu inside WSL? | #include <iostream>
int main()
{
constexpr size_t array_size{1000000000};
int stack[array_size];
std::cout << sizeof(stack);
return 0;
}
The program just prints out 4000000000. So seems like this should require almost 4GB of memory, significantly more than the 8MB that I thought was the stack size fo... | The program is (most probably) optimized to just show the size and no memory is actually allocated. This is allowed in accordance with the as-if rule.
Here are examples where you can compare the unoptimized (crashes) with the optimized (prints 4000000000) results.
|
65,845,403 | 65,846,409 | Read-only ranged based for | Let us consider the following example (of course this should be replaced by std::accumulate):
#include <vector>
auto sum(std::vector<int> const& numbers) -> int
{
auto sum = 0;
for(auto /*const, const&, &&, [nothing]*/ i : numbers) { sum += i; }
return sum;
}
As you see, there are many different ways to u... | Do not overthink this. In C and C++ there is "AS IF RULE" which causes that any version of your example doesn't lead to any changes in resulting machine code.
See this godbolt: https://godbolt.org/z/3rnWrr Explenation: note each compiler command line arguments is defining VERSION macro, to provide auto, auto& or auto c... |
65,846,102 | 65,857,016 | Proper way to fit int overflow in c, when we cast int to float to int |
code
#include <iostream>
int main() {
int num = 2147483647;
std::cout << (int)(float)num << std::endl;
return 0;
}
output
./main
-2147483648
-2147483648
I know that a float to int conversion is safe, but an int to float conversion is not. I also know that real floating point cannot be expressed ac... |
I know that a float to int conversion is safe, but an int to float conversion is not.
Each conversion has issues.
(Assume 32-bit int and 32-bit float for discussion.)
Large int to float risks lost of precision as float does not exactly encode all int. With OP's int num = 2147483647; (float)num, the 2147483647 was c... |
65,846,399 | 65,846,473 | constant expression evaluates to -1 which cannot be narrowed to type 'char' [-Wc++11-narrowing] error | I am working with old code and I got an error at every -1 when compiling using newer C++ standard.
constant expression evaluates to -1 which cannot be narrowed to type 'char' [-Wc++11-narrowing]
Here is the snippet code
typedef struct {
//short len;
//unsigned short cw;
char x, y, v, w;
} testSt... | To override the compiler, you have to write static_cast<char>(-1)
Some things are no longer acceptable with the newer C++ standards, so you have to find a more modern way to do things...
|
65,846,765 | 65,847,240 | Returning template class object | I have a template of a matrix class:
template <typename T>
class Matrix {
And many functions (like adding two matrices) return std::optional. I wanted to make an operator that would unwrap the value (or throw an exception):
template <class T>
Matrix<T> operator!(const std::optional<Matrix<T>>& other) {
return othe... | Your copy constructor is wrong which causes this ambiguity.
Matrix(Matrix<T>& other);
should be
Matrix(const Matrix<T>& other);
Note: You also leak memory since you new[] but don't delete[].
|
65,846,931 | 65,847,189 | C++ unable to create template constructor with template parameter |
person<worker> people (w);
I have person class and worker class, I want to create people objects from the person class.
//person.cpp
template <class T>
person<T>::~person()
{
//dtor
}
//person.h
template <class T>
class person
{
public:
person();
person(T a);
virtual ~person();
}... | Your constructor taking a worker is not defined. You only have the header, not the definition. This leads to the error
I added the definition in the class declaration as this:
person(T a) { x = a; };
Here is a minimal code that compiles and executes (from what you have done) :
#include <iostream>
class worker
{
priv... |
65,847,145 | 65,847,315 | Passing null to dlclose() | Is it safe to pass null (0, NULL, nullptr, ..) to dlclose()?
I could not find anything regarding this in the manual.
| If it is not documented, it is most likely not (or at "best" undefined).
Actually a simple test could verify that for your platform:
Compiling this
#include <dlfcn.h>
int main()
{
dlclose(0);
}
Already yields the following compiler warning (gcc):
test.c: In function ‘main’:
test.c:5:2: warning: null argument where ... |
65,847,532 | 65,848,569 | Is a recursive function in a ternary operator evaluated twice? | I came across an article that has the following statement:
maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];
My question is, would maxSubArray(A, i - 1) be evaluated (called) twice (if its value is greater than 0)? Does it increase the time complexity of the code? I think so, since w... | This:
maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];
is just a pseudo code notation of the relation between maxSubArray(A, i - 1) and maxSubArray(A, i). It just tells us how to compute the result for i when we do know the result for i-1. Read it like maths notation. Similar as
y = ... |
65,847,551 | 65,847,869 | Composition of OR statements does not yield the correct boolean value when comparing strings | I have the following code:
void funct(string m){
if (m != "s" || m != "l" || m != "r" || m != "S" || m != "L" || m != "R") {
//Do something
}
}
When passed value "r" the conditional body should not be executed, due to m!="r". Anyways "Do something" is executed.
On the other side when testing the follow... | It's surprising that you can spell out the problem so clearly and yet not see the mistake you are making
if (m != "s" || m != "l" || m != "r" || m != "S" || m != "L" || m != "R") {
//Do something
}
'Do something' will be executed if EITHER m != "s" OR if m != "l" OR ....
Since every string in the world is either n... |
65,847,581 | 65,848,169 | How to read shared preferences from Android NDK C++ code? | I'd like to read shared preferences from C++ code directly. Is that possible?
Any piece of code for that ? Thanks.
Here's what I would transcript to C++ :
val sharedPref = applicationContext.getSharedPreferences("OF_IR", MODE_PRIVATE)
val paramFromPref = sharedPref.getString("parameter", "")
if (paramFromPref != "") {
... | You can call Kotlin function from JNI easily.
Here is JNI Docs.
https://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html
You can find method for FindClass, GetMethodId, CallVoidMethod, etc.
Here is example for read sharedpreferences.
jclass jcContext = env->FindClass("android/content/Context");
jclass jc... |
65,847,741 | 65,852,130 | How to get the XId of a Gtk::Window in Gtkmm4 | I am using Gtkmm4, and lots of API has been removed. In Gtk3 one could use Gtk::Window::get_xid (inherited from Gdk::Window), but thats not possible anymore, because Gdk::Window has been renamed to Gdk::Surface, and Gtk::Window seems to not inherit from it anymore. But, one can always get the XId of a Gdk::Surface usin... | The code that deals with the underlying surfaces got split off into a separate interface, Gtk::Native, which Gtk::Window then implements. Gtk::Native has a method get_surface() which should just work like Gtk::Window::get_window() did in GTK 3.
|
65,847,945 | 65,849,165 | Structured template parameters | Building on top of this answer:
https://stackoverflow.com/a/3319851/13250135
I'd like to structure my template parameters into schemes, because the same classes are used in different contexts in the same application.
// adapted from https://stackoverflow.com/a/3319851
template<typename _string, typename _real>
struct s... | You need to make _collection a template template parameter.
template<typename _string, typename _real, template<typename, size_t> typename _collection>
struct scheme{
public:
using string = _string;
using real = _real;
// This is now a template type alias, i.e. "variable inside the scheme"
template<... |
65,848,114 | 65,849,398 | RAWINPUT.Keyboard: How to detect arrow keys when NUMLOCK=ON? | When NUMLOCK=ON then
Key ARROW_UP pressed:
data.keyboard.MakeCode = 42;
data.keyboard.VKey = 255;
data.keyboard.Flags = 2;
data.keyboard.Message = 256 (WM_KEYDOWN)
Key ARROW_DOWN pressed:
data.keyboard.MakeCode = 42;
data.keyboard.VKey = 255;
data.keyboard.Flags = 2;
data.keyboard.Message = 256 (WM_KEYDOWN)
Key ARROW... | Add flag: RIDEV_NOLEGACY and filter messages where VKey == 255
|
65,848,294 | 65,848,685 | How would I use a friend method that is predefined in a header file? | Essentially, my Computer Science teacher is making me use the friend std::ostream method for output.. I have imported it into the header file as one can see below, but I have no clue how to use it in the student.cpp. Adding student::ostream did not work. How would I be able to use the header predefined method in my stu... | I would proceed in the following manner:
add body and declaration parameters to function settingStudentName in both header and main file;
insert correct dependancies (#include);
add a main() driver function;
also, use correct syntax (friend std::ostream& operator << (std::ostream&, const student &);) lacked the comma ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.