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 |
|---|---|---|---|---|
69,231,700 | 69,232,007 | Recommended C++ Include Practice | In the following scenario, what would be the best approach to include the <string> header?
main.cpp
#include "extra.h"
int main() {
func("A string");
return 0;
}
extra.h
#ifndef EXTRA_H
#define EXTRA_H
#include <string>
void func(std::string);
#endif
extra.cpp
#include <iostream>
#include "extra.h... | Your extra.h includes <string> because it uses it directly. There is no direct use of std::string in your main.cpp so it would be strange to include <string> there.
Further, including <string> in extra.cpp is totally unnecessary because the use of std::string is in a function signature which you know is declared in ex... |
69,231,701 | 69,232,126 | I can't understand how the time complexity of following c++ code is calculated? | Following code prints union of two unsorted arrays using C++ STL set.
I know that the time complexity of inserting an element in a set is O(log N), where N is the size of the set.
This code is from https://www.geeksforgeeks.org/find-union-and-intersection-of-two-unsorted-arrays/.
// C++ program for the union of two arr... | In C++, a set is internally implemented using a self-balancing Binary Search Tree (BST). This means that everytime a new element is inserted into a set, internally it has to check the correct place of insertion of this new element in the BST, and then rebalance that BST. This operation of inserting a new element and pe... |
69,232,463 | 69,233,763 | Switch default c++ library from std=c++14 to std=c++17 on ubuntu | I have tried to install a package on ubuntu that needs c++17 or newer libraries.
I installed gcc-10 and g++-10. I also found that the default c++ library is c++14 by using this code:
man g++ | grep "This is the default for C++ code"
But I don't know how to change it to other versions.
To run a simple code we can use -... | The c++ standard library traditionally is part of the compiler. On GNU/Linux systems typically GCC is used in conjunction with its standard library. An alternative would be CLang.
Note that the standard version is not only about the library, but even more so about language features that need to be implemented by the co... |
69,232,521 | 69,235,328 | Convert a Tabled PDF data into a text (or any other readable format) file using C++ or Python | I have a PDF file that contains Timetable of a university, generated from aSc Timetables software.
The data looks something like this,
There are about 29 such pages in the PDF file.
I want to process this data for a program and therefore, want it to be in readable form in any programming language, and preferably in C... | I've compiled up a repository on GitHub
I used pdf2image to first convert the pdf to image files and store those files in an images folder.
Then used pytesseract to convert those images to txt files and store those txt files in texts folder.
After that, I formatted the text a little and store it in csv format in csvs ... |
69,233,057 | 69,233,089 | C++ - auto return reference and non reference type | When writing a function with auto return type we can use constexpr if to return different types.
auto myfunc()
{
constexpr if (someBool)
{
type1 first = something;
return first;
}
else
{
type2 second = somethingElse;
return second;
}
}
However, I'm struggling to work out how t... | Just auto will never be a reference. You need decltype(auto) instead, and also put the return value inside parentheses:
decltype(auto) myfunc()
{
if constexpr (someBool)
{
type1 &first = refToSomething;
return (first);
}
else
{
type2 second = somethingElse;
return second;
}
}
|
69,233,616 | 69,251,610 | Trouble accessing Unityplayer.log on Hololens | I want to see my debug statements after running an app on Hololens which are stored in the Unityplayer.log file.
I am not able to download this logfile from the Windows Device Portal after running the app.
I am not sure what is causing this problem. The following issue pops up on the browser : This site can't be reache... | The issue was that the project solution would not stop running in the Visual Studio when I closed the app on the Hololens. When I stopped the Deployment on the VS, I had no issue downloading the log file. In addition, sometimes the Hololens got disconnected from the internet now and then.
|
69,234,502 | 69,235,193 | How to pass a member function to a gloabal function in cpp? | Im on a Cpp beginner project. making a library system. And I wrote the following void Student::show(void) function to show student's details. Also I have written the first function to avoid repeating. I want to pass the create function to the printAtEnd function as a argument. But it gives me some errors. What I did wr... | Removing useless code from the question, it could be something like:
void printAtEnd(std::function<void ()> fn)
{
fn();
}
void Student::show()
{
printAtEnd([this](){ this->show(); });
}
However, the problem with your code it that it is recursive and if the user always select the option 2, you might eventuall... |
69,234,680 | 69,351,394 | Multiple source paths in batch-mode rule [nmake] | Im using the batch-mode rule for my makefile. Currently i have the following targets:
DIR_SRC = src
DIR_INCLUDE = include
DIR_LIB = lib
DIR_BIN = bin\x64
DIR_BUILD = build\x64
{$(DIR_SRC)}.cpp{$(DIR_BUILD)}.obj ::
@echo Compiling...
cl /c /EHsc /Fo$(DIR_BUILD)\ /MD /I$(DIR_INCLUDE) $<
$(EXECUTABLE... | If you add a second build directory to match your second source directory, you can get this to work. For example, if we modify your makefile to be:
DIR_SRC = src
DIR_SRC2 = another
DIR_INCLUDE = include
DIR_BIN = bin\x64
DIR_BUILD = build\x64
DIR_BUILD2 = build_another\x64
EXECUTABLE_NAME = foo.exe
{$(DIR_SRC)}.c... |
69,235,162 | 69,237,834 | How can I find the number of elements in an already declared array of size n, if it's partially filled? | Suppose I created an array of size 5. Filled two number 1 and 2 at index 0 and 1 respectively. Now I want to return number of elements currently present in the array, i.e. 2 and not 5 given by size below. How can I do that?
int arr[5];
arr[0] = 1;
arr[1] = 2;
//size returns 5 but I want it to return 2, ... | If you use a classic array, it is not possible to do what you say, you will get 5 outputs each time. But if you use std::vector, the size of the vector will change automatically every time you add a new element to the vector. Then, you can easily count the number of elements in the vector by using the size() function. ... |
69,235,185 | 69,235,357 | find difference between max and min element within a range of an array | Say I got following array
a = [4 5 2 1 3 4]
and I want to find the difference between two elements (the max and min) excluding some consecutive elements.
For example, excluding the 2nd and 3rd so that I need to find the difference of max/min of:
a = [4 1 3 4]
which in this case is
diff = 4-1
Now I am looking for... | So we have an array a of size N and M queries of this form: "Excluding the interval [L, R], what's the difference between the max and min element in a?". Consider we have an efficient way to query the min and max value on an arbitrary interval [X, Y], then we can use the following algorithm:
Query min/max on the inter... |
69,235,381 | 69,235,854 | What would new int[3] do to the int pointer? | I was looking for uses for pointers and this turned out to be one of them. Dynamically allocating memmory. I am a little confused with the keyword new, and when adding [number] in the end. new int[3]. I do understand that this question might be bad. I'm only 13.
#include <iostream>
using namespace std;
int m... | A pointer is basically a variable pointing to a specific address in memory. An array is a group of variables allocated consecutively in memory. When you write scores = new int[3] you allocate a memory for three int-type variables and make the scores variable reference the first one's address. Now, when referencing the ... |
69,235,389 | 69,235,776 | why do two getline() lead to no input? | I am creating a simple login program.
#include <iostream>
#include <string>
using namespace std;
void showRegister()
{
string user;
string pw;
cout << "Enter your username:";
getline(cin, user);
cout << "Enter your password:";
getline(cin, pw);
cout << "You have successfully registered!... | The fact is getline takes input from buffer if something exists in buffer else it ask the user for value. What actually happens in your code is as soon as you enter value for select which is not greater than 3 it comes out of the loop after with a value you entered for select and the entered (which stands for \n) that ... |
69,235,560 | 69,235,646 | How can an operating system detect an out of range segmentation fault in C? | I encounter this problem when learning Operating System and I'm really interested in how operating system detecs whether an array index is out of range and therefore produce a segmentation fault?
int main(){
char* ptr0;
ptr0[0] = 1;
}
The code above will absolutely produce a segmentation fault, since ptr0 is n... | A segmentation fault happens when a process attempts to access memory it's not supposed to, not necessarily if an array is read out of bounds.
In your particular case the variable ptr0 is uninitialized, and so if you attempt to read it any value may be read and it need not even be consistent. So in the case of the fir... |
69,235,641 | 69,235,715 | Why is not jthread::get_stop_source const? | The question says it. [thread.jthread.stop]/1 says:
[[nodiscard]] stop_source get_stop_source() noexcept;
Effects: Equivalent to: return ssource;
Why is it not a pure observer?
| A stop_source object allows you to request that the thread which has such an object (or its attendant stop_token) perform a stop. Such a request is not logically const. As such, if you fetch a stop_source for a jthread, it is expected that you are going to perform the aforementioned "not logically const" operation.
So ... |
69,235,904 | 69,236,026 | Print address of iterator | Why is it not possible to change the cout line with following in order to get the address of the iterator?
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main (int argc, const char* argv[]) {
vector<int> inputs = {15, 20, 10, 5, 19};
vector<int>::iterator i;
i = inputs.be... | It's not possible because there is no overload for operator<< that takes vector<>::iterator as its second argument. If you want to print the address of the iterator object, you'd need &i.
Or you could overload it yourself:
std::ostream &operator<<(std::ostream &os, const std::vector<int>::iterator &i) {
os << &i;
r... |
69,236,089 | 69,236,151 | Error C2280 : Class::Class(void) : Attempting to reference a deleted function | So, I am working on a project, and I have two files in this project:
main.cpp, matrix.h
The problem is that My code seemed to work perfectly a few hours ago, and now it doesn't
main.cpp:
#include <iostream>
#include "matrix.h"
#include <vector>
int main() {
Matrix f;
f.create(10, 1, {3, 4, 5, 6, 7, 8, 9});
}
m... | Here is the correct working example. The error happens because every const data member must be initialized. And
The implicitly-declared or defaulted default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true:
T has a const member without user-defined d... |
69,236,159 | 69,236,352 | Why can't I unpack entries of std::map into references? | I have noticed that unpacking keys and values from std::map does not give me references. I am assuming that individual entries in std::map is stored as a pair of const key and value.
What works:
Manually taking .second of pair from std::map into reference.
Unpacking a pair made using std::make_pair into references.
Ta... | It is a reference. However, there is a special rule that decltype on a structured binding does (from [dcl.type.decltype]/1.1):
if E is an unparenthesized id-expression naming a structured binding ([dcl.struct.bind]), decltype(E) is the referenced type as given in the specification of the structured binding declaratio... |
69,236,331 | 69,236,332 | Conda MacOS Big Sur ld: unsupported tapi file type '!tapi-tbd' in YAML file | When compiling a c++ project in a conda environment on MacOS Big Sur, the error
ld: unsupported tapi file type '!tapi-tbd' in YAML file may occur. How to proceed?
| On Big Sur, the SDK that comes with Command Line Tools is too new. An older one needs to be downloaded and used:
Download the 10.10 SDK "MacOSX10.10.sdk.tar.xz" from here.
Extract it: tar xf MacOSX10.10.sdk.tar.xz -C /opt
Add following lines to ~/.condarc:
conda_build:
config_file: ~/.conda/conda_build_config.yaml
... |
69,236,391 | 71,255,560 | why pass window pointer in callback function opengl | why do we pass GLFWwindow pointer to parameter when we don't use the window pointer variable
example:
coid sizecallb(GLFWwindow* window, int w, int h){
glViewport(0,0,w,h);
screeenw = w;
screeenh = h;
}
| This is done because GLFW is written in C, not C++. Therefore, there's not so much ways to distinguish one window from another. Also, it's not us who pass info to callbacks, it's GLFW that executes callbacks from its code. It specifies window handle so that you can choose the window for which this callback is meant to ... |
69,236,441 | 69,236,504 | Right method to declare a struct as member in another struct | Recently, I've asked a question about how to declare a struct member in another struct:
How to allocate memory for struct as member in other struct?
My question was marked as a duplicate. But really, do I need to initialize all members with default values?
In my project code base, the struct has 3 such members. And whe... | While this constructor "works":
B(A c_a) : a{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
{
a = c_a;
}
It is needlessly complex, as it initializes a with default values, just to overwrite it with new values afterwards.
At the very least, you could give A a default constructor that initializes the members to 0:
A()
{
a = 0... |
69,236,476 | 69,238,577 | Compile-time C++ function to check whether all template argument types are unique | There is a nice question (Which substitution failures are not allowed in requires clauses?) proposing the next problem.
One needs to write a compile-time function template<typename... Ts> constexpr bool allTypesUnique() that will return true if all argument types are unique, and false otherwise. And the restriction is ... | If you use virtual base classes depending on each of the given types, you will get exact one base class instance for every unique type in the resulting class. If the number of given types is the number of generated base classes, each type was unique. You can "measure" the number of generated base classes by its size bu... |
69,236,646 | 69,236,898 | Using poppler as a subproject in Cmake with `CMAKE_MODULE_PATH` set incorrectly | I'm new to CMake to I'm not sure what I'm doing
I'm using poppler as a library via CMake for my application. I've imported it as a submodule.
If I include popper in my top-level CMake file using add_subdirectory(...), it get the following errors
[cmake] CMake Error at external/poppler/CMakeLists.txt:7 (include):
[cmake... | So in your CMakeLists.txt just store and restore the CMAKE_MODULE_PATH before including the subproject.
set(tmp ${CMAKE_MODULE_PATH})
add_subdirectory(...)
# suffix the poppler stuff too.
set(CMAKE_MODULE_PATH "${tmp};${CMAKE_MODULE_PATH}")
You could also separately notify developers of the poppler project of the iss... |
69,236,857 | 69,236,927 | "ReadProcessMemory" how to get std::string? | Programm_A
int main()
{
std::cout << "Process ID = " << GetCurrentProcessId() << "\n"; // Id my process (i get something like '37567')
std::string My_String = "JoJo"; // My string
std::cout << &My_String << std::endl; //here i get something like '0x0037ab7'
system("pause");
}
This program just outputs ... | You can't easily read a std::string across process boundaries.
Different standard library implementations of std::string use different memory layouts for its data members. The std::string in your program may be using a different implementation than the program you are trying to read from.
But even if the two programs u... |
69,237,361 | 69,237,431 | What is the best way to store a value that will have to be read by multiple source files but is only know at runtime | I have a function that runs when the program is started and initializes all variables that will be needed by the program but that can only be obtained during runtime. These variables will have to be read by multiple source files.
What is the best way to store these values?
One of these variables is the file path to the... | Use a function-local static variable. It will be initialized on the first use.
const std::string &GetAppDataPath()
{
static const std::string ret = /*do stuff here*/;
return ret;
}
A global variable (which are initialized at program startup) would be inferior, because you can accidentally access it before it's... |
69,237,455 | 69,237,516 | How to return a WM_COPYDATA message instantly and also call a function? | How to return a response when receiving a WM_COPYDATA message 'instantly' and also call a function?
I tried to use chrono but the app that sent the message only receive a response after the sendCommand function has been executed.
#include <thread>
#include <future>
#include <iostream>
void sendCommand(std::chrono::sec... | What you're looking for is called a lambda function (https://en.cppreference.com/w/cpp/language/lambda) and looks like this:
With std::thread:
std::thread t([]
{
sendCommand(std::chrono::seconds(5), "Command1");
});
With std::async
Solution with shared future, by capturing it the lifetime of the future is ex... |
69,237,483 | 69,237,533 | How to separate the count of odd numbers in loops | I am currently making a program which asks the user to input 10 integers and the code will have to count how many odd numbers there are. At the end of the program it prompts the user whether to retry it again, essentially in a loop if they choose to input a new set of 10 integers.
int i, value;
int odd = 0;
char option... | The definition/initializationint odd = 0; is outside of the do…while loop so it is not being reinitialized for each loop iterations. There are two options to accomplish what you want to do:
Move int odd = 0; to the beginning of the do…while loop after do{. This reduces the variable scope to each iteration of the loo... |
69,238,325 | 69,238,528 | Return unique_ptr by value or by reference? | I want to create a wchar_t* which length is dynamic. So I decided to write the following function:
std::unique_ptr<wchar_t> mem::TO_WCHAR_T_PTR(char* str)
{
size_t len = strlen(str) + 1; // Size of my wchar_t string
std::unique_ptr<wchar_t> wStr_ptr(new wchar_t[len]); // Compiler supports C++17
size_t conv... | Your way of returning std::unique_ptr is correct. It'll either be placed in ptr1 directly via NRVO (Named Return Value Optimization) or moved into it. You should NOT return std::move(wStr_ptr), however, since that will prevent (N)RVO. And it works the same way for std::shared_ptr.
|
69,238,821 | 69,238,932 | Compile time subclass byte-offset with virtual inheritance | Is it possible to compute, at compile time, the byte offset of a virtual base in an inheritance hierarchy?
Example -
class A {};
class B : public virtual A {};
class C : public virtual A {};
class D : public virtual B, public virtual C {};
I would like to compute the byte offset of instance of B, C, and D w.r.t. A at ... |
Is it possible to compute, at compile time, the byte offset of a virtual base in an inheritance hierarchy?
No, because it's different for different object instances. It is not a property of the class.
Let's look at your example. B has a virtual base class A. So B has to have some byte offset to an A. The same is true... |
69,238,937 | 69,239,007 | Why is the array (sentence) printing 38 elements when it only have space for 30? | #include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
int main() {
//initialising the char array and vector
char sentence[30] = {};
vector<string> words{"The", "only", "thing", "to", "fear", "is", "fear", "itself"};
//For loop iterates through the vector and adds the c... | Indexing an array with index that is greater then size ot the array is undefined operation. You'll never know what will be an output.
For example in your case, if you try to access
char c = sentence[37], this is undefined operation. Means that char c could be whatever is read from memory location of sentence + 37 * siz... |
69,239,132 | 69,239,151 | C++ inherited parent calling all constructor overloads | I'm working through this course on udemy and I'm baffled at this output.
The default parent constructor for Creature() is called even when I call the constructor through the child's constructor. I've been in JavaScript land the last 8 years so I've seen some wacky stuff, but I'm not sure how I'm accident pull this off.... | This is wrong:
Dragon::Dragon(string name, float health)
{
Creature(name, health);
cout << "Dragon constructor WITH arguments" << endl;
}
Well, it is syntactically correct but it is not doing what you think it does. Creature(name,health); calls the constructor of Creature to create a temporary that lives till ... |
69,240,067 | 69,338,025 | CMake with Conan cannot find assimp-vc142-mt.lib | I'm trying to link assimp into a simple C++ project using Conan and CMake. However, when I build, it's giving me the following error:
LINK : fatal error LNK1104: cannot open file 'assimp-vc142-mt.lib' [C:\dev\test0\build\test.vcxproj]
Here is my conan default profile:
[settings]
os=Windows
os_build=Windows
arch=x86_64
... | https://github.com/conan-io/conan-center-index/issues/7342
I had the CMake directives in the wrong order. You must do conan_basic_setup() before creating your executable and linking any libraries.
|
69,240,165 | 69,241,708 | How to detect the last iteration of std::map using structured bindings from C++17? | How could I detect the last iteration of a map using structured bindings?
Here's a concrete example: I have the following simple code whereby I print elements from an std::map using structured bindings from C++17:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, size_t> ... | Yakk's answer inspired me to write an iterators_of using Ranges and without introducing a new class:
#include <iostream>
#include <map>
#include <string>
#include <ranges>
template<class Range>
auto iterators_of(Range&& r){
return std::ranges::views::iota(std::begin(r), std::end(r));
}
int main() {
std::... |
69,240,330 | 69,240,364 | Comparing pointers that are not necessarily associated with the same array | The C Programming Language book by Brian W Kernighan & Dennis M. Ritchie, 2e, states the following on Pages 102-103:
… pointers may be compared under certain circumstances. If p and q
point to members of the same array, then relations like ==, !=, <, >=,
etc., work properly. But the behavior is undefined for arithme... | Yes. Well, unspecified not undefined, which is much safer.
Converting to int_ptr is a guaranteed round trip however. Also std::less<>{}( a, b ) is guaranteed to be well behaved and consistent with < when < is specified.
This unspecified behaviour permits three things.
Originally, segmented memory; pointers could ign... |
69,240,486 | 69,240,663 | Program to calculate distance between two points in 3D with class and operator overload | I can't speak english very well, sorry. I am having a problem with a practice question given to me. I am asked to write a code that finds the distance between 2 points in 3D space according to their x, y and z coordinates. But while doing this, it wants me to use the class structure, use the get-set functions, use the ... |
#include <cmath> not math.h
Make coordinat store only one point (x, y, z).
Add a member function for subtracting one coordinat from an other:
coordinat& operator-=(const coordinat& rhs) {
// add code to subtract the values in rhs from the values stored in *this
return *this;
}
Add a member function to re... |
69,240,507 | 69,245,639 | Ambiguity in case of multiple inheritance and spaceship operator in C++20 | In the following simplified program, struct C inherits from two structs A and B. The former defines both spaceship operator <=> and less operator, the latter – only spaceship operator. Then less operation is performed with objects of class C:
#include <compare>
struct A {
auto operator <=>(const A&) const = defau... | gcc is correct here.
When you do:
c.operator<(c);
You are performing name lookup on something literally named operator<. There is only one such function (the one in A) so this succeeds.
But when you do c < c, you're not doing lookup for operator<. You're doing two things:
a specific lookup for c < c which finds opera... |
69,240,827 | 69,243,549 | Makefile returns an error when I try to use cl.exe as the compiler | I have activated vcvarsall.bat in my makefile, however I still get this error when I try compiling my program:
**********************************************************************
** Visual Studio 2019 Developer Command Prompt v16.11.1
** Copyright (c) 2021 Microsoft Corporation
**************************************... | In a makefile recipe, every command line is run in its own shell. In Windows the vcvarsall.bat file sets a bunch of environment variables and environment variables are in effect only for the current shell; when the shell exits they are gone. When you run:
build: main.cpp
@call "C:\Program Files (x86)\Microsoft Vi... |
69,240,902 | 69,258,919 | Protoc failed to parse input if integer value more than 127 in Unreal Engine 5 c++ | Environment:
Unreal Engine 5
Windows 10
Protocol Buffers v3.18.0
I'm trying to decode serialized data in Unreal Engine 5 (c++) by using protoc. If the message contains the value of int var less than 127 everything is okay. But if the value more than 127 I catch the error: Failed to parse input.
player.proto:
syntax =... | I found a solution.
I'll keep it here, maybe it will help somebody.
I changed the implementation to avoid string conversion.
Before:
...
// serialization
std::string MyPlayerString;
if(!MyPlayer.SerializeToString(&MyPlayerString))
{
UE_LOG(LogGameInstance, Error, TEXT("Can't serialize MyPlayer to String"));
re... |
69,240,967 | 69,240,976 | string uppercasing adds junk to the end of char array | I am learning c++, I write some code to convert a string to uppercase and display it. I assign a string str with "asdf" and then create a char array pointer and allocate a length same as that of the string.
But after I assign indices of char array with uppercase chars when I try to display char array there are many jun... | Your char array needs to be one character longer than the length of the string, for the null terminator
string str{ "asdf" };
char* str_c = new char[str.length() + 1];
for (int i = 0; i < str.length(); i++) {
str_c[i] = toupper(str[i]);
}
str_c[str.length()] = '\0';
cout << str_c; // displays ASDF
In C-sty... |
69,241,099 | 69,241,152 | What does std::move do when called on a function? | I'm working on making some changes to a piece of code, and have a doubt in understanding the behavior of std::move in below case:
struct Timer {
Timer (boost::asio::io_service& ios) : timer_{ios} {}
boost::asio::steady_timer timer_;
};
struct TimerContext {
void *ctxt_;
};
class A {
std::function<void(Tim... | Look carefully at A's constructor:
A::A (std::function<void(Timer *, const TimerContext&)> cb)
The function, cb is being passed by value. That means a copy of the function has already occurred from when it was invoked via new:
A *a = new A{customCallback};
The std::move in the constructor initializer list exists to ... |
69,241,697 | 69,241,954 | How can I determine parameters of lambda in C++? | I want to transform all functions, which take tuples as arguments, passed to Foo into functions which take plain arguments.
auto f = [](const std::tuple<int, char>& t) { return std::get<0>(t); };
template <typename F>
auto Foo(F&& f) {
...
}
Foo(f)(42, 'a')
My idea was to do something like this
template <typenam... | If you don't really need the parameter types. simply
template <typename Callable>
auto Foo(Callable f) {
return [=](auto&&... args)->decltype(auto){
return f({std::forward<decltype(args)>(args)...});
};
}
the plus side is Foo can now accept more generic f, which could have multiple opreator() defined.
|
69,241,721 | 69,242,817 | Why not apply [[nodiscard]] to every constructor? | Since C++20, [[nodiscard]] can be applied to constructors. http://wg21.link/p1771 has the example:
struct [[nodiscard]] my_scopeguard { /* ... */ };
struct my_unique {
my_unique() = default; // does not acquire resource
[[nodiscard]] my_unique(int fd) { /* ... */ } // acquires... | An example from the pybind11 library: To wrap a C++-class for python, you do:
PYBIND11_MODULE(example, m) {
py::class_<MyClass>(m, "MyClass"); // <-- discarded.
}
|
69,241,781 | 69,241,847 | Factorial loops with C++ | I'm trying to write a loop in C++ that calculates the factorial of a given input between (1 and 10 inclusive) then displays that factorial. The code only breaks when 0 is used as input. I have written the loop which does all these except that the only correct answer I get is the first input, all other successive iterat... | As mentioned in the comment, you don't reset the temporary variable when going into 2nd and subsequent loop operations. The easiest way to remedy that is to move the variable definition lower, limiting its scope:
do {
...
if (n > 0 && n <= 10) {
int factorial = 1; // <- here
for (int ... |
69,241,797 | 69,241,813 | Sized array in function signature | Does defining a sized array in a function signature (as opposed to the more commonly used unsized array or pointer syntax) have any bearing at all? My compiler is ignoring it completely, as the following sample code shows (which runs, although it prints some garbage values when a smaller-sized array is passed).
#inclu... |
Does defining a sized array in a function signature (as opposed to the more commonly used unsized array or pointer syntax) have any bearing at all?
No, it has not, the passed array argument will always decay to a pointer to its first element, placing a size is indeed pointless from the compiler standpoint, it will ig... |
69,242,776 | 69,242,826 | c++ why priority_queue greater<> result is different from sort`s greater result? | I searched for similar contents, but I don't understand the answer, so I'm asking you again.
vector<int> v;
v.push_back(3);
v.push_back(11);
v.push_back(13);
v.push_back(-1);
v.push_back(-8);
v.push_back(324);
v.push_back(55);
sort(v.begin(),v.end(), greater<int>() );
for(auto i : v)
{
cout << i << " ";
}
// resul... | From this std::priority_queue reference:
A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element
[Emphasis mine]
So the default sorting using std::less is descending. By using std::greater you reverse that. ordering.
|
69,243,308 | 69,243,415 | problem with accesing protected methods in friend class | I'm starting a new project and I have trouble with accessing protected methods of Organism inside World class. I suppose there must be some error with my definition of World being a friend of organism. I tried calling some method from Organism inside World, but the compiler says that it is inaccessible. The method was ... | The problem was the fact that #pragma once was not at the beginning of World.h But after including Organism.h. That leads to tons of weird errors including the fact that despite being friends of Organism, World couldn't use its private methods.
This is correct:
#pragma once
#include "Organism.h"
This, however is absol... |
69,243,670 | 69,244,233 | Integration with right rectangle rule | I am trying to complete the task of integrating with the right rectangle rule, but I am stuck at one moment. The first two values are being outputted, but further ones are just 0...
The task is about starting with iteration count 3 and continuing up to 512, by multiplying iteration count by 2 every time.
I feel somethi... |
Change sum += Function(lower + pre_sum + i); to sum += Function(lower + pre_sum * i);. That is, you should multiply by i rather than add it. i represents the index of the iteration (indexed by 1 for right-rectangle integration; indexed by 0 for left-rectangle integration.)
Change for (int i = 1, step ; i < iteration_c... |
69,243,826 | 69,243,868 | C++ code to print the number of words in a given string | This is the link above of the code of printing the number of words.
It's running properly but sometimes it's showing the error "out of range", I don't know the reason,
can someone please explain why?
#include <iostream>
using namespace std;
int main()
{
string str;
getline(cin, str);
int count = 0;
for... | Simple answer is:
while (str.at(i) != ' ')
might go out of bound.
Think what would happen if you enter these lines?
Hello!!!!
Hello world!!!
It will hit that while() loop and loop forever.
Why are you getting error sometimes, and not all the times? Because you are causing undefined behavior.
Your if statement is not ... |
69,243,906 | 69,244,291 | circular dependencies in member function specializations ....... "instantiation before specialization" | the code below doesn't compile
#include <iostream>
using namespace std;
template<class T> class A;
template<class T> class B;
//@@@@@@@@@@@@@y
template<class T>
class B{
int x=1;
public:
void write(A<T> x);
void add(A<T> x);
};
template<class T>
class A{
int x=1;
public:
void write(B<T> x);
void add(B<T> x)... | You can declare specializations of template methods after each class declaration:
#include <iostream>
using namespace std;
template<class T> class A;
template<class T> class B;
//@@@@@@@@@@@@@y
template<class T>
class B{
int x=1;
public:
void write(A<T> x);
void add(A<T> x);
};
// declare specializations:
templat... |
69,244,973 | 69,245,067 | C++ How to store odd numbers in an array and access them using a pointer notation? | I found an error in the book solution, the below solution is using the pointer notation to access the array as requested, but the printed results are not odd numbers, instead its printing 1 to 50 and 50 - 1.
Original instructions: Write a program that declares and initializes an array with the first 50 odd (as in not e... | Just write
for (size_t i = 0; i < n; ++i)
{
odds[i] = 2 * i + 1;
}
And the last loop rewrite using the variable i of the type size_t like
for ( size_t i = n; i != 0; --i )
{
std::cout << std::setw(5) << *(odds + i - 1 );
if (i % perlin... |
69,245,695 | 69,461,101 | Pragma ignoring comment [-Werror=unknown-pragmas] | I'm trying to make function which will return version from FileVersionInfo,
so far i built funtcion, but i have issue when i want to include version.lib
#pragma comment(lib, "version.lib")
I have tried to link, libversion.a, something like this
#pragma comment(lib, "libversion.a")
but, again compiler was returning er... |
"This pragma to link libraries from C++ source code is only supported by MSVC"
Switched compiler from gcc/g++ to MSVC, that's only solution :(
|
69,246,212 | 69,247,123 | How To Pass Component Pointer From QML To C++? | What is the easiest way to pass a component pointer created in a QML file to C++? From Qt Documentation explanations we could take the QML file root object and then search for our component objectName. But it's hard to keep sync the components objectName in both C++ codes and QML codes:
Just for Copy/Paste: qml_pass_ob... |
The easy thing is debatable since it depends on the definition of what is easy or difficult for each case so I will not answer this question since it falls outside of SO.
Yes, it is valid to export any QML object to C ++. The id is the reference to the object so you are not passing the name "testItemId" but you are p... |
69,246,294 | 69,246,735 | Why is this counting sort in C++ not working? | Why is this counting sort not working?
#include <bits/stdc++.h>
using namespace std;
void countSort(vector<int>& input)
{
int max = *max_element(input.begin(), input.end());
vector<int> counter(max + 1);
vector<int> output;
for(int i = 0; i < max + 1; ++i)
{
counter[i] = 0;
}
for(... | The main problem is in your push_back.
output.push_back(counter[input[i]]);
It should simply be:
output.push_back(i);
You also do not save the result of the sorted output array. You could return it or replace input. In my example below, I'm replacing input.
Another potential problem is that you are sorting signed int... |
69,246,328 | 69,249,592 | C++: redefining public class methods from imported shared library? | Suppose I have a shared library with a class that defines public non-virtual methods, and I want to import said shared library but re-defining some of those class methods without creating a new class, in a way that the library would call the methods I redefine when those are used internally within the shared library.
F... | No, this is a violation of C++ ODR rule and is handled in different ways on different platforms. It is not portable even for GCC - interposition will not work if e.g. the symbols in code have protected visibility or library has been linked with -Wl,-Bsymbolic or with -fno-semantic-interposition.
|
69,246,465 | 69,246,717 | Is there any way to perform this type of recursion in C++ or python? | Let us say I have a function called my_func(a,b,s,t). Suppose, I want a and b to be passed by value, but I want s and t to be passed by reference. As in, I want to some how pass in let us say (4,5,s',t'). The function performs computations by calling my_func(a/2,b/2,s/2,t/2). The thing is, there is a base case at the "... | Your code seems broken, already that base case (?) with a == b and s = 4 and t = -3 doesn't make sense. But see this C++ implementation and my Python translation using single-element lists instead of C++'s references:
def gcd(a, b, x=[None], y=[None]):
if b == 0:
x[0] = 1
y[0] = 0
return a
... |
69,246,546 | 69,246,710 | makefile is skipping target | I have the following makefile for a project:
VIEW := View
CONTROLLER := Controller
MODEL := Model
all: compilar
compilar: criterio acta persona director jurado asistente universidad view main
g++ -o Salida Criterio.o Acta.o Persona.o Director.o Jurado.o Asistente.o Universidad.o View.o main.o
criterio: ${MODEL}/Cr... | view: ${VIEW}/View.cpp ${VIEW}/View.h ${MODEL}/Universidad.h
g++ -c ${VIEW}/View.cpp
declares that you are going to create a file called view and that the inputs are ${VIEW}/View.cpp ${VIEW}/View.h ${MODEL}/Universidad.h. As your command actually produces a file called View.o your makefile won't work. You need:
Vi... |
69,246,823 | 69,246,878 | Does it need to initialise the variable after allocating memory? | I am trying to implement matrix multiplication in c++. I found a sample code using a class that writes in .h and .cpp files. This is just a part of the code that related to my question:
#include "Matrix.h"
// Constructor - using an initialisation list here
Matrix::Matrix(int rows, int cols, bool preallocate): rows(row... | From cppreference on new expression:
The object created by a new-expression is initialized according to the following rules:
[...]
If type is an array type, an array of objects is initialized.
If initializer is absent, each element is default-initialized
If initializer is an empty pair of parentheses, each element i... |
69,246,931 | 69,246,992 | How to make a c++ project from command prompt? | Note that this is referred to make a project from command prompt, not build or run it, by "make", i mean, creating a .vcxproj file like Visual Studio does.
I am unable to use Visual Studio for now, this is why i'm asking to make a project through cmd, i tried gcc, but it doesn't generate these project stuff.
| GCC is just a compiler, rather than a full IDE like Visual Studio. It takes source code (and some binary libraries), and then outputs compiled executables or object files.
You can use a build system like CMake or Meson, which can make the building process easier for you and those who clone your code, and can even be in... |
69,247,041 | 69,260,057 | Linkers: file was built for archive which is not the architecture being linked (x86_64) GLFW | Hello, this problem make me crazy and i need your help.
I am on a IOS High Sierra v10.13.6 and i am trying to try OpenGL on VSC on mac without XCode.
So i have downloaded the library GLFW for the right OS.
I have tried the basic exemple from the GLWF website.
#include "../GLFW/glfw3.h"
// g++ -v main.cpp -o main.o -L/L... | i want to say that i have found the solution for my problems.
You have to double check that the library libglfw3.a is compiled in the good architecture witch is the x86_64.
Here the official link to download the GLFW library in the right OS
Also here is the command you need to run for make it compile:
You need to make ... |
69,247,650 | 69,271,899 | How do I create a class with reference member and vector of pointers? | I am fairly new to C++ and am working on a personal project. I want to create a vector<Entity*> entitities in C++ where each Entity object is unique. I have a class inside header Entity.h that I want to create. Now Entity takes two member variables:
Rectangle rect - an Object of type Rectangle that has four float vari... |
My question here is, what should the class Entity look like ? Should I create separate CopyConstructor, Assignment Constructor and Destructor for this class ? Also if I want to implement copying one Entity into another (deep copying), is it necessary to have all 3 (Copy, Assignment and Destructor) ?
The answer to thi... |
69,247,777 | 69,247,826 | c++ Thread pool std::promise and function type error | I try to write my own version of a Thread pool but have difficulties with lines
template <typename F, typename...Args>
auto addWork(F&& f, Args&&... args) -> std::future<decltype (f(args...))>
{
using ReturnType = decltype(f(args...));
//...
result.set_value(f(args...... | In case where your ReturnType is void, your std::promise<ReturnType> result variable is a specialisation - std::promise<void>. Its set_value(4) method does not take any arguments.
To fix the issue, you can just use if constexpr to check whether you are dealing with the special case that involves a function returning vo... |
69,247,796 | 69,248,017 | Why does a `char *` allocated through malloc prints out gibberish after the function allocating it returns? | I'm trying to write a function to parse and extract the components of a URL. Moreover, I need the components (e.g. hostname) to have the type char * since I intend to pass them to C APIs.
My current approach is to save the components in the parse_url function to the heap by calling malloc. But for some reason, the foll... | The problem is that arguments are passed by value, so the newly created string never leaves the function (albeit exists until program termination as free is never called on it). You can pass by reference¹ like:
void cast_to_cstyle(string source, char *&target)
or better, pass the source string by (constant) reference ... |
69,247,811 | 69,247,910 | C++ Why is the output of this code 3? (structs) | Can someone help me understand step-by-step why the following C++ code outputs a 3?
#include <iostream>
using namespace std;
struct sct
{
int t[2];
};
struct str
{
sct t[2];
};
int main() {
str t[2] = { {0,2,4,6}, {1,3,5,7} };
std::cout << t[1].t[0].t[1];
}
| t[1] is {1,3,5,7}.
str is represented in memory as four integers back-to-back, organized into 2 sct structures. In this case, the first one has the values 1 and 3, while the second contains 5 and 7.
Thus, t[1].t[0] is {1,3}, so t[1].t[0].t[1] is 3.
|
69,247,901 | 69,247,943 | When the user enters the letter n as the major mark, the major mark will instead be represented by the number: | My code goes like this
#include <iostream>
#include <string>
using namespace std;
int main() {
string z,zz ="";
int x,y;
cin >> x >> y >> z >> zz;
for (int a = 1; a <= x; ++a) {
cout << z;
for (int b = 1; b <= y; ++b) {
cout << zz;
}
}
cout << z;
return 0;
}
If my... | If you:
Move the declaration of a outside of the outer for loop.
Change both cout << z; statements to cout << a;.
Change the outer for loop to start at 0 instead of 1, and to use < insted of <=.
Then you will get the output you want.
#include <iostream>
#include <string>
using namespace std;
int main() {
string ... |
69,248,025 | 69,248,204 | operator overloading about Abstract class (cpp) | In student.h file
class Student {
protected:
string Name;
int Stu_num;
public:
virtual void print() = 0;
// constructor...
}
class Grad_Student: public Student {
private:
string Lab;
public:
void print();
// constructor...
}
class Undergrad_Student: public Student {
private:
string Major;
public:... | So, your overloaded equality operator does nothing... You need to compare something in the body and return a boolean result.
Also, your Undergrad_Student currently doesn't derive from Student..
Furthermore, since you're comparing 2 Student objects you can just make the equality operator overload a member function takin... |
69,248,248 | 69,248,387 | How to start my else if for loop start with 01 - 09? | How do I make my code specifically on else if to print out this if my input is 45?
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
21.22.23.24.25.26.27.28.29.30
31.32.33.34.35.36.37.38.39.40
41.42.43.44.45
#include <iostream>
#include <string>
using namespace std;
int main() {
string dot = "";
int ... | Your entire program can be simplified using setw and setfill to do the hard work for you of inserting leading zero chars where needed. #include <iomanip> to have access to these stream modification functions.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int x;
cin >> x;
for (i... |
69,248,633 | 69,248,913 | Better system than having multiple vectors for each event type | I am trying to implement a basic event system. This event system consists of a series of void pointers used for callback functions. The code below is BAD design. If I want to add many events, the code quickly gets bloated.
Currently, the bad solution needs to know what vector to add to, and which vector to run based of... |
This event system consists of a series of void pointers used for callback functions.
Use std::function in a suitable form / shape / wrapper.
Currently, the bad solution needs to know what vector to add to, and which vector to run based off of the event type.
Use a std::multimap from the event type enum to a suitabl... |
69,250,055 | 69,251,578 | operator overloading abstract class | There is an Student abstract class, and two derived class Grad and Undergrad; and I want to overload operator in several ways.
student.h
class Student {
protected:
string Name;
int Stu_num;
public:
virtual void print() = 0;
bool operator==(const Student& x) const;
// constructor...
}
cla... | While that may appear to work, type_info::name() is
implementation-dependent,
not guaranteed to be unique between different types,
not guaranteed to be the same between different executions of the same program.
Comparing type_infos directly is reliable though, so you could do things like if (typeid(*this) == typeid(G... |
69,250,533 | 69,251,509 | Starting the default terminal on Linux | Tell me, please, is it possible to call the Linux Terminal, which is installed by default, in some way (method)?
Now, I run the process in the xfce4-terminal terminal, specifying this terminal and the arguments to it:
QProcess up;
QString cArg;
cArg="/tmp/cp.py -y " + ye;
up.start("xfce4-terminal", QStringList()<< "-... | No, there is no general way in the Linux kernel to find out which (or whether a) terminal emulator is installed on the system by default.
Although the (fairly ubiquitous) freedesktop.org specifications describe how to associate MIME type with a default application, there isn't a specification for default application wi... |
69,250,948 | 69,251,878 | How to combine two relative URIs into one in C++ | I have one base URI like https://stackoverflow.com/questions/ask and a relative URI.
I want to combine them all into one absolute URI.
Examples:
Relative URI: ../
Result: https://stackoverflow.com/questions
Relative URI: /abc/kk?6
Result: https://stackoverflow.com/abc/kk?6
Relative URI: task.php?ui=4
Result: https:/... | It seems the proposal to add URI-handling to standard C++, https://isocpp.org/files/papers/n3975.html, is dead and/or stuck in committee.
You therefore have to write your own or use a 3rd party - e.g., Qt has QUrl with https://doc.qt.io/qt-5/qurl.html#resolved
QUrl QUrl::resolved(const QUrl &relative) const
|
69,251,112 | 69,256,111 | Take inputs from keyboard and increase/decrease sides of a shape using GLUT | Take inputs from keyboard such as "+" or "-" and increase/decrease sides accordingly. For example if a triangle is currently displayed and if i press "+", it should transform into a rectangle etc. How can I achieve that?
static void DisplayShape(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glCol... | Distribute the N-points around a circle. Compute the angle between the vectors from the center of the circle to the points (360°/N). Calculate the points using their Polar Coordinates:
const float x0 = 0.0f;
const float y0 = 0.0f;
const float sideLen = 0.5;
float dist = sideLen / 2.0f / sin(M_PI * 2.0f / n / 2.0f);
flo... |
69,251,173 | 69,251,622 | When you have a number which has over 1 digit in a created board, what should you do prevent it from affecting the shape of the board | I am new to C++. And I am trying to implement a 2048 game based on C++ for practice. And I am trying to create a board first.
The problem I have is that when the number is become a two digit numbers it will affect the shape of the wall like this:
Here is the test code:
#include<iostream>
using namespace std;
int main... | It looks like you actually want a char gameboard[24][25]; rather than a 2d array of strings. When each cell of the board is exactly 1 character wide then you just need to print it character by character to get expected output.
If you do that you need to place individual digits rather than the complete number as string:... |
69,252,152 | 69,252,215 | String isn't printed after using strcpy | I'm trying to copy string s to r using strcpy(). But it does not print out any result. Why?
#include <iostream>
using namespace std;
#include <string.h>
int main() {
char s[] = "john lemon";
char r[] = "";
strcpy(s, r);
cout<<s<<" "<<r;
return 0;
}
| strcpy(a,b) copies the string b into the string a
You have copied the empty string to the the string s. After the copy it also contains the empty string.
Printing empty string results with no characters outputted as empty string does not contain any printable ones.
If you want to copy in the opposite direction you must... |
69,252,287 | 69,252,430 | Can I reorder elements in map by value? C++ | I want to make a table of letter frequency, just like this
So, I have variable str that contains some text, and I have map<char, int> m, that contains number of occurrences of each letter.
So I have something like that:
vector<char> get_rank(const string& str)
{
map<char, int> m;
for (char i = 'a'; i <= 'z'; i... | It is not possible to sort a map with respect to its mapped values. The order of elements of a map is managed by the map according to its comparator which only considers keys.
However, you do not need a map to count frequencies when the keys are contiguous and of limited range.
Instead of a map, use a std::vector<lette... |
69,252,437 | 69,252,860 | Run c++ function from python | I am trying to access GPIO of my IDS camera via python using pyueye. The original function is defined as: INT is_IO(HIDS hCam, UINT nCommand, void* pParam, UINT cbSizeOfParam). This is an example of usage:
Example 2
INT nRet = IS_SUCCESS;
IO_GPIO_CONFIGURATION gpioConfiguration;
// Set configuration of GPIO1 (... | The error is actually being thrown by your call to ctypes.pointer rather than pyueye. Specifically, gpioConfiguration is a _ctypes.PyCStructType rather than an instance. (This is what was meant by 'must have storage', i.e. you actually have to store something looking like that struct before you can get a pointer to i... |
69,252,632 | 69,252,897 | vcpkg: How do I submit a request for a package update, or see if the package is due an update? | I am (obviously) new to vcpkg but I can't figure out how to either see if a package is due for on upgrade on vcpkg or submit a request for an upgrade on a package. I have seen how to specify an older version of a package in the docs but not request an upgrade, see the planed versions etc.
Any links and explanation plea... | That's not how vcpkg works, the maintainers of vcpkg do not manage package upgrades. It is the responsibility of the package maintainers to create pull requests for vcpkg that upgrade their packages: https://github.com/microsoft/vcpkg/pulls
There isn't an open PR for sqlite, so either create one yourself or ask the sq... |
69,252,739 | 69,252,964 | Deleting node that doesn't exist in linked list causes segmentation fault | So I am new to data structures and I am trying out linked lists. I have made a class Node with an int key, int del and Node* next.
When I try to delete nodes by giving delete function (Del) a key, it works perfectly for head node or any node existing in the list but when I give a key that doesn't exist in the list it r... | in this line (curr->key != k && curr != NULL) you should check if curr is null first and before accessing curr to check it's key value, so it should be (curr != NULL && curr->key != k).
explanation :
when node isn't exist - i see in your code you assume node key is unique - so you still loop over the linked list till c... |
69,252,898 | 69,252,983 | Why can functions with different calling conventions still call each other? | int __cdecl funcB(int a, int b) {
return 0;
}
int __stdcall funcA(int a, int b) {
return funcA(a, b);
}
I wrote this two functions and they have different calling conventions: __stdcall and __cdecl.
And my question is why MSVC didn't throw a compile error?
Because in my view two functions with different cal... |
Because in my view two functions with different calling conventions can't call each other
That's simply an incorrect view. A calling convention is just a set of rules for how arguments are handled across the call. The compiler generates instructions at each call site and within the body of the function that follow wh... |
69,253,347 | 69,253,885 | Passing the partially constructed object in pimpl | I have a class setup that I have converted to use pimpl, something like this:
(outline only, I'm aware this doesn't compile)
struct GAME
{
unique_ptr<GAME_IMPL> _impl;
explicit GAME() : _impl( new GAME_IMPL( *this ) );
IMAGES getImages() { return _impl._images; }
};
struct GAME_IMPL
{
IMAGES _images;... | I think you missed some details, here is a setup that compiles.
#include <memory>
struct GAME_IMPL;
struct IMAGES {};
// A 'trick' I often use
// for pimpl you can define an abstract base
// helps you check if public and impl class
// implement the same functions
//
// it also ensures you only have a pointer to an in... |
69,253,581 | 69,253,641 | Using pragma once in .cpp file | Recently reading some pieces of code I encountered several .cpp files that contained
#pragma once in the beginning of file. I know that it is usually used in .h files as guards.
What are the cases when #pragma once should/can/must be used in .cpp files?
| #pragma once shouldn't be used in source files, its one goal is to act as include guard. It won't do much harm .cpp files are normally going to be "scanned" once during compilation anyway. Note: Clang tidy will warn you if you do it.
Warning clang-diagnostic-pragma-once-outside-header #pragma once in main file
|
69,254,531 | 69,254,576 | Calling GetDesktopWindow() function in winuser.h instead of CWnd::GetDesktopWindow() in an MFC OnButtonClick function | For my own education, I am playing around with the code snippets of some on-line examples.
Early in these examples, there are these lines:
HWND hDesktopWnd = GetDesktopWindow();
HDC hDesktopDC = GetDC(hDesktopWnd);
For convenience reasons, I added a new button to my dialog-based demo MFC project, and the code I expect... | Use the scope resolution operator on the functions:
::GetDesktopWindow();
::GetDC();
|
69,254,545 | 69,254,643 | How can I replace this code with one if statement? | For the sake of challenge, how can I replace this code with only one if statement?
unsigned int x, y;
cin>>x;
if((x>=0)&&(x<=1)) y = 1;
else if (x<=3) y = 2;
else if(x<=5) y = 3;
else y = 6;
| Without knowing why you want to use a single if, it's hard to tell. Of course, you can use ternary operators without any ifs:
unsigned int x, y;
cin>>x;
y = x<=1
? 1
: x<=3
? 2
: x<=5
? 3
: 6;
Or ugly boolean casting hacks for exactly one if (please don't actually do this outside of a puzzle or co... |
69,254,721 | 69,254,848 | template member function resolution fails when declaring const | the code below shows some interesting behavior:
#include <iostream>
using namespace std;
template<class T>
class B{
public:
void foo(B<T> &x)const;
template<class F> void foo(F f);
};
template<typename T> void B<T>::foo(B<T> &x)const{cout<<"foo_B"<<endl;}
template<typename T> template<typename F> void B<T>::foo(F f... | The issue here is that since void foo(B<T> &x)const; is const qualified, It would have to const qualify the object you are calling the function on. This isn't as exactly as a match as template<class F> void foo(F f); provides as it doesn't need to do that const qualification. That is why it is used for both calls.
Yo... |
69,254,792 | 69,256,013 | Qt: QAudioInput vs QAudioRecorder | I am using Qt Multimedia 5 to analyze audio (FFT, LUFS, and dBFS, etc.) from audio input device.
To get audio data, there are two main options, QAudioRecorder and QAudioInput.
They can all read audio data with PCM (QAudioInput use QBuffer and QAudioRecorder use QAudioBuffer) and set format (e.g., sample rate), what sho... | QAudioBuffer is very convenient, and you'd use the QAudioProbe class to get notified whenever a new buffer is available - in Qt 5. QAudioProbe is not supported on Mac OS unfortunately.
QAudioProbe doesn't exist in Qt 6, and wasn't fully supported in Qt 5 either.
The only way to access "live" raw audio data in both Qt 5... |
69,254,971 | 69,255,183 | How to use do while function but also not stop other codes | I am trying to fix this problem where if you use do and while code, it will stop other commands, but if it is done, then it will continue those commands.
for (int i = 0; i < 1000; i++) {
std::cout << "hey";
Sleep(1000);
}
for (int i = 0; i < 1000; i++) {
std::cout << "hey number 2";
Sleep(1000);
}
it ... | I think you'll need threads.
Take this example. It should do the trick
#include <iostream>
#include <thread>
#include <synchapi.h>
using namespace std;
void fun1() {
for(int i = 0 ; i < 1000 ; i++) {
std::cout << "Hey";
Sleep(1000);
}
}
void fun2() {
for(int i = 0 ; i < 1000 ; i++) {
... |
69,255,022 | 69,257,708 | Mesh generation algorithm gives visual artifacts | Right now I am trying to implement terrain generation. I am using msvc visual studio 2019. And when I got to decreasing level of details in my function, generation started to be very glitchy. Everything is fine when I am not using any of level of details decreasing values. But everything changes after 1 and more - gene... | Like PaulMcKenzie mentioned, seams that I just used Even Numbers instead of Odd numbers and that was entirely of the problem. And even more, sometimes It couldn't work correctly, because I used too small numbers for generating mesh grid like 90 or 100. So, for correct working of this mesh algorithm Width should be divi... |
69,255,065 | 69,258,963 | Creating a target for a non-CMake module | I'm pretty new to CMake and am trying to learn about modern CMake.
I'm creating a project using the poppler-cpp libraries on ubuntu.
The libraries are installed using sudo apt install libpoppler-cpp-dev so they should all be available on the system paths.
My goal is to make this build work on multiple platforms eventua... | You should just use the IMPORTED_TARGET option of pkg_check_modules...
find_package(PkgConfig REQUIRED)
pkg_check_modules(poppler-cpp REQUIRED IMPORTED_TARGET poppler-cpp)
target_link_libraries(my_target PRIVATE PkgConfig::poppler-cpp)
|
69,256,391 | 69,256,539 | my code is too cumbersome, how can I fix it? | My code is similar to CTRL + C + CTRL + V, outwardly I don't like it.
In the code, only one variable changes, and everything else is the same. What are some ways you can shorten this code?
struct offsets {
std::vector<DWORD> energy = { 0x168, 0x1B8, 0x30, 0x8 };
std::vector<DWORD> minerals = { 0x168, 0x1B8, 0x3... | With function, you can do
void foo(bool& m, uintptr_t* ptr, uintptr_t add_resource)
{
if (m)
{
*ptr += add_resource;
m = false;
std::this_thread::sleep_for(std::chrono::milliseconds(130));
}
}
and then
foo(hackMenu.minerals, minerals, add_resource);
foo(hackMenu.influence, influence... |
69,256,902 | 69,257,439 | do..while loop not terminating | I am trying to find if the given number is a perfect square, and if so find the next perfect square for this codewars problem.
#include <cmath>
using namespace std;
long int findNextSquare(long int sq) {
// Return the next square if sq if a perfect square, -1 otherwise
long int k = sq;
do{
k++;
//cout <<... | You should never try to check if a float is equal to an integer (or float) as a looping condition, as there are likely rounding problems (leading to infinite loops). That means you need to reformulate your problem using only integers.
Start with the root of sq in an integer, which can be rounded off.
compare the squar... |
69,256,908 | 69,257,043 | Cannot use std::future to store polymorphic object | struct Base {
virtual void squawk () {
std::cout << " I am base" << std::endl;
}
};
struct Derived : public Base {
void squawk () override {
std::cout << "I am derived" << std::endl;
}
};
int main () {
std::future<std::shared_ptr<Base>> f = std::async([](){return std::make_shared<D... | The return type of your lambda is a shared_ptr<Derived>. Therefore, the future that async will create contains a shared_ptr<Derived>. If you want it to have a different type, you need to make the lambda's return type the correct type, by static_pointer_casting the return value to shared_ptr<Base>.
auto f = std::async( ... |
69,256,940 | 69,258,123 | Why does this lambda [=] capture create several copies? | In the following code:
#include <iostream>
#include <thread>
using namespace std;
class tester {
public:
tester() {
cout << "constructor\t" << this << "\n";
}
tester(const tester& other) {
cout << "copy cons.\t" << this << "\n";
}
~tester() {
cout << "destructor\t" << ... | The standard requires that the callable passed to the constructor for std::thread is effectively copy-constructible ([thread.thread.constr])
Mandates: The following are all true:
is_constructible_v<decay_t<F>, F>
[...]
is_constructible_v<decay_t<F>, F> is the same as is_copy_constructible (or rather, it's t... |
69,257,162 | 69,257,906 | Trouble calling function via pthread | I have a function that counts the number of occurences of a string in a char array. Calling this function normally with findword(copy, "polar") works perfectly fine and prints an int that's the number of times the string "polar" occurs in the char array "copy". Calling the function via a pthread however gives me compil... | Your findword() function does not match the signature that pthread_create() requires:
void *(*start_routine)(void *)
Try this instead:
struct findwordargs
{
char *str;
std::string word;
};
void* findword(void *param)
{
findwordargs *args = static_cast<findwordargs*>(param);
std::vector<std::string> a... |
69,258,220 | 69,259,757 | Difference between UuidCreate and CoCreateGuid | Is there a difference between the UUIDs created by calling UuidCreate and CoCreateGuid from the Win32 API?
The documentation says CoCreateGuid just calls UuidCreate, but the remarks in the documentation are quite different.
Only CoCreateGuid specifically mentions the use case:
[...] absolutely unique number that you w... | CoCreateGuid calls UuidCreate.
UuidCreate used to be the only function, and it was a type 1 (mac + datetime) uuid.
Later, after a kid was arrested after software he wrote was traced back to his laptop because of his MAC address, Windows Vista changed UuidCreate to be a type 4 (random) uuid.
And Microsoft added UuidCrea... |
69,258,942 | 69,259,001 | Why exception not the same when catching exception pointer? | I'm new to C++ exception handling. I tried to throw an exception pointer and caught it but it seems the later caught exception isn't the same as which I thrown.
Here's my code:
try {
bad_exception e2 = bad_exception();
cout << e2.what() << endl;
cout << &e2 << endl;
throw &e2;
}
catch (bad_exception* e... | You should throw exceptions by value (usually).
The problem here is you are throwing a pointer to an object. Unfortunately, by the time the pointer is caught, the object that it is pointing to has been destroyed, and thus you have an invalid pointer.
try {
bad_exception e2 = bad_exception();
cout << e2.what() <... |
69,258,968 | 69,259,798 | HDF5 Cpp - getting names of all groups in h5 file | I want to get all group names from h5 file. I was able to do that using a global variable that collects the names. My question is how to do it without the global variable? I dont want to have any global variables but i have a vector that will need to contain all the group names.
//this is the global variable i am tryin... | One way to do that would be to pass someVec to H5Ovisit in the last parameter, i.e.:
status = H5Ovisit(fileId, H5_INDEX_NAME, H5_ITER_NATIVE, op_func, static_cast<void*>(&someVec);
Then in op_func push directly to it:
auto vec = static_cast<std::vector<std::string>*>(opdata);
vec->push_back(std::string(name));
(Note ... |
69,258,971 | 69,265,607 | How to connect slot with mutable argument to signal with const argument | I need to connect binaryMessageReceived signal of QWebSocket to my slot which modifies the QByteData
The QByteData may be large so it might be really costly to copy it again in mutable variable each time. I want to reuse the existing QByteData
when I try to compile with following slot
void route(QByteArray& msg);
I ge... | You probably don't want to do that.
The signal argument is not meant to be modified if passed as const &. You are not even sure of the lifetime of the binary data in the emitter object (QWebSocket).
The QByteData is emitted from here : https://code.woboq.org/qt5/qtwebsockets/src/websockets/qwebsocketdataprocessor.cpp.h... |
69,259,025 | 69,261,160 | QColor not a registered metatype? | This is a follow-on from this question.
That article should explain why I am using a quint16 to extract the variant type.
I have derived class MyVariant from QVariant and implemented the QDataStream read operator.
This allows constructs like:
MyVariant vt;
str >> vt;
This is the streaming implementation:
QDataStream& ... | Okay, I solved this one by pure luck.
In my main, I register the type using...
qRegisterMetaTypeStreamOperators<QColor>("QColor");
And now it works!
Let me know in the comments if I did the right thing or not.
|
69,259,061 | 69,259,149 | Reference returning blank value | I'm writing a linked list, and using my main function to test it. Here's my code:
#include <iostream>
using namespace std;
class LinkedList {
int value;
LinkedList* next;
public:
LinkedList(int valueIn, LinkedList* nextIn) {
value = valueIn;
next = nextIn;
}
LinkedList(int valueIn) {
... | You are insertin list1(which is actually a node) to the end of list2, not the other way around, yet you call getNext() on list1. You should change the code in main to the below:
int main() {
std::cout << "starting..." << std::endl;
LinkedList list1(1);
LinkedList list2(2, &list1);
std::cout << list2.getValue() ... |
69,259,072 | 69,259,246 | Searching std::map in O(n) for a partial key | I have a (C++ 14) map
using MyTuple = tuple<A, B, C>;
map<MyTuple, MyData>
where MyTuple has the obvious operator<() that compares first A, then B, then C.
I want to do an O(ln N) search for keys that match some constant (a, b). Obviously if any are present they will be consecutive. So basically I want
map<MyTuple, ... | In c++14 you can use the overload to search on a partial key:
struct CompareFirstTwo {
using is_transparent = void;
bool operator()(const tuple<A, B, C>& lhs, const tuple<A, B, C>& rhs) const ...
bool operator()(const tuple<A, B>& lhs, const tuple<A, B, C>& rhs) const ...
bool operator()(const tuple<A, ... |
69,259,778 | 69,352,037 | Does QMovie support an alpha channel? | I swapped out QImageReader for QMovie to easily loop an animated GIF. However, the QImage returned by QMovie::currentImage() does not have an alpha channel. If I use QImageReader::read(), it does have an alpha channel. The documentation does not mention any difference between the two regarding alpha. Is there any way t... | I figured out the issue and I would like to provide an answer in case others are in a similar situation.
The GIF file I was using had an alpha channel, but it didn't have any transparent pixels. Internally, QMovie calls QPixmap::fromImage(), which seems to remove the alpha channel if it is not used.
|
69,259,995 | 69,267,591 | How to write a portable constexpr std::copysign()? | In particular, it must work with NaNs as std::copysign does. Similarly, I need a constexpr std::signbit.
constexpr double copysign(double mag, double sgn)
{
// how?
}
constexpr bool signbit(double arg)
{
// how?
}
// produce the two types of NaNs
constexpr double nan_pos = copysign(std::numeric_limits<double>... | Use of __builtin... is not really portable, but works in compilers that mentioned as target. __builtin_copysign is contexpr, but __builtin_signbit is apparently not on clang, so doing signbit with __builtin_copysign:
#include <limits>
constexpr double copysign(double mag, double sgn)
{
return __builtin_copysign(ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.