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 |
|---|---|---|---|---|
66,275,744 | 66,279,783 | Is there a proposal for ? operator / null-conditional operator for C++? | Rust has a ? operator for error propagation without exceptions. When a function returns a Result or Option type, one can write:
let a = get_a()?;
Which effectively means:
let _a = get_a();
let mut a = match _a {
Ok(value) => value,
Err(e) => return Err(e),
}
Or, in other words, if the returned value contains ... | There is no such proposal. Nor is there likely to be one in the immediate future. The C++ standard library does not even have value-or-error types at the moment, so having an operator whose sole purpose is to automatically unpack such types seems very cart-before-the-horse.
At present, the C++ committee seems more inte... |
66,275,816 | 66,277,175 | How to use std::ostringstream to check the output? | I made code below to check the output.
ostringstream oss;
Fraction f12{1, 2};
oss << "fraction f12 is " << f12 << '\n';
string result = oss.str();
cout << result << '\n';
std::string expected{ "fraction f12 is 1/2\n" };
cout << expected << endl;
if(oss.str() == expected)
cout << "The... | You didnt not post all the code. In particular, the code that makes the two strings different is missing. However, looking at the output, we can see that result has two \n while expected has only one (in the output we see one line break more due to the endl/\n when you print the two).
I suppose your << for Fraction has... |
66,275,826 | 66,275,884 | Container with different data types: 2 approaches, only one compiles. Why? | I have a question in the hope that someone here might help me understand that issue. I am currently trying to build a code that needs a container with different types. I have found a formulation that works fine but only after having started out with a slightly different formulation that does not compile. And I do not u... | The problem is very likely this:
v1.emplace_back(myCircle);
v1.emplace_back(myCircle);
This will create two different std::unique_ptr<segment>> objects, both using the exact same pointer to the exact same object. This breaks the unique part of the std::unique_ptr.
When the first element is destructed the second becom... |
66,276,037 | 66,276,742 | Qt Quick - How to use setContextProperties() | I want to try out rootContext()->setContextProperties() instead of rootContext()->setContextProperty() because I read it is more efficient to bundle the properties instead of setting them X-times by yourself. Unfortunately I cannot find any good ressource on how to use it.
So e.g. in the main.cpp I have
ClassA a;
Class... | This struct contains a property name and a property value. You can add multiple properties as a collection.
QSharedPointer<QQmlApplicationEngine> m_engine;
QQmlContext* m_ctxt;
m_engine->clearComponentCache();
m_engine.reset(new QQmlApplicationEngine, &QObject::deleteLater);
m_ctxt = m_engine->rootContext();
m_ctxt->se... |
66,276,239 | 66,276,300 | printf() and cin interaction | I want to get string by cin>> and then I'd like to print it by printf. But printf is giving some unexpected result. How can I fix it?
string *planet;
planet = new string;
cout << "Enter planet name:"<<endl;
cin >> *planet; //Saturn
cout<< *planet<<endl; //Saturn
printf("Your planet is %s",plan... | string is not an array, it is a class. Do not use it like a pointer. To get a C-style string, use c_str():
string planet;
cin >> planet;
printf("Your planet is %s",planet.c_str());
cout<< planet[2]<<endl;
|
66,276,546 | 66,276,634 | Function pointer in a std::thread Args... list | I am trying to give a function pointer to my std::thread arguments list but I get a bunch of compile errors that I don't understand (@ MSVC\14.28.29333\include\thread(43,14): error C2672: 'invoke' : fonction correspondante surchargée introuvable [overloaded function not found]).
I could write a mcve that gives that sam... | The problem is that your function accepts the argument by non-const lvalue reference. std::thread will pass an rvalue into the funtion, and the non-const lvalue reference cannot be bound to rvalues.
In order to pass an lvalue, you must use a reference wrapper:
std::thread t1(worker<T>, std::ref(data_set), do_something)... |
66,276,719 | 66,276,888 | Strange behaviour of TCP-connection | We have the following configuration: Server, Client, DHCP-Server. The server runs on a static IP in "client mode". This means, that server has a list of all clients (hostnames) and builds TCP-connections. Clients have dynamic IPs.
How does it working: 1) Server creates a connection to a client and 2) Server waits for a... | I assume in step 3 you only send a heartbeat message to the client but do not actually wait for a response from the client on that heartbeat message.
The socket send() function only forwards the data to the OS. It does not mean that the data is actually transmitted or has been received by the peer.
The OS buffers data,... |
66,276,956 | 66,296,418 | Does passing multiple devices to a context, mean kernels will be distributed to both devices? | I've been writing some basic OpenCL programs and running them on a single device. I have been timing the performance of the code, to get an idea of how well each program is performing.
I have been looking at getting my kernels to run on the platforms GPU device, and CPU device at the same time. The cl::context construc... | I did some testing on my system. Indeed you can do something like this:
using namespace cl;
Context context({ devices[0], devices[1] });
queue = CommandQueue(context); // queue to push commands for the device, however do not specify which device, just hand over the context
Program::Sources source;
string kernel_code = ... |
66,277,050 | 66,314,349 | returning derivatives with boost odeint | I am using boost odeint to integrate 2n coupled equations. My basic question is quite general. How can I return not only the states x_i for each time step using the observer but also return the derivatives d(x_i)/dt? I know how to return the state or some function of the state at a given time, but I don't know how to ... | A minimal example on what I mean with my comment
You would have to call the system function from inside the observer to get the derivatives values for the state. That is, pass the system object via the constructor of the observer, provide the return object and just call the function and evaluate the results.
This is ... |
66,277,198 | 66,277,219 | Use of unique_ptr with overloaded constructor | I have a question on how to use unique_ptr together with an overloaded constructor.
Here is my class definition:
class circle : public segment
{
public:
circle()
{
center.x = 0;
center.y = 0;
};
circle(const double r, const point c)
{
radius = r;
center.x = c.x;
... | It should be
auto /* std::unique_ptr<circle> */ myCircle = std::make_unique<circle>(radius1, center1);
|
66,277,436 | 66,281,053 | Access field value raw bytes from a constructed Flatbuffer | Say I have following Flatbuffer definition compiled to C++.
table ParentObj { // this is the root table
timestamp:uint64;
child:ChildObj
}
table ChildObj {
...some fields...
}
I build a ParentObj (which includes the ChildObj) with Flatbuffer builder and send the final bytes over the network to another par... | No, because ChildObj is not necessarily contiguous in the buffer. It refers to a vtable (which may or may not be shared), and any sub-string/vector/table is an offset that may point to a non-adjacent part of the buffer.
Typically, you use nested_flatbuffer to store children that need to be treated as their own isolated... |
66,277,567 | 66,284,321 | What is wrong with my program to find the longest word in a sentence? | #include <iostream>
using namespace std;
int main() {
char a[101]{0};
cin>>a;
cin.getline(a,101);
cin.ignore();
int currLen{0};
int maxLen{0};
int startInd{-1};
int endInd{-1};
for(int i=0; i<101; i++) {
if(a[i]!=' ' ) {
++currLen;
} else if(a[i]==' '||... | A nice sliding window pattern implementation.
You have 3 problems in your code
You must not write cin >> a;
You must not write cin.ignore();
You need to modify your if statement like so: if (a[i] != ' ' && a[i] != '\0') Otherwise you will not detect the last word.
Your complete working code with that minor fixes will... |
66,277,783 | 66,277,822 | Gradient color for text of QLabel Qt/c++ | I trying to set gradient color for QLabel text. I am trying to use setStyleSheet function but it doesn't work. I read this article but still can't get the working solution.
this is my code
void MyClass::setTitle(const QString& text)
{
m_text = text;
m_titleText->setText(text);
QFont font = m_titleText->font... | You can try this.
void MyClass::setTitle(const QString& text)
{
m_text = text;
m_titleText->setText(text);
QFont font = m_titleText->font();
font.setPointSize(12);
m_titleText->setFont(font);
QPalette labelPal;
QLinearGradient colorGradient = QLinearGradien... |
66,277,859 | 66,277,946 | What happen to async member function after local object out of scope? | For example, if I can call an async function like this:
{
Example example;
example.asyncFuncInside();
}
Since the object is freed after the scope, will it have any risks on the ongoing task running inside the async function?
| This cannot be answered in the current form. If the "async" is a detached std::thread, nothing bad happens. If the async function was implemented using std::async, on the other hand, then asyncFuncInside would return its std::future, and since that's ignored the dtor of std::future would block.
|
66,278,375 | 66,287,178 | Progress Bar gtkmm Glade | Working with the buttons and handling its events is easy but I couldn't interact with progress bars. How do I get a Gtk::ProgressBar from a Glade file and set its fraction?
I use Gtkmm 3.24 and I want to update a progress bar when I click a button. here is my glade file:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Gen... | Here is code that does what you want:
#include <memory>
#include <gtkmm.h>
constexpr int ERROR = 1;
int main(int argc, char* argv[])
{
auto app = Gtk::Application::create(argc, argv, "de.engelmarkus.example");
auto builder = Gtk::Builder::create_from_file("MyGladeGUI.glade");
// Get the window. First a ... |
66,278,446 | 66,278,497 | c++ warning: ‘t’ may be used uninitialized in this function [-Wmaybe-uninitialized] cm(t,n); | Compilation séparée
I get the probleme why doesn't work
!g++ -Wall -Wextra -g -c cm1.cpp -o cm1.o
cm1.cpp: In function ‘int main(int, char**)’:
cm1.cpp:14:5: warning: ‘t’ may be used uninitialized in this function [-Wmaybe-uninitialized]
cm(t,n);
~~^~~~~
Compilation all the part to test
!g++ cm1.o cm.o -o test... | You must initialize t1 by allocating buffers before passing it to the function.
} int **t1;
// allocate an array of pointers
t1 = new int*[n];
// allocate arrays for each row
for (int i = 0; i < n; i++) {
t1[i] = new int[n];
}
cm(t1,n);
|
66,278,458 | 66,278,559 | Why am I getting string reversal wrong with a trailing space character? | I am unable to get why there is a space and it is getting me wrong.
Below is the code I wrote for the solution
Why there is blank space char at the end of the string at the end even after reversing my string.
Question
class Solution {
public:
string minRemoveToMakeValid(string s) {
string str = "";
... | The length of str may be less than one of s, but you are using the length of s while iterating within str. You must use correct length.
string s2="";
n = str.length(); // add this
for(int i=n-1;i>=0;i--){
|
66,278,670 | 66,278,895 | Force reinterpret_cast to return nullptr | I'm creating unit test for a function that receives a memory address as an unsigned long
Inside the function, this addres is reinterpret_casted into a pointer of one of ur classes.
void my function(Address inputAdress ) // Address comes from: typedef unsigned long Address;
{
ClsMyClassThread* ptr = reinterpret_cast<... | From reinterpret_cast conversion point 3 (emphasis mine):
A value of any integral or enumeration type can be converted to a pointer type. A pointer converted to an integer of sufficient size and back to the same pointer type is guaranteed to have its original value, otherwise the resulting pointer cannot be dereferen... |
66,279,589 | 66,283,738 | Boost beast send json with byte array to client throw websocket | I have file which is converted from byte array to string
processResultJson.append(reinterpret_cast<const char *const>(im->bits), sizeof(im->bits));
processResultJson.append(reinterpret_cast<const char *const>(im->bits), im_res->bmi->bmiHeader.biSizeImage);
docData.put("Image1", processResultJson);}
boost::property_tre... | Don't use Property Tree as if it's a JSON library. It has well known limitations: https://www.boost.org/doc/libs/1_75_0/doc/html/property_tree/parsers.html#property_tree.parsers.json_parser
Note especially the limitationssurrounding arrays.
Next up, you didn't write an array to begin with, instead writing a string. But... |
66,279,612 | 66,286,225 | How do you convert a Python Decimal instance to a C++ double? | In Python itself, you'd write simply float(f) where f is a Python Decimal. That yields a double type (called a float in Python).
But I need to do this in boost::python. My code (abridged) is
double toDouble(boost::python::object obj)
{
std::string type = boost::python::extract<std::string>(obj.attr("__class__").att... | The code you need in the if block is
static boost::python::object builtins
= boost::python::import("builtins");
static boost::python::object function
= boost::python::extract<boost::python::object>(builtins.attr("float"));
boost::python::object ret = function(obj);
double f = boost::python::extract<double>(ret... |
66,279,679 | 66,281,905 | Casting float to int with wrap-around on aarch64/arm64 | I'm trying to match the behavior exactly between an application running on both x86_64 and aarch64/arm64. However, they differ in how they cast a floating point number to an integer when it's outside of the possible range of integers.
Consider the following example:
#include <stdio.h>
#include <cstdint>
void cast(floa... | Use the CPU instruction fjcvtzs (or the intrinsic __builtin_arm_jcvt) to get behavior of x86 on aarch64.
(Thanks to @EOF for providing enough information in a comment for me to find the answer)
|
66,279,769 | 66,280,540 | Trying to understand partial template specialization with template template parameters | I came across this is_specialization implementation found in several posts on SO:
//1 default
template<typename Test, template<typename...> class Ref>
struct is_specialization : std::false_type {};
//2 specialization
template<template<typename...> class Ref, typename... Args>
struct is_special... |
for the first parameter passed to is_specialization, what is expected is a template (template<typename...> class Ref) and not a template instance?
That is an incorrect assumption.
Consider this additional specialization.
//1 default
template<typename Test, template<typename...> class Ref>
struct is_specialization : ... |
66,280,204 | 66,280,586 | Converting Between Incompatible Types | In some places in my code, I use the _mm_prefetch function, which takes in a const char * and int. The first parameter being the memory address of the object to prefetch. Since it's a const char * instead of void*, it needs to be cast.
Note: in the below context nextActive is a pointer to object.
Originally, I had:
_mm... | This should fix it:
void* ptr = this->nextActive;
_mm_prefetch(static_cast<const char*>(ptr), _MM_HINT_T1);
The only cast is from void* to const char* which is allowed.
|
66,280,796 | 66,281,953 | Removing all punctuation from a set of words, or writing all unique words from txt file into a set (without punctuation) in c++ | I needed a program that puts all unique words from a txt file into a set, and so i've found this code
#include <iostream>
#include <fstream>
#include <set>
#include <string>
#include <iterator>
#include <algorithm>
const std::string fileName{ "unique.text" };
int main() {
// Open the source file and check, if it cou... | Since the code has been originally written by me, I will answer your question.
We simply use a std::transform, to modify the strings received from the file and remove all punctuation.
The std::transform will iterate over all strings read from the stream, and then passes each string to a lambda. The lambda will modify t... |
66,280,861 | 66,282,953 | FFMPEG: 'Nonmatching transport in server reply' But openRTSP works | I bought a cheap chinese ip camera (GWIPC-26xxx/Yoosee). I want to record its stream with ffmpeg.
On FFMPEG I manage to make it work only using the RTSP/UDP transport protocol, like bellow. It also plays flawlessly on VLC.
ffmpeg -rtsp_transport udp -i rtsp://admin:pass@192.168.0.103:554/onvif1 streamfile.mkv
pass is ... | Quoting Wisdom
IP cameras are of varying quality, some behaving erratically in my experience. Dealing with their RTSP streams requires a dose of fault-tolerance.
This appears to be a byproduct of the low-end of the CCTV industry playing fast and loose with standards, RTSP and ONVIF being the two most frequently abused... |
66,280,870 | 66,288,307 | Should it be possible to export a constexpr function pointer from a cpp module? | I'm trying to export a constexpr function pointer from a cpp module, but Visual Studio (16.9.0 preview 4.0) gives me an internal compiler error. When I remove the second constexpr, everything works just fine. Am I trying to do something that's not allowed?
export module MyModule;
constexpr int twice(int x)
{
retur... | This code is valid: presumably MSVC is confused by the default internal linkage associated with a const variable, but that doesn’t apply to exported variables. (It shouldn’t apply in an importable module unit at all, since the historical reason of allowing multiple inclusion of named constants doesn’t apply there. I ... |
66,281,116 | 66,281,733 | CMAKE: Configure/build a foreign package from your package | Let say that your CMake C++ project depends on some external library such has Google Benchmarks/Test.
I know that I can independently configure and install the external library so that later when building my personal project I can access its CMake file which will nicely satisfy the dependency (It will nicely add its he... | Yes. Have a look at https://cmake.org/cmake/help/latest/module/FetchContent.html
This is exactly what I use for fetching GTest.
Idea is simple - FetchContent will clone a repo for you, then you do add_subdirectory into that repo, and you can manage all subproject details (assuming project uses CMake and is written prop... |
66,281,418 | 66,283,083 | Linking my Dynamic Link Library to my CPP executable | I'm using CLion with cmake.
I want to link my dll to my c++ project in cmakelists.txt but I don't know how to do that.
I have searched a lot but I didn't find any solution.
I have published a dll by visual studio in c++ which I want to link to my cmake project.
the project name and output name is Benchmark -> Benchm... | If the absolute directory of the .dll is "D:\\VS Projects\\BenchmarkLibrary\\C-Family\\Release-output\\x64", then you just need to add the following instead of find_library statement. it just searches for the library as the comment said.
target_link_directories(SpeedTest
PRIVATE
"D:\\VS Projects\\BenchmarkLibr... |
66,281,449 | 66,281,758 | Does glibc wcslen() expect data alignment along wchar_t sized boundaries? | Been wracking my brain for hours on this one. glibc wcslen() is returning a different value than expected for a given input string. I've narrowed the problem to a possible data alignment issue but even that doesn't make sense to me. My own function that dumps the string appears to work fine and also calculates the s... | In general, C++ always requires that all access to an object is aligned to at least as strict boundary as the type requires. This is because objects cannot exist in misaligned addresses. So, this requirement is not specific to wcslen.
On your system, alignof(wchar_t) is likely greater than 1, in which case prebuffer + ... |
66,281,494 | 66,282,064 | TaskScheduler is able to execute a service in NT AUTHORITY\SYSTEM account? | I have a Windows service that run in NT AUTHORITY\SYSTEM (SERVICE_WIN32_OWN_PROCESS) account during system startup.
Now i have a doubt:
Suppose that i want change the way of automatic execution to TaskScheduler.
TaskScheduler will execute my service normally like before and mainly in NT AUTHORITY\SYSTEM account?
| TaskScheduler doesn't directly support running services, but you can use a command-line operation to instruct the SCM to start the service (ie, net start "<ServiceName>"). You can use whatever account you want to run the operation, but the account that the service will use is specified in the service's own configuratio... |
66,281,544 | 66,292,842 | Eigen - reshape a vector to matrix | I am trying to reshape a vector to a matrix, but getting the following error
unsigned int Nx = 8;
unsigned int Ny = 7;
Eigen::VectorXi G_temp = Eigen::VectorXi::LinSpaced((Nx + 2) * (Ny + 2),0,(Nx + 2) * (Ny + 2)-1);
Eigen::MatrixXd G = Eigen::Map<Eigen::MatrixXd>(G_temp.data(),Nx+2, Ny+2); // error: no matchin... | There is no implicit conversion from integer-valued to double-valued expressions in Eigen. Either just use VectorXd for G_temp (and the LinSpaced expression):
Eigen::VectorXd G_temp = Eigen::VectorXd::LinSpaced((Nx + 2) * (Ny + 2),0,(Nx + 2) * (Ny + 2)-1);
Or use a MatrixXi-Map and .cast<double>() the result before as... |
66,281,624 | 66,281,778 | C++ Inserting elements in doubly linked list logic error | I am working on code that takes a list of unsorted elements and sorts them into a doubly linked list. The code works for the most part, elements can be added to both the beginning and end of the list however for some reason that is beyond me if the first element added will stay on the head (the highest in alphabetical... | This:
nn->next = head;
nn->prev = NULL;
nn->next->prev = head;
should be:
nn->next = head;
nn->prev = NULL;
nn->next->prev = nn;
And similarly this:
nn->next = NULL;
nn->prev = tail;
nn->prev->next = tail;
should be:
nn->next = NULL;
nn->prev = tail;
nn->prev->next = n... |
66,281,875 | 66,283,731 | how to implement simple object container in C++ | I want to implement some object container like java bean does,for example:
I have several objects like pig,apple,dog....which may be constructed and used in my framewrok.
class pig:public object{
public:
pig(double weight);
};
class apple:public object{
public:
apple(int qty);
};
class dog:pub... | All your class are derived from object. The things you can do, is to create a template function that return an pointer to an object like:
template<class T, class... Args>
std::shared_ptr<object> create(Args&&...) {
return std::make_shared<T>(std::forward<Args(args)...);
}
Then just call it like:
std::shared_ptr<do... |
66,281,954 | 66,282,099 | How to compare types (including ref-qualifiers) in a parameter pack and the types of std::function parameters | I'm storing an std::function inside a variadic class template (passed in the constructor of the class).
While doing so, I want to check that the types of the std::function parameters are the same as the types within the parameter pack of the class template. Here is an example:
template<typename... T>
class Foo {
public... | If you can use C++17... what about using the CTAD defined for std::function to check that the std::function deduced for the argument of the constructor is exactly the same of func?
I mean... what about as follows?
template <typename... T>
struct Foo
{
template <typename L>
Foo (L && l) : func{ std::forward<L>... |
66,282,313 | 66,282,488 | Do I have to define classes in header files in C++? | I am new to C++ so please be kind. I was wondering if we really have to put classes in headers files (.h) . I know it looks better and is more efficient to separate the definition with the implementation but is there another benefit of doing this such as faster compilation or something like that?
Anything would help, t... | Actually you don't have to. However using header files has following benefits:
Enables you to find your classes easier by choosing your desired file rather than time consuming scrolls.
Your code is easy to maintain, meaning that developing process is easier and faster in the future.
It potentially can reduce compilin... |
66,282,396 | 66,282,708 | Is it possible to write variadic template constructor initializing all members of a class/struct? | Is it possible to achieve this:
struct S
{
int a;
std::string s;
template<typename... Args>
S(Args... args)
: // what next?
{
// what next?
}
};
Or is there any other way to achieve (something like) this? (std::tuple?)
| You can use std::tie to create tuple of lvalue references to your data members, and assign content of another tuple created based on passed arguments:
struct S {
int a;
std::string s;
template<typename... Args>
S(Args&&... args) {
static_assert(std::is_same_v< std::tuple<int,std::string>, std::... |
66,282,581 | 66,297,655 | Deduction of Return / Argument types from function | I've got a hierarchy of types for Callback objects. After some heavy simplification, it looks a bit like this:
template <typename Return, typename... Args>
struct Callback
{
virtual Return Call(Args...) =0;
void* mCtx;
}; // ctor, virtual dtor omitted
template <class T, typename Return, typename... Args>
struct M... | Unfortunately, it seems like a pack expansion where the pack is not at the end of the list, such as Return(*)(Args..., void*), is a non-deduced context (see #8 here; disclaimer: I'm not a language lawyer). This means that Args cannot be deduced from the type of FooBaz in your example.
However, you can work around this ... |
66,282,618 | 66,283,739 | store a function without directly creating new function objects in C++ way | I'm trying to create a generic menu, so I came with the idea of creating a menu with options, and each option in the menu will have a label, key to execute, and an Action.
The Action is template class simply stores a function and runs it when I need it by the call to execute().
My problem is that for each Action, I nee... | Using Command Design Pattern is a great option and answer my needs.
|
66,282,628 | 66,283,242 | Is it possible to initalize ApplicationWindow before Component.onCompleted is done? | I am trying to import some data from a .csv file using a modified version of FileIO. I am supposed to use this data to show axis posture information. Therefore, values should be updated automatically every second. Then I created Q_PROPERTIES for every variable and created the code which gets data from the CSV file. I ... | The problem is that the reading of the data is very fast so that our slow vision cannot see the change. In this case, what you should do is create a method that only reads a line and updates the value of xValue, yValue and zValue and then use a Timer to invoke that method every T seconds:
class FileIO: public QObject{
... |
66,282,909 | 66,283,162 | What is wrong with this void pointer to struct cast? | The task here is to call out everything that is wrong with this snippet. I do not know if the code is being presented as C or C++, so either assumption is valid and helpful.
struct MyStructData
{
VOID* pPtr;
UINT32 flags;
}
VOID main()
{
MyStructData* pMyStructData = InitFunction();
// work done here
... | Answer was provided before language tag was changed from C to C++.
struct MyStructData
{
VOID* pPtr;
UINT32 flags;
}
There are no types VOID or UINT32 in C unless you include some headers providing them. Maybe some Windows stuff?
Also a ; is missing after that struct declaration. (Thanks to wildplasser)
VOID m... |
66,282,954 | 66,282,999 | Is a single if statement bad for checking whether a key exists in a map or not for C++ | int n, pNumber;
string name, sName;
cin >> n;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
map<string, int> m;
for (int i = 0; i < n; i++) {
cin >> name >> pNumber;
m[name] = pNumber;
}
while (cin >> sName) {
if (m[sName]) {
cout << sName << "=" << m[sName] << endl;
}
else {
... | This doesn't check whether or not the key exists. It tests if the value corresponding to the key is non-zero, creating it if it doesn't exist.
So, yes, it's bad for checking whether a key exists in a map or not because:
It will return that the key doesn't exist if the corresponding value is zero.
It will create the ke... |
66,283,032 | 66,283,128 | c++: OR operator: "enum" vs "enum class"? | Unscoped enumeration WORKS with the OR operator where the scoped one does not... WHY and how to work with it?
The enum type type-name is unscoped. Prefer 'enum class' over 'enum' (Enum.3)
#include <iostream>
enum eDogType
{
eHusk = 0,
eGold,
eAus,
eGerm,
ePud
};
int main()
{
eDogType eDog1 = eDogType::e... | enum eDogType values are processed as int values, where enum class eDogType values are not (they are processed as values of type eDogType).
So in the first case, the operator | (int, int) is used, whereas in the second case, the operator | (eDogType, eDogType) is needed (but not found).
#include <iostream>
enum class... |
66,283,125 | 66,283,253 | Acces denied when moving folder to usb drive | when I try to move the "HelloWorld" folder to an usb drive it says acces denied in the command line
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char src[50],dest[50],cmd[100],penPath[1];
cout<<"\nENTER LETTER OF THE FLASH MEMORY (raw letter. E.g: I,H,F,...): ";
cin>>penPath;
st... | Based on this path "%USERPROFILE%\Desktop\HelloWorld" it seems like you are running this on Windows.
This question has been answered here: how do i fix: 'access denied' with the move command in windows 7?
The move command cannot move folders to another drive, you will have to use the robocopy command instead.
Your comm... |
66,283,685 | 66,283,873 | Is std::map exception safe with custom comparator? | What std::map will do if custom comparator throw an exception during rebalancing? Apparently, it should remember all the previous turns and return everything to its original state. Is it true?
| See [associative.reqmts.except]:
For associative containers, no clear() function throws an exception. erase(k) does not throw an exception unless that exception is thrown by the container’s Compare object (if any).
For associative containers, if an exception is thrown by any operation from within an insert or emplace ... |
66,283,753 | 69,831,144 | Set the process priority and the affinity of an irq process from C/C++ | i want to set rise the priority and the affinity of irq processes (spi, gpiod) in linux, from a program written in C/C++. To set the priority of my own process I use pthread_setschedparam to set the affinity of my own process I use pthread_setaffinity_np. I use pthread_self() for this functions. However especially the ... | I solved it by using libprocps. It is possible to get the pid of the irq via the name of the gpio or of the spi device and then to set the cpu affinity/priority of the irq.
|
66,284,083 | 66,284,196 | Can we assign the result of a logical expression to an integer variable? | I searched about this issue but the answer I found was that the result of a logical expression cannot be assigned to an integer variable it can be only assigned to a boolean variable, but then I tried a simple code to check my point that the result can be assigned to an integer variable because in the first place the l... | when you say:
b = (n1 == n2);
the compiler says:
b = int(n1 == n2);
this concept is known as implicit type conversion.
|
66,284,332 | 66,284,705 | Boost Spirit nested components | I am trying to parse the following messages with Spirit Qi:
"A/B AND C/D", "A/B", "A/B AND C/D AND E/F"
I am able to parse "A/B" but cannot get the correct results for the other strings.
I tried to following code:
qi::rule<It, AstNodeVector()> entries;
qi::rule<It, AstNodeVector()> lists;
qi::rule<It, std::string()> e... | It seems you're not skipping whitespace. Maybe that's a conceptual problem (see Boost spirit skipper issues).
Regardless, it does parse:
Live On Coliru
#include <boost/spirit/include/qi.hpp>
#include <iomanip>
namespace qi = boost::spirit::qi;
using AstNodeVector = std::vector<std::string>;
template <typename It>
str... |
66,284,674 | 66,285,036 | CUDA Segmentation fault on cudaFree pointer to array in struct | I got a struct living on the CUDA device which contains a pointer to an array. Computations, accessing the elements and everything works fine but when I try to be a good boy and call
cudaFree(my_struct->pointer_to_array)
I get a segmentation fault. cudaFree(my_struct) however works perfectly fine. Is there something I ... | This statement:
status = cudaFree(d_dummy->arr);
requires dereferencing of a device pointer (d_dummy - which was allocated with a device allocator i.e. cudaMalloc) in host code. That is illegal in CUDA.
Since you already know that (d_dummy->arr) == d_arr, one possible approach to freeing the embedded pointer would be... |
66,285,460 | 66,291,196 | Winsock socket doesn't recveive packet cpp | I have a client that waits for the server to send a broadcast to a specific port and then return a message.
I can see the packet in Wireshark, but my application doesn't catch it.
Here is the function that catches the packet. (getPrivateIP works)
uint32_t findMastersIP()
{
sockaddr_in recvAddr{};
sockaddr_in s... | I found the problem, the firewall blocked my program in private networks for some reason. I have now enabled the program and it works perfectly.
|
66,285,750 | 66,285,902 | Best way of representing binary data | I am writing a Qt C++ application where I am reading a pcap file and interpreting packets described in given file. As I am reading packet by packet, I need to somehow store binary data. It needs to be flexible enough so I can pass it across multiple functions as parameter and being able to work with it as char*. It als... | Some notes about Qt:
You can use QByteArray QIODevice::readAll() directly to obtain a buffer:
QFile file(fileName.c_str());
auto buff = file.readAll();
QByteArray is implicite sharing / copy-on-write. So while you can pass by reference, you should either pass by const reference or simply pass by value.
Your solutio... |
66,285,885 | 68,583,361 | Clang compiler couldn't find C/C++ standard libraries when I gave a specific target although it works without giving target | I am currently using clang11 on ubuntu to compile any c/c++ code and it works fine but when I tried to compile any code (including any standard library) to assembly code for any specific target like x86_64 (even I have x86_64) riscv with giving a flag that --target=x86_64 or --target=riscv32 I got errors for any stand... | I solved my problem by linking compilations with riscv-gnu-toolchain built and also answered a similar question here in detailed: Using Clang to compile for RISC-V
Simply we need cross-compilation.
Further information you can also look here: https://github.com/lowRISC/riscv-llvm#how-can-i-build-upstream-llvmclang-and-u... |
66,286,146 | 66,286,197 | Microsoft visual studio file not found | I was trying to make a basic program that would print out the words "hello" and then "press any key to continue" but whenever I try to run the code, this pops up
enter image description here
This is my code btw,
#include <iostream>
int main() {
std::cout << 'hello\n';
system('pause');
}
Does anyone know ho... | Your code is wrong. Try fixing that first not to fail into compilation error.
#include <cstdlib> is missing while using system()
A implementation-defined integer is passed to system() instead of a pointer to string, which system() requires. You should use "", not '', to express string literals.
#include <iostream>
#i... |
66,286,420 | 66,286,494 | SFINAE | strange behaviour | I am studying SFINAE and c++ in general. I'm having a strange behaviour with My SFINAE macros (called here "annotations"):
<lang/Annotations.h>
#pragma once
#define ENABLE_IF(y) typename std::enable_if<y,std::nullptr_t>::type
#define IS_REFERENCE(x) std::is_reference<x>::value
#define IS_CONSTRUCTIBLE(...) std::is_cons... | I don't know if it is the problem (the only problem) but this macro
#define ENABLE_IF(y) typename std::enable_if<y>::type
becomes void when y is true.
So when y is true
template <typename... Types, ENABLE_IF(!IS_CONSTRUCTIBLE(Types...)) = 0>
becomes
template <typename... Types, void = 0>
That can't work. 0 isn't a v... |
66,286,496 | 66,286,531 | operator< overload for std::set::insert not working as expected | I am trying to implement a std::set::insert such that it will 'insert' a struct given that one does not already exist.
I have added the required custom operator overload for 'less than' (<); however, when the code is executed it just seems to skip past it and not work as expected. (Implementation for which was modified... | std::set - cppreference.com says:
In imprecise terms, two objects a and b are considered equivalent if neither compares less than the other: !comp(a, b) && !comp(b, a).
The member x of the two objects Coordinate(1, 2) and Coordinate(1, 3) are both 1, so operator< cannot be true and therefore they are considered as sa... |
66,286,779 | 66,286,995 | Why is the use of std::min in these fold expressions undefined behavior? | Thanks to Can I implement max(A, max(B, max(C, D))) using fold expressions? I'm aware of one working approach to use std::min in a fold expression(min2 below). However, I'm curious why the below approaches min1 and min3 are considered undefined behavior(seemingly given the warning)?
Per my understanding the expression ... | You don't actually have any undefined behavior. Note that the warnings say:
warning: operation on 'myMin' may be undefined [-Wsequence-point]
(my emphasis)
This warning, in both min1 and min3, comes from the expression
((myMin = std::min(myMin, anArgs))...)
If the parameter pack has 3 elements as it does in your cas... |
66,287,079 | 66,287,228 | Translating C++ to ARM Assembly using (MLA instruction) | I am trying to translate this C++ code:
y = y+ x*32;
z = y+ x*x;
To ARM assembly assume (x is R1 register, y is R2, z in R3), and I should use only one assembly instruction for each case
So, I suggest to do it using (MLA) but I don't know how, can you please help me!!
| Firstly, put your code snippet in an function and create a complete code.
void x(void){
volatile int x = 1, y = 2, z = 3;
y = y+ x*32;
z = y+ x*x;
}
Then, compile that on Compiler Explorer.
Result is:
x:
mov r1, #1
mov r2, #2
mov r3, #3
sub sp, sp, #16
... |
66,287,309 | 66,287,417 | What's the best way to handle member dependencies in OOP? | I have a Position class which represents a stock position like this:
class Position {
private:
double price_;
double amount_;
double value_;
public:
void SetPrice(double price) {
price_ = price;
}
void SetAmount(double amount) {
amount_ = amount;
}
double GetValue() {
... | Okay, you listed 4 ways of handling value in a Position class. I'll ignore the 4th one for a second, because the Timestamp attribute adds another level of complexity (your first 3 options don't have a Timestamp attribute either).
Between the 1st 3 options, the 1st option (simple setters for price and amount, and a gett... |
66,287,475 | 66,287,537 | Putting odd size int enums into very small struct? | I have a struct that represents common playing cards using few bits.
struct Card {
unsigned short suit : 2;
unsigned short rank : 4;
};
I'd like to use this sort of enumerator to set the rank and suit of the cards when I initialize them.
enum class Rank {two=2, three, four, five, six, seven, eight, nine, ten, ... |
the size of values in enumerators is always minimum 1 byte and always a power of two. That would increase the size of every card by a lot.
Actually, that wouldn't necessarily increase the size of the card at all. The size of your Card is two bytes, and two enumerations of one byte are also two bytes. Of course, it wo... |
66,287,661 | 66,287,681 | How to use OR operator on three operands? | Any ideas, or tips (links to tutorials), are much appreciated, I'd be happy to take a reference if this has been addressed elsewhere.
I haven't been able to find anything referencing how to use the OR on three operands here is the question that I got wrong.
Let A = true, B = false, and C = true. Evaluate the following:... | Firstly, evaluate the lefthand operand of (3 != 5) && !(A || B || C).
It is 3 != 5, which is true.
Then, evaluate the righthand operand of (3 != 5) && !(A || B || C).
It is !(A || B || C).
To evaluate this, let's evaluate the operand of ! operator, which is A || B || C.
|| operator has left-to-right assosiativity, so A... |
66,287,737 | 66,296,972 | How to use thrust to accumulate array based on index? | I am trying to accumulate array based on index. My inputs are two vectors with same length. 1st vector is the index. 2nd vector are the value. My goal is to accumulate the value based on index. I have a similar code in c++. But I am new in thrust coding. Could I achieve this with thrust device code? Which function coul... | As indicated in the comment, the canonical way to do this would be to reorder the data (keys, values) so that like keys are grouped together. You can do this with sort_by_key. reduce_by_key then solves.
It is possible, in a slightly un-thrust-like way, to also solve the problem without reordering, using a functor pro... |
66,287,813 | 66,287,875 | Xor with unsigned char | I am trying to perform an Xor between a 64 bit key and a 64 bit unsigned char array and I keep getting very strange output. Is there an issue with the data type or the order of operations?
#include <iostream>
using namespace std;
int main() {
unsigned char inputText = '7';
unsigned char key = 'a';
cout <... | you are not xoring the hex numbers, but the ascii values of the characters.
input: '7', '3', '6', '5'
ascii: 55, 51, 54, 53
key: '0', 'f', 'f', 'a'
ascii: 48, 102, 102, 97
result: 55 ^ 48, 51 ^ 102, 54 ^ 102, 53 ^ 97
result: 7, 85, 80, 84
|
66,287,954 | 66,292,930 | How can I create a wxMenu with only bitmaps | I would like to draw a wxMenu where the items are drawn as bitmaps with a size of my choosing. I know I can call SetBitmap etc on a wxMenuItem, but that leaves space on both the left right for the item label etc.
I know how to do this using MFC, where I would subclass CMenu and override DrawItem and MeasureItem so it s... | You can override OnMeasureItem() and OnDrawItem() in your own wxMenuItem subclass, but this will indeed work under MSW only.
You might also want to take a look at the ownerdraw sample.
|
66,288,184 | 66,288,245 | How to connect IF in my ELSE condition inside of while? | C++
I'm stuck my if and else is not connecting
error: else without previous if
#include<iostream>
int main(){
int i=1, num, sum=0;
while (i <= 5) {
cout<<"Enter a number: ";
cin>>num;
if (num % 2 ==0 ){
sum = sum + num;
i++;}
cout<<"\nThe sum is " << su... | The real problem here is indentation and structure, which is easily fixed by writing it in idiomatic C++:
#include <iostream>
// Avoid using namespace std; as that separation exists for a reason
int main() {
int sum = 0;
// Use a for() loop instead of while(n < L) { ... n++ }
// Declare iterator variables insi... |
66,288,228 | 66,288,543 | Mashed-up data in string vector | I've been trying to fix this for ages,
I've got a program that takes in a random word from a supplied dictionary (txt file),
and then adds this word to a vector of strings.
The randomWord() function works as intended, but the getWords() seems to mash-up everything when I try to print out the vector.
The vector declarat... | There is a very high probability that you're reading in CR characters from a CRLF delimited file, assuming it is just LF delimited, and printing them, where the carriage return will slam the cursor to the left and write over existing text.
You will need to either read this as CRLF or strip out any CR or LF characters.
... |
66,288,233 | 66,288,303 | Why can we return char* from function? | Here is a piece of C++ code that shows some very peculiar behavior. Who can tell me why strB can print out the stuff?
char* strA()
{
char str[] = "hello word";
return str;
}
char* strB()
{
char* str = "hello word";
return str;
}
int main()
{
cout<<strA()<<endl;
cout<<strB()<<endl;
}
... | Why does strB() work?
A string literal (e.g. "a string literal") has static storage duration. That means its lifetime spans the duration of your program's execution. This can be done because the compiler knows every string literal that you are going to use in your program, hence it can store their data directly into th... |
66,288,262 | 66,288,331 | Decomposing C++17 function-like object in generic fashion? | In C++17 suppose I have a function-like object passed as a parameter to some template:
template<typename F>
void g(F f) {
auto x = f(/*...*/);
}
There are lots of different types F could be, such as a function pointer, a std::function, a lambda expression, and in fact any class type that implements operator().
... | C++17's adds deduction guides for std::function, which we can use to do the deduce the function signature of non-overloaded function-like objects:
template <typename R, typename... Args>
constexpr auto do_something_with_the_signature(std::function<R(Args...)>) {
// Assuming that you only care about the return type.... |
66,289,041 | 66,289,290 | How to use cout formatting statements to print the input and output in proper format? | I have a 2d array which stores numbers for Maths and Chemistry for X number of sets. Below is how I take input for each class and store them in 2d array for each class.
Input for Maths class:
50 20 30 40 50
Input for Chemistry class:
90 70 20 10 40
Now basis on above input for each class I need to calculate "BEST", ... | This could be a way:
auto w = std::setw(6); // for number like " 10.00" (6 chars)
auto wb = std::setw(8); // for the numbers with more space between them
auto sw = std::setw(11); // for titles (math, chemistry)
// print the numbers above
cout << " ";
for(int i=1; i<=5; ++i) std::cout << w << i;
std::cout <<... |
66,289,160 | 66,298,774 | Switch case statement with for loop not working as expected | The obstacle here is to find a number with the same decimals and do some math with them.
What I want to achieve here is just to make the switch/case statement work.
I just started programming (ಥ_ಥ)
What did I do wrong here?
I can't find the issue with the logic...
#include <bits/stdc++.h>
using namespace std;
int ma... | If statement worked as intended.
Thanks for helping me.
#include <bits/stdc++.h>
int arr[10001]={0};
int main() {
for(int i=1; i<10000; i++){
if(i<10)
arr[i+i]=1;
else if(i<100)
arr[i+i/10+i%10]=1;
else if(i<1000)
arr[i+i/100+(i%100)/10+i%10]=1;
el... |
66,289,207 | 66,289,239 | Why delete char array cause crash after assign a value by operator=? | This is my code. I create a char array and assign a string literal to it by operator=. After which, I free it by delete.However, it cause segmentation. But it works fine with strcpy. Besides, Is char array always assigned by strcpy?
I got to this problem from Implementaion of STL std::string, I wonder why private char*... | You can only delete[] something that you allocate with new[].
So this code is OK, because a points to memory you allocated with new[]
int main()
{
char* a = new char[3];
delete[] a;
}
This code is also OK, because a is still pointing at memory allocated with new[]
int main()
{
char* a=new char[3];
strc... |
66,289,394 | 66,290,979 | How do we assign variables and update them in unordered maps in C++? | I am trying to implement a probability distribution of characters in the text. I am trying to learn unordered maps, but I could not update the probs map after inserting the pair. Let's say we assigned letters 'a', 'b' and 'c', I want to increment the value of 'a' in the map. Any suggestions?
string text = "abcaa";
unor... | You could write right away probs[ch]++.
Because if ch does not match the key of any element in the container, the [] operator inserts a new element (constructed using its default constructor) with that key and returns a reference to its mapped value.
int main() {
std::string text = "abcaa";
std::unordered_map<c... |
66,289,704 | 66,289,928 | Best way to copy a vector | I have a struct Y with a vector of type X, I would like to ask whether in this case assign is the best solution or copy would be better? Should I resize y.xVec?
#include <iostream>
#include <vector>
struct X {
X(int x):x_(x)
{}
int x_;
};
struct Y {
std::vector<X>xVec;
};
int main()
{
X x1(1);
X x2(2... | The simplest code is the best here:
y.xVec = v;
Or if you don't need v anymore:
y.xVec = std::move(v);
Or if you will use v again but starting from empty:
y.xVec = std::exchange(v, {});
exchange() is better than move() if you need to use v again, because it leaves v in its default-constructed state (empty), rather t... |
66,289,860 | 66,289,875 | Switch over a non-enumerator value for an enum class | In C++ it's allowed to have values of an enumeration type which don't correspond to any enumerator so long as they are in range:
enum class E { X = 1, Y = 2 };
E z = static_cast<E>(0);
Is it possible to switch over such a value? That is,
void f(E a) {
switch(a) {
case E::X: // something
case E::Y: // so... | This should do:
enum class E { X = 1, Y = 2 };
constexpr E z = static_cast<E>(0);
void f(E a) {
switch (a) {
case E::X: // ...
case E::Y: // ...
case z: // ...
default: // ...
};
}
|
66,289,890 | 66,289,919 | boost::geometry::index::rtree get intersection area of boxes from rtree::query | I'm having boost::geometry::index::rtree of a boost::geometry::model::box. With rtree::query I'm getting all boxes that intersects with the set one. Now I need to calculate the intersection square for all the returned boxes. I can write the code that will do it, but probably in boost there is already something that do... | boost::geometry::intersection will do it.
|
66,289,913 | 66,294,701 | C++ Subtracting days from current time using date.h | I am trying to subtract a number of days from the current time using the date.h library of Howard Hinnant.
auto currentTime()
{
using namespace std::chrono;
return date::floor<seconds>(system_clock::now());
}
auto oldDate(date::days daysNum)
{
using namespace date;
auto time = currentTime();
auto s... | year_month_day is the wrong data structure for days-oriented arithmetic. The reason is that doing so results in gratuitously expensive code (like putting an indexing operator on std::list).
The right data structure is just a time_point. This makes your oldDate function really simple and very efficient:
auto oldDate(d... |
66,290,487 | 66,290,887 | function template parameter deduction of template parameter vs of default template parameter vs of return type | This is a question about how template deduction works when template parameter used as template parameter vs as default template parameter vs as return type.
1: plain template parameter
As tested using GCC and VS compiliation of below snippet fails to deduce template parameter defined by std::enable_if_t
#include <iostr... | You can remove everything about enable_if in the question. It boils down to these three:
void is an invalid anonymous template parameter:
template<class T, void>
void SwapInPlace( T& left, T& right );
A void* as an anonymous template parameter with a default value is ok:
template<class T, void* = nullptr >
void SwapIn... |
66,290,611 | 66,301,904 | VC++ Multiple projects in one solution - Linker issues (LNK2019) | In an attempt to have modular code, that is easy to maintain, I have split code from a previous VC++ solution into separate other projects. That was I can maintain the separate code bases, whilst still being able to include the working code in a solution. My solution explorer looks like this:
I have followed this (Pr... | For any programmers who come to C++ from languages such as Python, Java or any other interpreted language. This post may help with you with some misconceptions you may have. When trying to import code from other managed projects, it is not enough to add the secondary project to the include directory of the solution.
As... |
66,290,661 | 66,290,758 | Why is this dangling-gsl warning invoked? | I am analyzing a codebase with clang-tidy and see a warning I do not understand. The warning is invoked by the following lines of code:
void fun(const QString& bar) {
const char* c_format = bar.toStdString().c_str();
expand_some_macro(c_format);
}
c_format is passed around in the expanded macro which reads as ... | Consider the statement...
const char* c_format = bar.toStdString().c_str();
bar.toStdString() returns a temporary std::string which will be destroyed before the next statement. But you then call std::string::c_str() against that temporary variable and save its return value to be used in...
expand_some_macro(c_format)... |
66,290,698 | 66,294,666 | How to get the number of items used in an unbounded knapsack problem? | I'm trying to solve an unbounded knapsack problem but I am stuck. I've already solved the main part of the problem which is getting the max value, but I'm also supposed to figure out how many of each item I used in order to get my maximum answer.
The bounds are less than 100 items and less than 100 capacity of the knap... | I think you need to think about your basic organization. I'm not going to do your homework for you, but I'll try to give some hints.
Your explanation of the knapsack problem seems flawed. Let me make sure we have the same problem.
You have a knapsack (a backpack). It can hold up to N "pounds".
You have several piles of... |
66,290,983 | 66,291,015 | C++ Candidate template ignored: deduced conflicting types for parameter 'T' ('std::__1::basic_string<char>' vs. 'char [4]') | I have the following code that fails when I call a bfs function and pass string literal as an argument:
template<typename T>
using Graph = unordered_map<T, vector<T> >;
template<typename T>
vector<T> bfs(const Graph<T>& graph, const T& root) {
...
}
int main() {
Graph<string> social_network = {
{"you"... | You can make type of root as being ignored in deduction of template parameters by using type_identity_t (required c++20), then T is taken from graph parameter:
const std::type_identity_t<T>& root
Demo
|
66,291,008 | 66,291,028 | Where is better place to declare local variable which is used only inside one function? | class MyClass{
public:
MyClass();
void memberFunction();
private:
int myVariable_; // can i declare it here?
};
void MyClass::memberFunction(){
int myVariable_; //or here?
}
//variable "myVariable_" is used only inside "memberFunction()"
| If it's only used within a function, and it doesn't need to exist longer than that function, then you're talking about a local variable.
If you need it to persist between calls, you need a property.
In other words, do you need the value stored in myVariable_ to persist to the next call?
|
66,291,201 | 66,291,448 | How to pass a struct member pointer to a function? | How does one go about passing a struct member identifier to a function such that the function can apply an operation to that specified member? The below code example should highlight what I am trying to achieve.
struct _struct {
int a = 0;
int b = 0;
};
_struct test[5];
void printVar(int index, ??? member) {
... | This is what "pointer to member" is for.
struct _struct {
int a = 0;
int b = 0;
};
_struct test[5];
void printVar(int index, int _struct::* member) {
// Print specified member at array element
printf("%d\n",test[index].*member);
};
int operation(int _struct::* member) {
// Some operation applied t... |
66,291,298 | 66,291,474 | Why constructor of std::set compares the same elements two times? | Let's consider the following example:
#include <iostream>
#include <set>
struct Obj {
int x;
int operator<=> (const Obj& obj) const {
std::cout << __FUNCTION__ << " " << *this << " " << obj << std::endl;
return x - obj.x;
}
friend std::ostream& operator<< (std::ostream& os, const Obj& obj);
};
std::os... | It probably test them for equality. If you look at std::set's template parameters, you can see that it only requires a less function to be provided. So how can we test two elements for equality given that we have only <? Compare twice. If !less(a, b) && !less(b, a), then a == b.
|
66,291,615 | 66,291,886 | reading signed ints from openCV in/to libtorch tensor c++ | I have a cv::Mat which is CV_32SC3 type, it stores both positive and negative values.
When convert it to tensor, the values are messed up:
cout << in_img << endl;
auto tensor_image = torch::from_blob(in_img.data, {1, in_img.rows, in_img.cols, 3}, torch::kByte);
The in_img has negative values, while after print out t... | The type 32SC3 means that your data are 32bits (4 bytes) signed integers, i.e ints. Pytorch kByte type means unsigned char (1 byte, values between 0 and 255). Therefore you are actually reading a matrix of ints as if it were a matrix of uchars.
Try with
auto tensor_image = torch::from_blob(in_img.data, {1, in_img.rows,... |
66,292,012 | 66,292,067 | removing vowels from c++ string | char arr[5000];
ifstream is("test.txt");
is.get(arr,5000);
int i = 0;
int j = 0;
cout << arr << endl;
char anar[5000];
while (arr[i] != '\0')
{
if (arr[i] == 'i' || arr[i] == 'a' || arr[i] == 'e' ||
arr[i] == 'o' || arr[i] == 'u')
{
++i;
}
else anar[j] = arr[i]; ++j; ++i;
}++j; an... | How big do you think sizeof(char) is? So how many characters is this going to write?
os.write(anar, sizeof(char));
You actually have j characters in your array, so this works
os.write(anar, j);
But since you have a null terminated character array even simpler would be
os << anar;
Some other errors, look at this lo... |
66,292,050 | 66,292,153 | size deduction in a templated c-string wrapper | Why doesn't this work :
#include <cstring>
template<size_t sz>
struct wstr {
wchar_t _str[sz];
wstr(const wchar_t source[sz]) {
wcscpy_s(_str, source);
}
};
int main(int argc, char** argv) {
wstr ws = L"Hello"; //needs template argument
return 0;
}
L"Hello" is known it's a const wchar... | For template deduction to work on arrays, you need to take the argument as a reference to the array.
wstr(const wchar_t (&source)[sz]) { ... }
|
66,292,359 | 66,292,483 | c++ derived class needs to tweak base class via callback | I would like to create a base class ==> derived class setup where the base class' constructor has a callback to run a (possibly complex) function to modify the base class' private member with information from the derived class. However, I'm running into a chicken and an egg problem because the base class constructor ru... | One approach is to let D calculate the adjusted string before calling the constructor of B.
class D : public B {
D(std::string str)
: B(my_f(str))
{}
std::string my_f(std::string str) { return str + "..."; }
};
A second approach is to let the body of constructor D do some work. Here adjust_base could also be... |
66,292,512 | 66,292,513 | How to print Content of currently Executing file C++? | How to print all the content of the currently executing file from in itself in C++?
#include <iostream>
using namespace std;
int main() {
// some code that print current file.
}
expected output:
#include <iostream>
using namespace std;
int main() {
// some code that print current file.
}
| there can be many ways possible, easy one.
#include <iostream>
using namespace std;
int main() {
string more = "more ";
more.append(__FILE__);
system(more.c_str());
}
Output:
#include <iostream>
using namespace std;
int main() {
string more = "more ";
more.append(__FILE__);
system(more.c_str... |
66,292,596 | 66,292,855 | Why my code is wrong?:A simple conversion of number systems | OJ result :partial accepted
Description
Put n balls into 50 boxes numbered 0, 1, 2, ......, 49, (n<250) and require that the ith box must contain pi times (m to the i-th power) of balls, or none if the box cannot satisfy this condition. Where 2 <= m <= 16 and pi is an integer between 0 and m - 1. Find a specific solut... | Potential errors in the code include:
The problem statement specifies there are 50 boxes, numbered 0 to 49, but the code loops over 51 boxes, numbered 0 to 50, with for(int i=0;i<=50;i++).
pow should not be used for integer exponentiation because it is inefficient in this use, presents overflow and precision issues, a... |
66,292,597 | 66,294,412 | Is it safe to cast atomic<T> to T | I have two questions:
In the general case is it safe to use an atomic as a T and switch between them interchangeably?
In the case of a futex is it safe to do the cast?
I am aware that performing atomic operations on non-atomic types is undefined behaviour but I cannot find an answer for the reverse. For example, this... |
In the general case is it safe to use an atomic as a T and switch between them interchangeably?
Not with reinterpret_cast. reinterpret_cast is only safe in the cases where it is explicitly listed as such, and this is not one.
You can however turn a T temporarily into an atomic object with std::atomic_ref.
In the cas... |
66,292,658 | 66,292,732 | Overload return of a pointer with reference and pointer | I got following code:
class myarray
{
float* rawdata;
float* GetRawData () const noexcept { return rawdata; };
float& GetRawData () const noexcept { return rawdata; };
const float& GetRawData () const noexcept { return rawdata; };
}
I get compiler error saying it is not possible to ove... |
Is it not possible for C++ to distinguish
It is not. Overloading is possible with different parameter lists, and in the case of member functions, ref/const qualifiers. But not by return values. Your overloads have identical parameter lists and ref/const qualifiers, so they cannot overload each other.
since we in a r... |
66,292,717 | 66,293,221 | Want to check if templated argument is std::endl | I want to write a functionality like:
DEBUG_LOG<<"append" << 123 <<" float=" <<123.432 << std::endl;
the << operator for this looks like:
Logger& operator<<(const T& message)
{
if(message == std::endl)
{
flushBuffer();
ret... | I am not sure what write to buffer or flush buffer are going to be, I have used std::stringstream under the hood.
std::endl is not a valid type of your template function it will not compile (with an error message like : undefined reference to `operator<<(logger&, std::ostream& (*)(std::ostream&))', so you need to provi... |
66,293,039 | 66,293,052 | How to I use the overloaded operator [] in the same class? | Example
class MyMap {
std::map<K,V> m_map;
public:
void myFunc( K const& a, V const& b ) {
// want to use [] operator on the current object.
// something like this->[a] = b;
}
V const& operator[]( K const& key ) const {
//body
}
}
How d... | You can dereference on this, e.g.
void myFunc( K const& a, V const& b ) {
(*this)[a];
}
or call the operator[] in function-call syntax:
void myFunc( K const& a, V const& b ) {
this->operator[](a);
}
BTW: The overloaded operator[] returns V const&, on which you can't perform assignment.
|
66,293,173 | 66,294,788 | Recognizing if one value is larger or smaller than the second value (C++) | My Comp Sci teacher gave us 2 basic C++ tasks to do for homework. I've managed to do the first one, but this second one is confusing me. I'm supposed to write code that recognizes if one value is larger than the other, and print out a message saying if one value is larger or not larger than the other. The code:
#includ... | Problems:
std::cin >> num1, num2; only affects the first argument. The comma operator doesn't make std::cin apply num2 (More info about how comma operator works here).
else if (num1 < num2); does not guard the block cout << "First number isn't bigger than the second" << endl; because of the semicolon after the conditi... |
66,293,191 | 66,293,518 | What is wrong with this iteration method code с++? | Given the problem to solve the equation by the method of iteration, but why the conclusion is wrong, what's the problem?
#include <iostream>
#include <cmath>
using namespace std;
double f(double x) {
return 4*(1+sqrt(x))*log10(x)-1;
}
int main() {
system("chcp 1251>nul");
const double eps = 0.0001;
d... | int main() {
system("chcp 1251>nul");
const double eps = 0.0001;
double x0=-2;
double x1=3;
double oldx0;
do {
oldx0 = x0;
x0 = x1;
x1 = f(oldx0);
} while (abs(x1 - x0) > eps);
cout << x1 << endl;
system("pause>nul");
return 0;
}
|
66,293,237 | 66,293,285 | Set size of boost::shared_array after declaration | I have at the beginning of the code boost::shared_array<uint8_t> buffer(new uint8_t[fileSize]);. I want to change that as size will be read from a file. Therefore, how can I just declare boost::shared_array<uint8_t> buffer and allocate the size after I read it?
I am reading the file with:
size_t fileSize;
union... | Use std::unique_ptr or std::shared_ptr:
std::unique_ptr<uint8_t[]> buffer; // note []
// std::shared_ptr<uint8_t[]> buffer;
// get size
size_t sz = ...;
buffer.reset(new uint8_t[sz]); // allocate memory
|
66,293,332 | 66,293,472 | Append binary number | For example, if my input is 010010, bitmap should be updated to 010010. And since I have to check if the input is either '1' or '0', I have to initialize c to char, after the checking, append it to bitmap, but with the code below what I get is 2 instead of 010010.
How can I do this without using string or array? Thanks... | int ic = c
Does not do what you think it does. As you may know, all characters (char type) are actually 8-bit numbers. Converting them to int results in the same value, but not with regard to the semantics of the digits (eg. '0' == 48 would evaluate as true, while '0' == 0 is false).
A possible solution to your case w... |
66,293,354 | 66,293,413 | searching for the name of a variable linked to a cout! like a:cout c++ | When I was searching for new information through source code in the internet,
I saw someone used goto to a variable, and this variable was linked with a cout
statement, the same as in std::cout.
He wrote a:cout.
Can you help me to find the name of this function?
void Main_Menu() {
int i;
cout << "\n\n\n\n\n\n\n... | There is no variable a linked to cout. The a: is a label that you can jump to with goto a;. The code could also be written like
a:
cout << "\t\t\t\t\t\tEnter your choice: ";
cin >> i;
if (i > 5 || i < 1) {
cout << "\n\n\t\t\t\t\t\tInvalid Choice\n";
cout << "\t\t\t\t\t\tTry again...........\n\n";
goto... |
66,293,430 | 66,294,341 | Why in this case, my Java code runs faster than my C++ code? | I wrote a small benchmark, in which the program creates 108 2-Dimensional std::vector structures of {float, float}, and then sums up the square of their lengths.
Here is the C++ code:
#include <iostream>
#include <chrono>
#include <vector>
#include <array>
#include <cmath>
using namespace std;
using namespace std:... | Try this:
float sum = std::transform_reduce(
std::execution::par_unseq,
begin(vecs), end(vecs),
0.f,
std::plus<>{},
[](auto&& x){
return x.len();
}
);
this explicitly tells the C++ compiler what you are doing, that you are ok with using extra threads,... |
66,294,185 | 66,294,260 | no matching function for call to 'std::vector<std::vector<int> >::push_back(int)' | I made a vector of vectors and i wanted to take values from the user.I simply don't know what is the problem with it
why can't i use push_back() here
and if you have any other method than this please tell.
vector<vector<int>> v;
for(int i=0;i<n;i++)
{
v.push_back(i+1);
for(int j=0;j<n;j++)
{
v[i].pus... | You declared a vector of vectors of the type std::vector<std::vector<int>>.
vector<vector<int>> v;
It means that elements of the vector v has the type std::vector<int> not int.
So the compiler issues an error message for this statement
v.push_back(i+1);
that does not make a sense.
You could use such a call provided ... |
66,294,441 | 66,294,512 | error: cannot convert 'const CHAR**' {aka 'const char**'} to 'LPCSTR' {aka 'const char*'} in C++ | I have a big chunk of code that I am debugging, and I am stuck trying to figure out why I get the following error when I try to build the project:
"error: cannot convert 'const CHAR**' {aka 'const char**'} to 'LPCSTR'
{aka 'const char*'}"
The issue is with the wsKey parameter. SHRegGetValue is a function defined in t... | The line:
LPCSTR wsKey[MAX_PATH] = {"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"};
declares wsKey to be an array of MAX_PATH character pointers, the first of which points to the given string literal. If this is really what you want, then the second argument to your SHRegGetValue call should be tha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.