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 |
|---|---|---|---|---|
72,677,835 | 72,677,893 | accessing elements of a vector of struct with iterators c++ | I made the following code:
namespace bcra {
// The value type of a data item.
using value_t = long;
/// This class represents a single Bar Chart.
class BarChart
{
//=== Definition
public:
/// Represents a single bar information.
struct BarItem
{... | This would have been solved by a suitable comparison function in the past but in modern C++ you would use a projection:
https://en.cppreference.com/w/cpp/algorithm/ranges/sort
|
72,679,343 | 72,679,424 | Manjaro Linux cannot open source file "gtkmm.h" | I have been trying to set up my coding environment for GUI development in c++ recently, with little success. I use Manjaro Linux with Visual Studio Code, but for some reason, I always seem to get include errors when including files that I know are there.
Most recently, I tried to set up gtkmm-4.0 by installing the pac... | You need to install pkg-configand add this to the compiler flags in your Makefile:
flags = -g $(shell pkg-config gtkmm-2.4 --cflags)
libs = $(shell pkg-config gtkmm-2.4 --libs)
# ...
$(exec): $(objects)
g++ $(objects) $(flags) -o $(exec) $(libs)
The tool pkg-config has a database of the correct paths for support... |
72,679,435 | 72,680,648 | Cmake doesn't move the actual binary when into the install dir when using --install | I'm trying to install a cmake project with
cmake --install build --prefix instdir --strip
but then instdir has bin, include, and lib but not my actual executable and it's not in any of the folders
my CMakeLists.txt looks like
cmake_minimum_required(VERSION 3.0.0)
project(executionbackup VERSION 0.1.0)
# include(CTest... | Adding
install(TARGETS executionbackup DESTINATION bin)
to the end of my CMakeLists.txt worked.
|
72,679,649 | 72,679,710 | A lambda with a capture fail to compile when used with std::semi_regular | The following example fails to compile as soon as the lambda capture any variable. If the capture is removed the compiler will successfully compile the code below.
#include <concepts>
#include <functional>
#include <iostream>
template<typename T>
concept OperatorLike = requires(T t, std::string s) {
{ t[s] } -> st... | std::semiregular requires both std::copyable and std::default_initializable.
std::copyable means that it requires the type to be copy-constructible and copy-assignable.
std::default_initializable means that it requires the type T to have well-formed initializations of the forms T t;, T() and T{}.
A lambda with a captur... |
72,679,871 | 72,679,892 | Enqueue successful, but Queue prints nothing? | I am trying to enqueue data into a queue.
The enqueue appears to have been successful because the current Node's Thing pointer is not null. Indeed, its Thing id is 7 as expected. However, something is wrong with ThingQueue's print function because the exact same Node is identified as a nullptr. This is despite the fact... | Look at enqueue, it creates a new Node and sets curr to point at it. But curr is a variable in the enqueue function, it has nothing to do with your queue, as soon as the enqueue function is exited the curr variable is lost.
You also have another problem. For some reason you have made thing a pointer. This means you end... |
72,680,155 | 72,680,214 | Explicitly defaulted copy/move assignment operators implicitly deleted because field has no copy/move operators. C++ | I'm new to C++ and dont know why this is happening and how to fix it. Here's some snippets of the code:
header file:
class Dictionary{
private:
string filename;
const string theSeparators;
public:
Dictionary(const string& filename, const string& separators = "\t\n");
... | This data member
const string theSeparators;
is defined with the qualifier const. So it can not be reassigned after its initialization in a constructor.
Thus the compiler defined the copy and move assignment operators as deleted.
You can just remove the qualifier const for this data member.
Or if to keep the qualifi... |
72,680,159 | 72,692,985 | How do you properly overwrite instructions loaded in memory from an injected DLL? | I am writing a dynamic link library to be injected into a singleplayer game on Windows and serve as a "cinematic tool" (overwriting camera transforms, timescale, etc.):
Let's say that the base address for the game executable in the virtual memory space is 0x140000000 and there's an instruction at foo.exe+0x10D64B81 tha... | Pausing and resuming threads
Thanks to @CherryDT for pointing this out — suspending the other threads of the process before writing to memory and then resuming them did the trick.
The function whose instructions I'm overwriting is one that calculates and modifies HUD opacity. In hindsight, it seems kind of obvious that... |
72,680,740 | 72,680,754 | Invalid argument STD error after compiling - no errors in VS Code IDE | I need some help with a simple program I am writing to get output from the /sys/class/thermal/thermal_zone0/temp file. Ordinarily using the command cat /sys/class/thermal/thermal_zone0/temp outputs the temperature as a five digit integer (i.e. 45000). The intention of my program is to take that output and convert it ... | Variables in C++ will not automatically updated like wire in Verilog.
Do the conversion after reading lines.
// Preprocessor directives and namespace usage
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
// Main function
int main()
{
ifstream thermal;
string sy... |
72,680,962 | 72,680,973 | Video frame returning !_src.empty() in function 'cvtColor' error | I am trying to convert frames from a video to Tensors as the video is playing. This is my code:
#include <iostream>
#include "src/VideoProcessing.h"
#include <opencv2/opencv.hpp>
#include <opencv2/videoio.hpp>
typedef cv::Point3_<float> Pixel;
const uint WIDTH = 224;
const uint HEIGHT = 224;
const uint CHANNEL = 3;
c... | You will have to read the frame before performing any conversion.
Move the part
//Capture frame by frame
bool success = cap.read(frame);
//If frame is empty then break the loop
if (!success){
std::cout << "Found the end of the video" << std::endl;
break;
... |
72,681,360 | 72,682,148 | How C++ call parameterized ctor to create object arrays? | I know in c++11 I can use initializer to create array/vector elements one by one like:
int ar[10]={1,2,3,4,5,6};
vector<int> vi = {1,2,3,4};
This is done manually, but what if I wish to initialize an array/vector with 10000 elements and specify their value, can it be done in one statement, RAII pattern?
E.g. I've defi... | You can not do this with C-style arrays. One of the many reasons you should not be using them in the first place.
You should be using std::vector, which provides a constructor to populate the vector using a single value:
std::vector<Somebody> ar{300, Somebody("42", "filler")};
But often it is better to not create such... |
72,682,129 | 72,683,466 | Does initializing references cost more memory if you copy to an lvalue less than the size of a reference? | So I believe on 64-bit systems a pointer is 8B. A float is 4B. Let's say you have the following code:
const float a = 1.0f;
Then, I want to know the cost comparison of the following. Say we have
const float b = a;
I know that copying float will be 4B. But I would think that we can 'save' memory if we don't have t... | If you write const float b = a; then you are making a copy of the value. Now if the type is a fundamental type or trivially copyable with no custom copy constructor the compiler can easily optimize away the copy and no actual code gets generated at all. That is unless you take the address of the obejct:
#include <iostr... |
72,682,461 | 72,702,302 | Reading android asset file by JNI C++ is failed | I have made android app with jni C++ code.
To read model file while creating apk on android native code(C++), I placed the model file in assets folder. (so file path is my_app/src/main/assets/model.tflite)
Then, I tried to read the model with following code but an error has raised:
Kotlin code:
private val context: Con... | Thanks to @Botje, I can load the model.tflite in assets by this way:
AAssetManager* mgr = AAssetManager_fromJava(env, asset_manager);
AAssetDir* assetDir = AAssetManager_openDir(mgr, "");
const char* filename = nullptr;
while ((filename = AAssetDir_getNextFileName(assetDir)) != nullptr) {
AAsset* asset = AAssetMana... |
72,682,547 | 72,682,630 | Is there a method to let #define normal literals as essential operators of C++? | Problem Description
I participate in competitive programming. Given that I am in desperate need of an essential template to memorize, I use macros very much.
For instance, I use
#define large long long
large value;
There are two operators that I am annoyed of though: << and >> as of input and output.
Expectation
I wou... | It is perfectly legal (though nauseous) to have a macro that expands to an operator such as << or >>, example. You just can't use and as the name of your macro, since and is a keyword.
So if you insist on going this route, just choose some other name that isn't on the list of keywords.
|
72,682,866 | 72,683,792 | How to Multi-Client in UDP socket communication | I want to have multiple clients connect, and I want to do recvfrom and sendto.
I have used std:vector as follows, but every time I recvfrom, I put information, so I wrote an if statement, but '==' gets an error.(no operator == matches these operands)
Is there a way not to add it to the vector when the same client 'recv... | First, your loop condition is wrong. i should be size_t, and you need to use < instead of == when comparing i to udpClient_list.size().
Second, you are comparing a SOCKADDR_IN instance to a SOCKADDR_IN* pointer, which obviously won't work. Get rid of &. But even then, you can't compare SOCKADDR_IN instances using opera... |
72,682,905 | 72,683,087 | last character of character array is getting excluded | #include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
cin.ignore();
char arr[n+1];
cin.getline(arr,n);
cin.ignore();
cout<<arr;
return 0;
}
Input:
11
of the year
Output:
of the yea
I'm already providing n+1 for the null character. Then why is the last character ge... | You allocated n+1 characters for your array, but then you told getline that there were only n characters available. It should be like this:
int n;
cin>>n;
cin.ignore();
char arr[n+1];
cin.getline(arr,n+1); // change here
cin.ignore();
cout<<arr;
|
72,683,577 | 72,683,730 | Checking if vector passes through vertices c++ | How can I check if a vector that starts at one point passes through another one point?
It is on two-dimensional coordinates.
Mainly uses c ++, but other languages are possible.
float2 startToTarget = target - start;
if ((startToTarget.x) * vec.y - (startToTarget.y) * vec.x >= -floatingPoint && (startToTarget.x) * v... | Calculate cross product of vector d (direction) and AB vector. If result is zero, then these vectors are collinear, so B point lies on the line, defined by point A and direction vector d.
To check direction, evaluate also dot product, it's sign is positive, when direction d coincides with direction AB
abx = B.x - A.x;... |
72,684,588 | 72,685,104 | How to solve the problem that the subclass inherits the base class and meanwhile the base class is a template parameter | #include <iostream>
using namespace std;
template <typename Child>
struct Base
{
void interface()
{
static_cast<Child*>(this)->implementation();
}
};
template<typename T,
template<class T> class Base
>
struct Derived : Base<Derived >
{
void implementation(T t=0)
{
... | template<typename T,
template <typename> typename Base>
struct Derived : Base<Derived<T, Base>>
{
void implementation(T t=0)
{
t = 0;
cerr << "Derived implementation----" << t;
}
};
Derived<int, Base> d;
d.interface(); // Prints "Derived implementation"
Online Demo
|
72,686,164 | 72,686,240 | Doubts about the auto keyword type deduction in C++ | Here is a code snippet I have created:
auto f = [](auto a) -> auto {
cout << a << endl;
return a;
};
cout << f(12) << endl;
cout << f("test");
Here is what I know: Types have to be all resolved / specified at compile time.
The question here is, how is the compiler behaving when it sees... | Lambda is mostly equivalent to functor class:
struct Lambda
{
template <typename T>
auto operator()(T a) const
std::cout << a << std::endl;
return a; // make auto deduce as T
}
};
f(12) would instantiate Lambda::operator()<int>
and f("test") would instantiate Lambda::operator()<const char*>... |
72,686,433 | 72,703,068 | ANSI escape code not working properly [C++] | I am using the ANSI escape code to print colored output.
I am getting proper colored output in vs code integrated terminal.
But when I am running the program in external command-prompt/Powershell, I am not getting the expected colored output.
My program looks something like this:
#define RESET "\033[0m"
#define RE... | Historically, consoles on Windows required use of the console API in the Windows SDK in order to do effects like color. But recent versions of Windows now support escape codes (and even UTF-8), but programs have to opt-in by calling SetConsoleMode with ENABLE_VIRTUAL_TERMINAL_PROCESSING. (Opting in preserves backward... |
72,686,690 | 72,686,871 | std::filesystem example not compiling on c++ 17 | I cant compile this official cpp filesystem reference example using c++ 17 clang:
https://en.cppreference.com/w/cpp/filesystem/recursive_directory_iterator
#include <fstream>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::current_path(fs::temp_directory_path());
fs::cr... | There was a defect in C++17 standard that didn't allow operator<< to be called with std::filesystem::directory_entry, reported in LWG 3171. It's now fixed as defect report, but it seems clang only fixed it in version 14: https://godbolt.org/z/3arTcGYvY. gcc seems to have backported the fix to all versions that support ... |
72,687,106 | 72,691,230 | Template for initialization of the "customer class" from Nicolai Josuttis' c++17 presentation | I just watched a presentation by Nicolai Josuttis “The Nightmare of Move Semantics for Trivial Classes”
In the presentation he shows how to build a "perfect customer class", so that it's constructor accepts up to all three arguments with as few mallocs as possible. Here are the solutions he presents:
// 11 mallocs (4cr... | template <typename Args>
Customer(Args... args) :
CustomerData{std::move(args)...}
{
}
is comparable to
Customer(std::string first, std::string last = "", int id = -1) :
first(std::move(first)), last(std::move(last)), id(id)
{}
(Which is the preferred variant from the video, but not the most efficient, as there i... |
72,687,290 | 72,687,379 | c++ overloaded (stream extraction and insertion) operator function as member function? | From c++ how to program 10th edition by deitel
//Fig. 10.3: PhoneNumber.h
//PhoneNumber class definition
#ifndef PHONENUMBER_H
#define PHONENUMBER_H
#include <iostream>
#include <string>
class PhoneNumber
{
friend std::ostream& operator<<(std::ostream&, const PhoneNumber&);
friend std::istream& operator>>(st... |
No, not for regular user defined types. The functions you made into friends in your class definition are free functions:
std::ostream& operator<<(std::ostream&, const PhoneNumber&);
std::istream& operator>>(std::istream&, PhoneNumber&);
std::basic_ostream does have some operator<< member overloads for fundamental typ... |
72,687,366 | 72,687,423 | What's the relation between `std::cout` and `std::ostream`? | I saw the code snippet below somewhere.
#include <iostream>
int main()
{
std::ostream& os = std::cout;
os << "thanks a lot" << std::endl;
return 0;
}
Since the aforementioned code snippet works well, it indicates that std::cout is derived from std::ostream. But I can't find any direct reference yet.
As ... | ostream is a class. cout is an instance of that class.
This is no different from class Person {}; Person john;. Person is the class, john is an instance of that class. The C++ standard library just happens to create an instance (cout) of this particular class (ostream) ahead of time, configured to write to the standard... |
72,687,538 | 72,693,115 | boost::regex_replace | Currently I have a problem with boost :: regex, I need to find the appropriate word և replace. with the corresponding word. My code now looks like this.
std::string name = ptap;
std::string name_regex = "\\b" + name + "\\b";
boost::regex reg(name_regex);
checks_str = boost::regex_replace( checks_str, reg, alias_name ... | You can prevent a match if there is a dot after a word:
#include <boost/regex.hpp>
#include <string>
#include <iostream>
int main()
{
std::string str = "ptap ptap.power";
std::string name = "ptap";
std::string rep = "pplug";
std::string regex_name = "\\b" + name + "\\b(?!\\.)";
boost::regex reg(reg... |
72,687,632 | 72,688,034 | How to store command output and exitcode from terminal in a variable | From here I have the code that gives me the command line output and the exit code. Unfortunately I don't understand much of that operator overloading and if I try to rewrite it to the simple code I know (with global variables i.e.) I always get the wrong exit code status of 0.
So how can I modify the following code so ... | Assuming the code provided in the article is correct and does what it should do, it is already doing all you need. The exit code and output are returned from the exec function.
You only have to use the returned CommandResult and access its members:
int main() {
auto result = Command::exec("echo blablub");
std::co... |
72,687,724 | 72,687,862 | C#: Use negative char numbers in C imported dll | I imported a DLL that I compiled with rato.hpp:
#ifndef RATO_H
#define RATO_H
extern "C"
{
__declspec(dllexport) void mouse_move(char button, char x, char y, char wheel);
}
#endif
and rato.cpp:
typedef struct {
char button;
char x;
char y;
char wheel;
char unk1;
} MOUSE... | char in C# is a 16-bit unsigned type so obviously you can't use it to interop with char in C++. sbyte is the way to go. However the range of sbyte is -128 to 127, similar to unsigned char in C when CHAR_BIT == 8, so obviously -150 can't fit in C# sbyte/C char
Note: char in C can be signed or unsigned, so if for example... |
72,687,761 | 72,690,616 | a sleek C++ variadic named test output | I've made some variadic output macros, especially for test output purposes.
Examples: C++-code // output: function file(first and last char) linenumber variable=value
L(i,b); // result e.g. {evenRCpower@ih2943: i=36 b=1 @}
L(hex,pd,dec,check.back(),even,"e.g.");
// result e.g.: {way@ih3012: pd=babbbaba check.back... |
Is there a solution needing no textual analysis, e.g. to avoid #VA_ARGS and get the names for every parameter separated?
You might do it with hard coded limit.
Some utilities MACRO to "iterate" over __VA_ARGS__:
#define COUNT_VA_ARGS(...) TAKE_10(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define TAKE_10(_1, _2, _3, ... |
72,687,797 | 72,697,141 | Output from reading text file is repeated C++ file handling | I would like to read my text file and output it exactly like in the input but the thing is, they are repeated! and the number will be either 1 or 0
My c++ code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int n, count, size = 10;
string name, ID, stamina, plusmode, type;
int main ()
{... | Here's some code that reads and prints your data file. I am assuming that your data is tab delimited, which is what your initial code implies, but you haven't explicitly stated anywhere.
int main()
{
...
int n;
string name, ID, stamina, plusmode, type;
while (data >> n) // continue reading until no more... |
72,687,892 | 72,688,160 | Question about the implementation of std::istream& operator>>(std::istream& is, icmp_header& header) | I saw such an implementation for asio::icmp_header in asio-1.22.1/src/examples/cpp03/icmp/icmp_header.hpp
class icmp_header
{
//omit several functions
friend std::istream& operator>>(std::istream& is, icmp_header& header)
{ return is.read(reinterpret_cast<char*>(header.rep_), 8); }
//omit several functions... | It is not the class definition in the header file that defines how large an ICMP header is, but it is the protocol definition. And from there it can be derived that the header is 8 octets (bytes). Therefore, it is reasonable to hard-code the size in the read() function call in order to ensure that exactly that many byt... |
72,688,090 | 72,688,312 | What is the C++2014 equivalent of the C++2017 concept std::invoke_result_t? | In my current project (Hardware Acceleration with Xilinx Vitis) I'm trying to include a header only Library which uses several C++2017 features. Xilinx Vitis however does not allow C++2017 to be used. Now since it is a header only library I tried to just create a local copy of it and replace all C++ 2017 Features with ... | The single parameter to std::result_of_t is a (very misleading1) function type. In your case it would be std::result_of_t<Fin(size_t)>.
That function type denotes a function that takes the arguments and returns the callable type that you are inspecting. For this reason it was deprecated in C++17 and removed in C++20.
... |
72,688,295 | 72,689,425 | Converting qsort function to std::sort | I currently have this comparator function that sorts a custom struct using qsort, and I want to port it to std::sort, but it seems like it needs to return a bool value instead of -1, 0 and 1, how would I rewrite it?
int tsort = 1, sorta = 1;
static auto titleSort(const void *c1, const void *c2) -> int {
switch (ts... | If possible, get rid of int tsort = 1, sorta = 1;
and use directly the appropriate method.
The dispatch, if needed, can be done with something like (C++20):
void sortTitle(std::vector<Title>& title, int tsort = 1, sorta = 1)
{
switch (tsort)
{
case 0:
std::ranges::sort(titles, std::ranges::l... |
72,689,409 | 72,689,495 | C++ Why can't I throw an abstract class? | I have a pure virtual class, BaseClass, with no data members and a protected constructor. It exists only to provide the interface for a subclass (which is templated). I want just about all the functionality implemented in the base class. Functions that operate on these typically would return BaseClass&, to allow conven... |
Why can't I throw an abstract class?
Due to [except.throw]
/3 Throwing an exception copy-initializes ([dcl.init], [class.copy.ctor]) a temporary object, called the exception object.
/5 When the thrown object is a class object, the constructor selected for the copy-initialization as well as the constructor selected f... |
72,689,494 | 72,689,599 | std::map object destructor getting called? | I have a global map object which contains an ID and a class object, but I don't understand why the destructor for the objects in the map are getting called.
#include <map>
#include <iostream>
#include <cassert>
#include <chrono>
#include <thread>
class TestMapObject{
private:
std::string m_sName;
public:
TestM... | What you see is not the std::map getting destroyed, but the temporaries you are using to insert elements in the map. You can use emplace to avoid the construction (and destruction) of that temporaries:
Test::g_tMap.emplace(Test::k_ETestMapKeyFirst,"Alice");
Test::g_tMap.emplace(Test::k_ETestMapKeySecond,"Mocha");
Live... |
72,689,542 | 72,689,866 | Should static_pointer_cast calls be std:: qualified, or relied upon ADL? | static_pointer_cast resides in std namespace. Yet it takes pointers that are also in std namespace.
So both std:: qualified calls and unqualified calls are accepted.
Which one is the right, more idiomatic way to call static_pointer_cast?
| Generally, if you know exactly which function you want to call, rather than allowing for customization, I would try to avoid ADL, implying avoiding unqualified calls.
In this case it is not expected for a library to provide its own static_pointer_cast for shared_ptrs of their own type. You always want to call the std v... |
72,690,058 | 72,690,251 | Raylib my Screen Collisions are not accurate | So I'm new to raylib and, basically, I'm trying to make a sandbox game and I am trying to make it so that when the player places a square or material when that material hits the edge of the screen it stops. Currently, my square when it falls it goes to the edge of the screen and it stops. but there's noticeable space b... | I don't really understand how this code would work at all.
But if what you mean is that the Y coordinate should be as close as possible to the edge, your if statement should be like so:
if (MousePos.y < 0) {
MousePos.y *= -1;
}
else if (MousePos.y > GetScreenHeight()) {
MousePos.y = GetScree... |
72,690,254 | 72,691,461 | Spaceship operator on arrays | The following code is intended to implement comparison on an object that contains an array. Two objects should compare as <,==,> if all array elements compare like that. The following does not compile for a variety of reason:
#include <compare>
class witharray {
private:
array<int,4> the_array;
public:
witharray( a... |
Two objects should compare as <,==,> if all array elements compare like that.
This is a fairly interesting order. One thing to note here is that it's a partial order. That is, given {1, 2} vs {2, 1}, those elements aren't all < or == or >. So you're left with unordered.
C++20's comparisons do have a way to represent ... |
72,690,333 | 72,690,512 | C++ std::max acting like std::min | When I try using the built-in max for (2, 8), and I get 2 for some reason. I also created my own functions like this:
#define min(number_1, number_2) (number_1 < number_2 ? number_1 : number_2)
#define max(number_1, number_2) (number_1 < number_2 ? number_2 : number_1)
but it still fails. Here is the code:
#include <i... | The error is that you are re-using the teleportation_start_position variable.
teleportation_start_position = min(teleportation_start_position, teleportation_end_position);
Before this line the state of your program is:
teleportation_start_position = 8
teleportation_end_position = 2
But after, it is:
teleportation_s... |
72,690,937 | 72,690,991 | why here 2 cannot implicitly convert to MyClass object? | class MyClass {
public:
MyClass(int){}
};
MyClass operator +(MyClass& lOperand, MyClass& rOperand) {
return lOperand;
}
int main() {
MyClass obj1(0);
obj1 = obj1 + 2; // 1
}
Here compiler says no match function of operator + in line 1. But I think 2 can be converted to a MyClass object as the constr... |
I think 2 can be converted to a MyClass object as the constructor of MyClass is not explicit.
The problem is that after the conversion from int to MyClass we will have a prvalue of type MyClass which cannot be bound to an lvalue reference to non-const MyClass.
Basically, an lvalue reference to nonconst type cannot be... |
72,692,099 | 72,692,233 | How can I pass a class member's fixed size array by reference? | I have a class Node that contains a fixed-size array. I have another class that creates an instance myNode and calls a function to assign 5 values to the fields in the array. I want to pass the array by reference so the function modifies the actual array and not a copy, but I can't figure out how.
Node:
class Node
{
pu... | Yes, the array is modified. A minimal reproducible example:
#include <cstdint>
#include <iostream>
class Node {
public:
uint8_t mArray[5];
};
class worker {
void doStuff(uint8_t (&arr)[5]) {
arr[0] = 12;
arr[1] = 34;
arr[2] = 56;
arr[3] = 78;
arr[4] = 90;
}
public:... |
72,692,330 | 72,692,377 | C++ Getting points between 2 points | So I have 2 points where I want to get points in between them for smoother teleport travel.
POINT a; //Character Position
POINT b; //Some random map position
I was using this formula to get a middle point first, but I want to add more points of travel before reaching POINT b.
POINT midpoint(const POINT& a, const POINT... | It's all just using proportions.
void MakePoints( const POINT& a, const POINT& b, int n, std::vector<POINT> & pts )
{
pts.clear();
pts.push_back( a );
int dx = b.x - a.x;
int dy = b.y - a.y;
for( int i = 1; i <= n, i++ )
{
pts.emplace_back( a.x + dx * i / n, a.y + dy * i / n );
}
}
|
72,692,700 | 72,692,780 | What is the actual mechanism behind the constructor initializer list? | There are cases where we must use an initializer list in order to initialize members, like when we have const data members. So, what makes an initializer list able to initialize members while the constructor itself can't?
| An initializer list always initializes all members. Full stop. Any members you fail to list have their default constructor called. If you reassign to them in the constructor body, then (in principle) you've just allocated and then immediately discarded one extra object.
In the particular case of const, a const variable... |
72,692,926 | 72,694,131 | Error using Eigen: invalid use of incomplete type ‘const class Eigen | I have the following code that works:
Matrix <float, ny+1, nx> eXX;
eXX.setZero();
Eigen::Matrix< double, (ny+1), (ny)> u;
u.setZero();
for(int i = 0; i< nx; i++){
for(int j = 0; j< ny+1; j++){
eXX(j + (ny+1)*i) = (i)*2*EIGEN_PI/nx;
u(j + (ny+1)*i) = cos(eXX(j + (ny+1)*i));
... | The Matrix class is built for linear algebra. When you want to operate over the elements of a matrix you need to the use the Array class instead. See Eigen documentation on Array.
The other way to do this is to use the unaryExpr to take each element of the matrix as an input.
Here are both methods:
#include <iostream... |
72,693,813 | 72,693,949 | Simplest way to process HTTP post data in C++ | I would like a website to send data to be stored to a database. Consequently I think I require a web server, listening to HTTP, parsing the POST, extracting the data and storing to database?
I'd like the web server to be C++.
However, I am struggling to find a simple example. I assume this is simple because we're just ... | Writing your own web server in C++ that
only supports a single HTTP connection from a single client at a time,
assumes that the incoming HTTP requests are never malformed and always in a certain format, and always of a certain type,
in the case of something unexpected happening, is not required to provide a proper HTT... |
72,694,301 | 72,694,436 | In cppreference's description of std::basic_ostream, what does "constructing and checking the sentry object" mean? | The documentation for std::basic_ostream<CharT,Traits>::write says [emphasis mine]:
Behaves as an UnformattedOutputFunction. After constructing and checking the sentry object, outputs the characters from successive locations in the character array whose first element is pointed to by s. Characters are inserted into th... | If you follow the UnformattedOutputFunction link in the text you quoted, you will find the following description of what the sentry is and what it does:
A UnformattedOutputFunction is a stream output function that performs the following:
Constructs an object of type basic_ostream::sentry with automatic storage durati... |
72,695,066 | 72,695,142 | How to insert multiple fixed objects of a class inside another class c++ | class Distance{
private: float km;
//some member functions like
//rounding off
}
class Payment{
private:
std::unordered_map<std
::string,Distance>
distancesFromAtoB;
/*e.g distancesFromAtoB [0]=.
{"chicagoToNewYork":Distance
chicagoToNewYork
(101.345)}*///does not work
// here
/... | As Stephen Newell says in the comment, use constructors
#include <unordered_map>
#include <string>
class Distance{
private:
float km;
public:
// add constructor to set members
Distance(float km):km{km}
{
}
//some member functions like
//rounding off
};
class Payment{
private:
// define map... |
72,695,497 | 72,697,444 | How is `std::cout` implemented? | std::cout is an instance of std::ostream. I can see the declaration of std::cout in a file named /usr/include/c++/7/iostream:
extern ostream cout; /// Linked to standard output
And std::ostream is defined by typedef std::basic_ostream<char> std::ostream.
What's more, it seems that you can't create an instance of ... |
how std::cout is created?
First things first, from https://en.cppreference.com/w/cpp/io/ios_base/Init :
std::ios_base::Init
This class is used to ensure that the default C++ streams (std::cin,
std::cout, etc.) are properly initialized and destructed. [...]
The header <iostream> behaves as if it defines (directly or
... |
72,695,765 | 72,695,844 | does making static inline inside namespace is redundant | is there any significance of making a variable and function inline and static inside a namespace. For example consider following 2 files:
consider first header file
// header1.h
#include <string>
#include <iostream>
namespace First
{
static inline std::string s {"hi"};
static inline void print(std::string str)... |
Do not namespace variables and functions have internal linkage, like unnamed namespace ?
No, your assumption that namespace(named namespaces) variables and functions by default have internal linkage is incorrect.
Does compiler sees two codes differently or they introduce similar behavior ?
The one with thestatic ke... |
72,696,098 | 72,696,395 | Does this function vector<int> help(257, -1); creates 257 vectors with -1 elements each? | As I am referring this code from someone else.This is the solution of longest substring without repeating elements.So why are we using only (257,-1) over here?Can we use more than 257 over here or what?
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int> he... |
Does this function vector help(257, -1); creates 257 vectors with -1 elements each?
No, it creates 1 vector with 257 values that are all initialized to -1. See https://en.cppreference.com/w/cpp/container/vector/vector constructor #3. The first parameter is count of elements, the second is the initial value for each e... |
72,696,384 | 72,696,853 | How can I deal with a fat interface? | Say I have a big interface IShape of which Circle, Square, Triangle... inherit from.
IShape has become very big, and has functions dealing with unrelated topics: for example, many for dimensions calculation, others for moving and animations, others for colouring, etc.
This is against the Interface Segregation and Singl... | One approach is to keep the object (IShape) fairly "dumb" (keeping track of its internal state only, plus boilerplate access functions) and then add free-standing functions acting on it in more involved ways. In some contexts it might be useful to integrate these functions into class interfaces of their own (particular... |
72,697,962 | 72,750,127 | Resizing window(framebuffer) without stretching the rendered content, (2D orthographic projection) | Im trying to retain the ratio and sizes of the rendered content when resizing my window/framebuffer texture on which im rendering exclusively on the xy-plane (z=0) and would like to have an orthographic projection.
Some general questions, do i need to resize both glm::ortho and viewport, or just one of them? Do both of... | I believe there were problems with my handling of FBOs as i have now found a satisfactory solution, one that also seems to be the obvious one. Simply using the width and height of the viewport (and FBO attached texture) like this:
proj = glm::ortho<float>(-zoom *viewportSize.x/(2) , zoom*viewportSize.x/(2) , -zoom*v... |
72,698,375 | 72,698,521 | Template function to wrap any function passed to it in C++ | I am trying to use libgit2, and thought it would be nice to wrap the calls with something that will throw an exception for me instead. My philosophy was that I would then be able to invoke functions that have a common return typ. I figured I would be able to do it with a templated function but I am running into some i... | To have following syntax
Git::invoke<git_branch_name>(&name, _ref);
You need (C++17)
template<auto F, typename... Args>
void invoke(Args&&... args) {
git_error_code errCode = F(std::forward<Args>(args)...);
if (errCode != GIT_OK) {
throw GitErrorException(errCode);
}
}
For c++14, you might do inst... |
72,698,425 | 72,698,517 | Undefined Reference to Time::Time(int,int,int) | An error appeared while I was testing the driver code. The compiler raised such an error:
undefined reference to Time::Time(int, int, int)
AND
undefined reference to Time::setTime(int, int, int)
Why did the Code::Blocks IDE raise this error? Is it due to the main or any declaration or definition errors? Please point o... | The problem is that you've not implemented the constructor Time::Time(int, int, int) in your source file.
To solve this just add a definition for Time::Time(int, int, int).
TIME.CPP
//implmentation for constructor that was not there before
Time::Time(int phour, int pminute, int psecond): hour(phour), minute(pminute), s... |
72,699,309 | 72,699,823 | Why does cin.fail() ignore periods and commas in "while" loop? What's a simple way to error check input? | Sorry it sounds stupid, but I'm just getting started in C++ programming...
My input checking loop works fine if I want it to accept 'float' numbers, but outputs some weird results if it has to accept only 'int' numbers.
EDIT: Tutorials I read/watched assumed that user wouldn't input things like that, which is dumb...
#... | cin read '5'-> integer -> get -> cin read '.' -> not integer -> not get -> n = 5 -> recall func -> cin read '.' -> not integer -> invalid -> cin fail
if you write like this:
int a;
cin >> a;
double b;
cin >> b;
cout << a << " " << b;
with input 5.5, the output will be 5 0.5.
If you want check if your input is inte... |
72,701,129 | 72,701,232 | A constexpr function that calculates how deep a std::vector is nested | Is there a way to write a constexpr function that returns how deep a std::vector is nested?
Example:
get_vector_nested_layer_count<std::vector<std::vector<int>>>() // 2
get_vector_nested_layer_count<std::vector<std::vector<std::vector<float>>>>() // 3
| The easy way is to use recursion
#include <vector>
template<class T>
constexpr bool is_stl_vector = false;
template<class T, class Alloc>
constexpr bool is_stl_vector<std::vector<T, Alloc>> = true;
template<class T>
constexpr std::size_t get_vector_nested_layer_count() {
if constexpr (is_stl_vector<T>)
return 1... |
72,701,223 | 72,701,573 | (non)ambiguous static overload within templated class | My class template NodeMaker has 3 static member function templates called create_node which are distinguished by their argument(s) using C++20 concepts. When calling NodeMaker<>::create_node(x) from main() everything works as I intended, but when calling create_node from another member function, GCC claims ambiguous ov... | This seems to be a gcc bug. Here is the submitted bug report.
It seems that gcc requires the call to the static method create_node to be explicitly qualified with NodeMaker<>:: even from inside the non-static member function do_something.
You can confirm that this is the case by adding NodeMaker<>:: and you'll see that... |
72,701,502 | 72,709,441 | How to declare a policy class that does nothing to a string, has consistent signature with other policies and is evaluated at compile-time | I am putting together a set of policy classes that operate a number of operations to a string. I would like these policies to be exchangeable, but the "do nothing" policy is problematic too me, as:
I don't see how to avoid copy using move semantic while maintaining the same (non-move) interface with the sister policie... | What you want here is reduce unnecessary copy and don't use std::move when calling edit. Why not just return a const reference?
struct identity
{
static const std::string& edit(const std::string& s) {
return s;
}
};
std::string s = "my_string[this is a comment]";
assert(remove_comments_of_depth<0>::edi... |
72,702,026 | 72,735,797 | Pybind11 cv::Mat from C++ to Python | I want to write a function that gets an image as parameter and returns another image and bind it into python using pybind11.
The part on how to receive the image as parameter is nicely solve thanks to this question.
On the other hand, the returning image is a bit tricky.
Here my code (I try flipping the image using a c... | Yes it indeed is a problem with py::buffer_info, the strides to be more precise
Instead of:
{ cols * sizeof(uint8_t), sizeof(uint8_t), 3 }
The strides should be:
{ sizeof(uint8_t) * cols * 3, sizeof(uint8_t) * 3, sizeof(uint8_t)}
|
72,702,138 | 72,703,125 | Qt cannot write to file. File exists, isn't open, "Unknown error" (Windows OS) | Would really appreciate your help. I'm new to Qt and C++.
I managed to get this working previously, but for some reason am no longer able to do so. I haven't touched anything to do with the writing of files, but all functions pertaining to file writing no longer seem to function. Here's an example of one of the simpler... | You can not write to a Qt resource. If you want to update/write to a file you should put the file into a writeable filesystem. To e.g. place it in the appdata folder you can use QStandardPaths::writeableLocation(QStandardPaths::ApplicationsLocation)
|
72,702,243 | 72,702,331 | Creating a very basic calculator in C++ | I'm extremely new to C++, I was following a tutorial and wanted to go a bit off what the course said, I attempted to make a basic calculator that instead of just being able to add could subtract, divide and multiply but it still seems to only be able to add, why is this?
int num1, num2;
double sum;
int addType;
... | You are creating new variable in if condition part, update condition part to check if it is equal to something with addType == x
int num1, num2;
double sum;
int addType;
cout << "Type a number: ";
cin >> num1;
cout << "Type a second number: ";
cin >> num2;
cout << "Do you want to 1. add, 2. subtract, 3. divide o... |
72,702,485 | 72,702,612 | Function style casting using the `new T()` operator in C++ | Here is an example of a simple function style casting done by int(a):
float a = 5.0;
int b = int(a);
More info from cpprefrenece:
The functional cast expression consists of a simple type specifier or a typedef specifier followed by a single expression in parentheses.
I have 2 questions:
1) would using the new operat... |
would using the new operator still count as a functional cast?
No, the use of the new operator(like you used in your example) is not a use case of functional cast.
test t = test(1, 2); isn't because it has more than 1 expression in parenthesis?
Both test t = test(1); and test t = test(1,2); are copy initialization... |
72,702,574 | 72,709,859 | Does bitfield count as common initial sequence with a whole int of the same type? | I was wondering if the following was valid C++:
union id {
struct {
std::uint32_t generation : 8;
std::uint32_t index : 24;
};
std::uint32_t value;
};
I want this so I can access both generation and index separately, which keeping access to the whole number. Since they all are std::uint32_t... | By resolution of CWG 645 (for C++11; not sure whether it is supposed to apply to C++98 as DR) the common initial sequence requires corresponding non-static data members or bit-fields in the two classes (by declaration order) to either be both bit-fields (of the same width) or neither be bit-fields.
The wording for that... |
72,702,684 | 72,703,386 | Is there any other way besides MAPI to know two different email addresses belong to one Outlook account? | I am trying to integrate my application with Outlook. I have referred to Integrating IM applications with Office.
I met an issue when an Outlook/Office account has two different email addresses, Outlook will call the IContactManager.GetContactByUri() API twice with the two email addresses. Because I don't know the two ... | For an Exchange account, multiple proxy addresses are stored in the PR_EMS_AB_PROXY_ADDRESSES MAPI property (DASL name http://schemas.microsoft.com/mapi/proptag/0x800F101F), which can be accessed in Outlook Object Model using AddressEntry.PropertyAccessor.GetProperty.
|
72,702,736 | 72,703,242 | Is there a better way to generic print containers in C++20/C++23? | I use the following code to print generic C++ containers and exclude strings (thanks to this SO answer).
#include <iostream>
#include <vector>
template <typename T,
template <typename ELEM, typename ALLOC = std::allocator<ELEM>>
class Container>
std::ostream &operator<<(std::ostream &out, const Con... | With concepts, you might require only container/range types and discard
string-like types, something like:
template <typename Container>
requires std::ranges::input_range<const Container>
&& (!std::convertible_to<const Container, std::string_view>)
std::ostream &operator<<(std::ostream &out, const Container& conta... |
72,703,052 | 72,703,130 | Why the output is "abBA"? | I have this code:
#include <iostream>
class A
{
public:
A() { std::cout << 'a'; }
~A() { std::cout << 'A'; }
};
class B
{
public:
B() { std::cout << 'b'; }
~B() { std::cout << 'B'; }
A a;
};
int main() {B b; }
Why is it creating object A a; is done before executing B b; arguments?
Is there a pr... | Class members are initializing before executing the constructor of B. Same as:
B() : a() { std::cout << "B"; }
|
72,703,255 | 72,703,319 | Unable to Allocate large cpp std::vector that is less than std::vector::max_size() | I am trying to allocate a vector<bool> in c++ for 50,000,000,000 entries; however, the program errors out.terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc (or in the online compiler it just ends).
I initially thought this was due to too large a size; however, v1.maxsize() is great... | From std::vector::max_size:
This value typically reflects the theoretical limit on the size of the
container, at most std::numeric_limits<difference_type>::max(). At
runtime, the size of the container may be limited to a value smaller
than max_size() by the amount of RAM available.
This means that std::vector::max_si... |
72,704,422 | 72,704,583 | how to return a dynamic char array from function C++ | I dont really understand pointers and how to call and create dynamic arrays despite spending the time to educate myself on them and I am running into an error on the following line:
char *dArray = alphabet(N);
Here on my instructions and what Im trying to do:
The program first asks user to enter the number of element... | you have declared the return type wrong. it should be char *
char *alphabet(int N) // <<<<====
{
char *dArray;
dArray= new char[N+1];
dArray[N]= '\0';
int i;
srand(time(NULL));
for (i=0; i<N; i++)
{
int r = rand()%26;
char letter='a'+r;
cout<<"dArray["<<i<<"] is: "<< ... |
72,705,340 | 72,705,623 | Effective way of finding GCD of 2 numbers using recursive approach | I have been recently solving a problem to find GCD/HCF of two numbers using Recursion. The first solution that came to my mind was something like given below.
long long gcd(long long a, long long b){
if(!(a - b) return a;
return gcd(max(a, b) - min(a, b), min(a, b));
}
I saw other people's solutions and one app... |
What is the difference between the Time Complexities of these two programs?
If you are talking about the time complexity, then you should consider the big-O notation. The first algorithm is O(n) and the second one isO(logn), where n = max(a, b).
How can I optimise the former solution?
In fact, the second algorithm ... |
72,705,449 | 72,747,798 | Visual Studio Won't Update C++ Version | I am trying to use the <filesystem> library, and for that I need C++17 or later. I went to the project properties, to General, then to "C++ language standard", and set the language to C++20. But when I compile, it says that the library is only available with C++17 or later, and doesn't let me use it.
I went to the <fil... | As I already suspected in the comments and as confirmed by the OP, the problem was that the OP changed the properties for a configuration and/or platform which was not the currently active one. It is quite easy to forget to select the desired one in the properties dialog since the combo boxes in the properties are not ... |
72,706,198 | 72,706,295 | Printing a type in a namespace via {fmt} and ostream | This answer mentions how you can include <fmt/ostream.h> to have ostream-printable types recognized by {fmt}. I noticed that it doesn't work when the type is in a namespace:
#include <fmt/format.h>
#include <fmt/ostream.h>
namespace foo {
struct A {};
}
std::ostream& operator<<(std::ostream& os, const foo::A& a)
{
... | By argument-dependent lookup, it's required to put the operator<< definition inside the foo namespace:
#include <fmt/format.h>
#include <fmt/ostream.h>
namespace foo {
struct A {};
std::ostream& operator<<(std::ostream& os, const A& a)
{
return os << "A!";
}
} // namespace foo
int main()
{
fmt::print("{}\n", foo... |
72,706,224 | 72,706,812 | How do I reverse the order of the integers in a `std::integer_sequence<int, 4, -5, 7, -3>`? | Sometimes I want to reverse the values in an index_sequence and use the result to reverse the values in something tuple-like, like in this illustration which reverses the values in a constexpr std::array at compile time.
#include <array>
#include <cstdint>
#include <utility>
namespace detail {
template <class T, std::... | A solution that doesn't use std::tuple is to convert to an std::array and access the corresponding indices with the help of std::make_index_sequence.
namespace detail {
template<typename T, T... N, std::size_t... Indices>
constexpr auto reverse_sequence_helper(std::integer_sequence<T, N...> sequence,
... |
72,706,624 | 72,706,672 | Possible strict aliasing violation? | I was scrolling through some posts and I read about something called the strict aliasing rule. It looked awfully close to some code I've seen in a club project, relevant snippet below.
LibSerial::DataBuffer dataBuffer;
size_t BUFFER_SIZE = sizeof(WrappedPacket);
while(true) {
serial_port.Read(dataBuffer, sizeof(Wr... | Yeah, it's a violation. The rule lets you use raw byte access (char*, unsigned char*, std::byte*) to access other data types. It doesn't let you use other data types to access arrays of raw bytes.
The solution is memcpy:
WrappedPacket wpkt;
std::memcpy(&wpkt, dataBuffer.data(), sizeof wpkt);
|
72,706,894 | 72,707,195 | Why can I use curly brackets to initialize one enum class with a value from another enum class? | I have found the following behavior of Clang-12, Clang-13 and Clang-14 with c++17 standard:
enum class FOO {
VALUE
};
enum class BAR {
VALUE
};
FOO value1{BAR::VALUE}; // OK
FOO value2 = BAR::VALUE; // Error
Why is there a difference? I would expect enum class to be 100% type safe.
Compiler Explorer
| This is CWG issue 2374.
In C++17, before the resolution of this issue, direct-list-initialization of an enumeration with a fixed underlying type by a single expression was specified to always be equivalent to a functional style cast. A functional style cast then would be equivalent to a static_cast and that would actua... |
72,707,337 | 72,707,621 | How can I decide if I want to return a pair with an integer key or string key inside a template function | I'm trying to figure out what type the template currently is, I have looked in stackoverflow but did not find a solid answer. Basically I want to create an #if #else #endif and depending on the type of the template put code.
Here is my code
#include <map>
#include <iostream>
template <typename T>
#define IS_INT std::i... | Whenever I need some type_traits from newer C++ standards, I steal them and adapt them to the older standard (if needed).
Example:
namespace traits98 {
struct false_type { static const bool value; };
const bool false_type::value = false;
struct true_type { static const bool value; };
const bool true_type::value = true... |
72,707,516 | 72,707,562 | Using an unique_ptr as a member of a struct | So I have a struct like this:
struct node {
node_type type;
StaticTokensContainer token_sc;
std::unique_ptr<node> left; // here
std::unique_ptr<node> right; // and here
};
When I tried to write a recursive function to convert a node to string for printing like this:
std::string node_to_string(node... | you pass node by value, and you cannot set one std::unique_ptr equal to another:
int main() {
std::unique_ptr<node> a = std::make_unique<node>();
std::unique_ptr<node> b = a; //Error C2280
}
because who is now the unique owner of the data?
To fix your error, simple take a const reference in your function. Thi... |
72,708,798 | 72,709,956 | shrink and grow an object using cos and time in vertex shader | so here is my problem. I have to make a rabbit grow and shrink using a time variable and a cos() I managed to pass the time variable to my vertex shader but I have absolutely no idea how to make the rabbit grow or shrink. I try some formula that I find on the internet but none works I will show the code where I pass my... | You have to scale the vertex coordinate:
float scaleFactor = 0.2 * (cos((2 * PI) / time * 100) + 2.0);
gl_Position = Proj * View * Model * vec4(Position * scaleFactor, 1.0);
However, I suggest to scale the model transformation matrix on the CPU:
glm::mat4 modelMatrix = glm::scale(o->frame()->getModelMatrix(), glm::vec... |
72,709,043 | 72,709,119 | Dynamic macro-selection in a loop | I have a header file 'a.h' with some macro-definitions of the type:
Header 'a.h' contents:
#define STREAM1 cout
#define STREAM2 cerr
#define STREAM3 some_out_stream3
#define STREAM4 some_out_stream4
...
#define STREAM100 some_out_stream100
Now in a different c file which includes the above header, I need to use the ab... | Put all the macros in an array and loop over them.
std::ostream streams[] = {STREAM1, STREAM2, ...STREAM100};
for (int i = 0; i < std::size(streams); i++) {
streams[i] << some_text_method(i+1);
}
|
72,709,133 | 72,709,178 | __declspec(align(#)) equivalent with i686-w64-mingw32-g++ compiler | Hello I'm doing a MASM course and there is also C++ but the teacher is using Visual Studio and I'm using Linux.
In the code I'm doing there is the following instructions:
__declspec(align(#))
I have this code:
_desclspec(align(16))XmmVal a;
_desclspec(align(16))XmmVal b;
_desclspec(align(16))XmmVal c[2];
But I cannot... | The issue isn't "Windows vs. Linux" as much as "choice of compiler".
Here's the documentation for MSVC. Note the caveat about "MSVS 2015 and later":
https://learn.microsoft.com/en-us/cpp/cpp/align-cpp
In Visual Studio 2015 and later, use the C++11 standard alignas
specifier to control alignment. For more information,... |
72,710,346 | 72,710,516 | How to use std::format to format all derived class of the same base class? | I have lots of classes derived from the same base class, and I'm trying to avoid writing a formatter for all derived classes. I tried to only implement the std::formatter for the base class, but passing a derived class object/reference to std::format will trigger compile errors.
C:\Program Files\Microsoft Visual Studi... | Base and D1 are different types. A more appropriate way should be to use constrained templates
#include <concepts>
#include <format>
template<std::derived_from<Base> Derived, typename CharT>
struct std::formatter<Derived, CharT> : std::formatter<std::string> {
template<typename FormatContext>
auto format(Derived& ... |
72,711,521 | 72,715,937 | Win11 22H2 Programmatically switch between predefined power modes (Best power efficiency/Balanced/Best performance) | How do you programmatically switch between predefined power modes (Best power efficiency/Balanced/Best performance) in Win11 22H2?
Is this still possible given that Microsoft is now removing all Sleep/Screen off overrides?
| You can use Powercfg command-line options
Setting the "Super performance" scheme active:
powercfg /setactive ac093644-6503-4314-b3b6-0b601924e3e9
A detailed tutorial can be found here:
https://www.windowscentral.com/how-use-powercfg-control-power-settings-windows-10
And of course, you can set all values in the registr... |
72,711,708 | 72,721,031 | How to pass wide characters to libcurl API which takes only const char*? | I'm using libcurl to upload some files to my server. I need to handle files whose names are in different languages e.g. Chinese, Hindi, etc. For that, I need to handle files using std::wstring instead of std::string.
libcurl has a function with a prototype like below:
CURLcode curl_mime_filename(curl_mimepart *part, co... | curl_mime_filename is not suitable for
files whose names are in different languages e.g. Chinese, Hindi, etc.
It is suitable for ASCII and UTF-8 file name encodings only.
The job of curl_mime_filename is:
Detect the data content type, for example file.jpg → image/jpeg.
Add the multipart header Content-Disposition, f... |
72,711,720 | 72,725,085 | Is there a way to show tool tips for QRubberBand? | I am trying to set a tool tip for QRubberBand. This is how the constructor of the parent looks. Please note the parent is not a window, but rather a widget of a window.
roiRB = new QRubberBand( QRubberBand::Rectangle,this);
roiRB->setGeometry(QRect(QPoint(1,1), QPoint(100,100)));
roiRB->setAttribute(Qt::WA... | On digging the source code of QRubberBand, I found out that in the constructor of QRubberBand, the attribute (Qt::WA_TransparentForMouseEvents); is set to true. Manually setting this back to false fixed the issue.
From what I see, tooltips work on MouseEvent calls of the widget, if the this attribute is set to true, t... |
72,712,115 | 72,712,883 | std::chrono::system_clock::now() serialization | How can I serialize the result of std::chrono::system_clock::now() so I can then load it and compare it with a later timestamp?
I tried to serialize in the following way:
std::to_string((uint64_t)std::chrono::system_clock::now().time_since_epoch().count())
Then to unserialize it:
std::chrono::milliseconds t(<uint64 nu... | As noted, time_since_epoch is not necessarily in milliseconds. If you want to serialize milliseconds, use duration_cast. Otherwise something like this should work:
using clock_t = std::chrono::system_clock;
clock_t::time_point tp = clock_t::now();
std::string serialized = std::to_string(tp.time_since_epoch().coun... |
72,712,318 | 72,713,395 | converting to ‘A’ from initializer list would use explicit constructor ‘A::A(int)’ | I am trying to migrate an old C++03 codebase to C++11. But I fail to understand what gcc is warning me about in the following case:
% g++ -std=c++03 t.cxx
% g++ -std=c++11 t.cxx
t.cxx: In function ‘int main()’:
t.cxx:8:21: warning: converting to ‘A’ from initializer list would use explicit constructor ‘A::A(int)’
8... | The given program is ill-formed for the reason(s) explained below.
C++20
B is an aggregate. Since you're not explicitly initializing a, dcl.init.aggr#5 applies:
For a non-union aggregate, each element that is not an explicitly initialized element is initialized as follows:
5.2 Otherwise, if the element is not a refe... |
72,712,405 | 72,712,584 | C++: Is it possible to use a function of a class from outside? | Is there any way to use a class member function from outside?
As far as I know for this it would be necessary to somehow inject a private component into it.
For example (this is just an example the notFooClass function does not compile):
class FooClass{
private:
int i;
public:
FooClass(int x){
this->i =... | public methods can be called from outside. Thats what they are for.
notFooClass creates an instance and calls a member function. Thats basically the same as you do in main. The difference is only that you are using an unnamed temporary and wrong syntax:
int notFooClass(int num1, int num2){
return FooClass(num1).f(n... |
72,712,601 | 72,713,380 | Templated requires clause fails | I have a set of classes roughly defined as follows:
template <typename U>
class Iterable {
// More code
};
class Container : public Iterable<Element> {
// More code
};
class Tuple : public Container {
// More code
};
class List {
public:
template <typename I, typename T>
requires std::is_bas... | Your example won't work because there is no way to deduce the type of T.
If you want to constrain I to inherit from base class Iterable<U> for some type U, you might want to do
template <typename U>
class Iterable { };
template<typename T>
concept derived_from_iterable = requires (T& x) {
[]<typename U>(Iterable<U>&... |
72,713,158 | 72,714,213 | C++20 Constraints - Restrict typename TFunction to be a function (with certain signature) | How to translate this TS Code into modern C++20 using lambdas and modern templating features?
[Edit]: The main question here is: How to restrict typename TFunction to be of type Function or even a more specific function with a given signuature?
interface Subscription<TFunction extends Function> {
readonly subscriber:... | Function types in C++ are expressed as types like R(Arg1, Arg2, Arg3) (denoting a function that takes three arguments of types Arg1, Arg2, Arg3 and returns an R). You can take a pointer to such a function, which has the type R(*)(Arg1, Arg2, Arg3).
A template will typically use one type parameter for R and a parameter ... |
72,713,652 | 72,713,872 | Deduce Function Arguments From A Function Type Declare, For Templated Struct Method? | I was wondering if it was possible to deduce the return type, and parameters from a function type define.
I was hoping to do something similar:
template<class T>
struct _function_wrapper_t
{
[return of T] call([Args of T]....)
{
return (T)m_pfnFunc(Args);
}
void* m_pfnFunc;
};
int MultiplyTwoN... | The simple solution is to let the compiler deduce return type and let the caller pass the right types (and fail to compile when they don't):
template<class T>
struct _function_wrapper_t
{
template <typename ...U>
auto call(U&&... t)
{
return m_pfnFunc(std::forward<U>(t)...);
}
T m_pfnFunc;
... |
72,713,796 | 72,722,468 | Problem while linking a static library during compilation in MinGW, why? | I am trying to compile a simple project which uses one of my headers. I am on Windows and I am using MinGW-W64-builds-4.3.5 Suppose the project is called test.cpp and I want to compile it using my headerosmanip which requires also the linking of its created static library libosmanip.lib. The static library has been com... | I finally solved the issue. The problem was related to the fact the the suffix of my library was .lib. By changing it in .a and rebuilding the library passing the correct static library name to the ar command the problem disappeared.
|
72,713,971 | 72,728,392 | In C++, how to correctly obtain a shared pointer to a vector , minimizing the number of copy constructor calling? | I need a function which returns a shared_ptr to a vector containing a large number of objects. The following code realizes this but one can see that copy constructors are called for an extra number of times.
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class A {
public:
int IA ;
... | There are two usages in your code that cause extra copying.
myA.push_back(A(10)) will create a temporary object of class A, which is then copied into the vector myA. Note that we cannot reduce such duplication by changing to myA.emplace_back(A(10)). It will also creates a temporary A object, and then calls the constru... |
72,714,020 | 72,714,365 | C++ share atomic_int64_t between different process? | I am using C++ multi-processing passing data from one to another using shared memory.
I put an array in the shared memory. Process A will copy data into the array, and Process B will use the data in the array. However, process B need to know how many item are in the array.
Currently I am using pipe/message queue to pas... | Atomics will work, for the most part. Some caveats:
Only use lock-free atomics. See Are lock-free atomics address-free in practice?
Obviously pointers won't work, for example std::atomic<std::shared_ptr<T>>
std::atomic<T>::wait, and notify_one/all may not work
Technically, the behavior is non-portable (and lock-free ... |
72,714,058 | 72,714,163 | Does the stack implementation that's part of the C++ STL have a capacity? | I learned in my college DSA course that a stack is initialized with a capacity that limits the number of elements it can contain. But when I create a stack using the STL, you don't have to define a capacity. Is there a capacity involved, or does it not apply in the STL implementation? Do stacks even really need a capac... | The stack implementation you looked at in your course may have had a limit, but that's not essential to being a stack. (And your course really should have taught you this.)
The C++ standard library stack is just an adapter for any underlying collection that supports the necessary operations, so whether it has a limited... |
72,714,268 | 72,720,810 | OMP reduction for loop with std::map | I want to parallelise the following for loop with a std::map with OpenMP 4.0:
int n=5000;
int nbin;
std::map<int, int> histogram;
for (int i = 1; i < n; i++)
{
.
.
nbin =....... \\some calculation with integer result
++histogram[nbin];
}
... | Ok, toy example counting characters in a string:
string text{"the quick brown fox jumps over the lazy dog"};
charcounter<char,int> charcount;
#pragma omp declare reduction\
( \
+:charcounter<char,int>:omp_out += omp_in \
) \
initializer( omp_priv = charcounter<char,int>{} )
#pragma o... |
72,714,516 | 72,714,983 | Call function in C++ dll from C# | I'm trying to call a function in a C++ dll, from C# code.
The C++ function :
#ifdef NT2000
__declspec(dllexport)
#endif
void MyFunction
( long *Code,
long Number,
unsigned char *Reference,
unsigned char *Result ... | long in C maps to int in C#. And char is ANSI, so you need to specify UnmanagedType.LPStr. The Result appears to be an out parameter, for which you will need to pre-assign a buffer (size unknown?) and pass it as StringBuilder
[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern voi... |
72,714,763 | 72,714,938 | Array changes it's values inside a function but other variable don't | #include <iostream>
using std::cout;
using std::cin;
using std::endl;
void func(int arr[5], int n1, int n2)
{
cout << "INSIDE func()" << endl;
arr[0]++, arr[3]++;
for(int i = 0; i < 5; i++)
{
cout << arr[i] << ' ';
}
cout << endl;
n1++, n2++;
cout << n1 << ' ' << n2 << endl;... | This function declaration
void func(int arr[5], int n1, int n2);
is adjusted by the compiler to the declaration
void func(int *arr, int n1, int n2);
That is parameters having array types are adjusted by the compiler to pointers to array element types.
On the other hand, this call
func(arr,a,b);
is equivalent to the... |
72,715,323 | 72,716,577 | Output not matching the expected output for almost palindrome program in C++ | I can't find any error in my code for an almost palindrome. The statement
'r = isPalindrome(str, p[0], p[1]-1);'
is not getting executed while the function calls for p&q are getting executed fine. It prints values of only p & q. Can someone please explain what is wrong with the flow of the program?
#include <iostream>
... | Lets assume you are right and the function isn't execute and lets find out why the compiler might optimize it in such a way that the function call is not needed:
int* isPalindrome(string &s, int i, int j) returns a pointer to the global array arr or NULL and other than writing to arr it has no side effect.
Lets analyze... |
72,715,968 | 72,716,182 | std::move with polymorphic move assignment operator and memory safety | I was wondering if the following code was safe, considering the child object is implicitly converted to type Parent and then moved from memory. In other words, when passing other to Parent::operator=(Parent&&) from Child::operator(Child&&), is the entire object "moved" with the parent call, or just the underlying Paren... | What you are doing is safe. You are just passing a reference to the base-class subobject to the base assignment operator. std::move doesn't move anything. It just makes an xvalue out of an lvalue, so that a rvalue reference may bind to it. The binding here is to a subobject because Parent is a base class type of Child.... |
72,715,987 | 72,727,895 | creating UML or class diagram manually from existing project | Is there anyway to build manually a class or UML diagram from some part of existing code in Visual Studio Professional? Assume there are plenty of project and classes. Can i manually select some of the classes (with only some of its base/derived classes and member functions) I am interested in, and they are automatical... | You can install the Class Designer component.
In addition, UML Designers have been removed.
|
72,716,773 | 72,717,230 | eigen bind matrix row/column to vector l-value reference | How can i pass a column (or row) of a Matrix to a function as an l-value Vector reference?
Here is an example for dynamically allocated matrices:
#include "eigen3/Eigen/Eigen"
void f2(Eigen::VectorXd &v) {
v(0) = 0e0;
}
void f1(Eigen::MatrixXd &m) {
if (m(0,0) == 0e0) {
// both calls below fail to compile
... | This is what Eigen::Ref is designed to do.
void f2(Eigen::Ref<Eigen::VectorXd> v) {
v[0] = 123.;
}
void f1(Eigen::Ref<Eigen::MatrixXd> m) {
m(1, 0) = 245.;
}
int main()
{
Eigen::MatrixXd m(10, 10);
f1(m);
f2(m.col(0));
assert(m(0,0) == 123.);
assert(m(1,0) == 245.);
// also works with part... |
72,717,084 | 72,718,543 | Pushing non dynamically allocated objects to a vector of pointers | I've been trying to figure out this issue while I was coding on Codeblocks but didn't have any luck.
So basically I have the following code inside a function:
Node * newNode;
newNode->data = num;
//root is defined somwhere at the top as 'Node * root';
root->adj.push_back(newNode);
and the following struct:
struct Node... | "Traversing" pointers that are not pointing at objects is undefined behavior in C++.
The pointer doesn't have to point at a dynamically allocated object, but that is typical. The pointer could point at an automatic storage object. For example:
Node bob;
Node* root = &bob;
however, in every case, you are responsible ... |
72,717,228 | 72,718,637 | C++ std features and Binary size | I was told recently in a job interview their project works on building the smallest size binary for their application (runs embedded) so I would not be able to use things such as templating or smart pointers as these would increase the binary size, they generally seemed to imply using things from std would be generally... | This question probably deserves more attention than it’s likely to get, especially for people trying to pursue a career in embedded systems. So far the discussion has gone about the way that I would expect, specifically a lot of conversation about the nuances of exactly how and when a project built with C++ might be mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.