question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
62,852,221 | 62,852,279 | Does cout/cin internally call printf() / scanf() like `new` calls malloc? | I have looked it up over the Internet. I have found many answers comparing cin vs scanf() and cout vs printf(), but never found if cin actually uses scanf() internally like new operator in C++ uses malloc() function of C.
| The C++ standard does not specify how standard library facilities such as std::cin and std::cout are implemented, only how they should behave. Whether the C++ I/O functions call their C counterparts is up to the implementation.
As an example of how the C++ I/O streams can be implemented, we can look at the source code ... |
62,852,387 | 62,852,702 | std::function vs alias function pointer , why one wont compile | Wanting to investigate the performance hit (if any) of std:function.
I have this struct:
struct InstructionDescription
{
std::string name;
word mask;
word code;
std::function<void(Cpu*, word)> func;
word flags;
};
and I set up a vector of them like this
std::vector<InstructionDescription> instructi... | The std::function is very convenient: it recognizes that &Cpu::Clr is a member function whose first parameter will be a Cpu*.
When you make it a function pointer, this doesn't work like this. You have to use a member function pointer:
using InstrFunc = void (Cpu::*)(word);
Additional info
This is standard: std::funct... |
62,852,559 | 62,852,623 | How to add clicked signal and slot to custom button in qt | I have a Box class that inherits from QPushButton. I want to have a onClick event on the button by using connect (SIGNAL and SLOT) and call a custom function onClick() declared in box.h
box.h
#ifndef BOX_H
#define BOX_H
#include <QPushButton>
class Box : public QPushButton {
public:
Box(const QString& text, QWidg... | your box needs the label for defining slots
class Box : public QPushButton
{
Q_OBJECT
public:
Box(const QString& text, QWidget* parent = nullptr);
//may be public or private
public slots:
void onClick();
};
|
62,852,579 | 62,852,635 | what is the difference between lib-mingw and lib-vc2019 | I'm new to Windows programming and found that lots of prebuilt libraries for Windows offer libraries like lib-mingw, lib-vc2019, lib-vc2017...
Could anyone help to point out
what is the difference? Which library should I use in what case?
If I want to use Clang on Windows, which one should I use?
Why these different l... |
Mingw (GCC), VC2019 and VC2017 are different compilers. Use the library corresponding to your compiler.
I'm not sure but I think none of them will work with Clang. At least on Linux GCC and Clang are very similar. I mean they are mostly binary compatible, many same compiler flags, many same compiler extensions. Clang... |
62,852,663 | 62,852,817 | Does MSVC support C++11-style attributes instead of __declspec? | I know that C++11-style attributes support vendor-specific attributes that are prefixed by a namespace. Both GCC and Clang support various attributes with the prefix either gnu:: (gcc and clang) or clang:: (clang only) which correspond to an equivalent __attribute__((...)) syntax.
The documentation for MSVC attributes ... | There is no [[msvc::noinline]] or other __declspec equivalents as of VC++ 2019.
From the official MSVC documentation for Attributes in C++:
In Visual C++, you can use the [[deprecated]] attribute instead of using declspec(deprecated) and the attribute will be recognized by any conforming compiler. For all other declsp... |
62,852,758 | 62,998,020 | Overload tuple indexing operator - C++ | How can I overload indexing [] operator for std::tuple<int,int,int>? So when I have std::tuple<int,int,int> tup and I type tup[0] I want it to return the reference to get<0>(tup). Is this possible?
| As mentioned in other answers - it is not possible to add any member function to std type like std::tuple. And operator[] has to be non-static member function.
But you can wrap this tuple - and add operator[] to this wrapper type. In such case - you would need to know the common return type for all elements of tuple. W... |
62,852,879 | 62,872,355 | How to send Custom Message from C++ MFC to WPF C# application? | I need to send a custom message/notification from MFC(C++) to WPF(C#) application.
There are some topics over the internet about message sending from C# to C++ application.
I have tried to implement my case followed by those articles but unable to receive message from WPF.
Whatever I have tried is given below:
From MFC... | I can use the code to get the message sent by the C++ project (both deviceAttachedEvent and WM_COPYDATA).
I used FindWindow(NULL,L"WPFwindow name") to get the hwnd handle, instead of GetProp, so make sure you've got a correct window handle. You could use EnumPropsEx to test if you have the property of the "DEVICE_CONNE... |
62,852,882 | 62,852,943 | Problems with std::cin.fail() | I am writing some code to read from the terminal with cpp but for some reason it crashed after running out of numbers. From what I have read online I should be able to check if std::cin was successful by using std::cin.fail() but it crashes before.
The code I am running is
#include <iostream>
int main()
{
int x{};... | Nothing in your input causes cin to set the fail bit. Hence, the while (true) will just keep going. You can enter a letter, or something which is otherwise not an int, which will set the fail bit, and cause the loop to break.
Note that a new line will be ignored for this purpose.
If you know that all your input will be... |
62,852,912 | 62,854,172 | How to take input in a vector inside a vector without knowing it's size? | So I had a question that required me to take input of a list of variable lists of which I was only given the list size and not the lengths of the variable lists inside it.
INPUT:
3
1 5 7 2
3 6 2 6 2 4
6 2 3 5 3
The first line of INPUT is the size of the list of lists, followed by input of each list which are variable... | You can do the thing with the help of the std::stringstream as shown:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main(void) {
vector<vector<int>> mainVector{};
string tempInput = "";
int number = 0;
int lines = 0;
cout << "Enter the number ... |
62,853,246 | 62,853,427 | hacker rank Mini-Max Sum | this problem
I normally erase the default code and start solving the whole thing myself. However, hackerrank test cases show a different output than the one that appears to me whenever i run against custom input. Why does it show different number?
Keep in mind I have tried different input sizes as float, long long int,... | When you are neglecting the last element you are doing an i++ and this will add the arr[5] to the curr value, but arr[5] is out of bound of the array, thus it can give segfault or unexpected result.
I would suggest that you should not increment the i in the for loop, instead you can use continue when you want to negle... |
62,853,331 | 62,853,812 | Get dos_name of usb on inserting or removal | I have designed a program to detect whenever a usb device is connected or removed. I want to know the either the dos path of the connected device or a Guid like this \\?\Volume{17ee3574-7082-4881-aeae-07893db4e957}\
But instead dbcc_name gives me \\?\STORAGE#Volume#_??_USBSTOR#Disk&Ven_JetFlash&Prod_Transcend_8GB&Rev_1... | at the begin you need open Mount Manager and save it handle in class associated with your window, for not open/close it multiple time, bit only once
#include <mountmgr.h>
HANDLE hMountMgr = CreateFileW(MOUNTMGR_DOS_DEVICE_NAME, 0, 0, 0, OPEN_EXISTING, 0, 0);
for query dos like name (if it exist !) you need first get ... |
62,853,489 | 62,856,125 | How to get data for a custom widget using an async source | I'm new to QT and I would like some help. If any of you could help me I would really appreciate it.
QUESTION:
I have an asynchronous class that makes an HTTP request and it's going to receive some data into a JSON format and from there I will extract the necessary information which should be passed to my custom widget.... |
WeatherObject data = api->getWeatherObject(); //HERE I'm getting the DATA
No, you do not get the data here. WeatherAPI::readData is where you get the data.
That is the point of the Signal - Slot mechanism. You do not wait for an event to happen, but react to it via callback, i.e. slot.
Having that in mind, you have t... |
62,853,609 | 62,854,545 | understanding user defined string literals addition for c++20 | I found in user defined string literal the following:
For user-defined string literals, let str be the literal without ud-suffix:
a) If the overload set includes a string literal operator template with a non-type template parameter for which str is a well-formed template argument, then the user-defined literal exp... | This is confusing wording, which was copied directly from the standard:
If [the overload set] contains a literal operator template with a non-type template parameter for which str is a well-formed template-argument
The confusing bit is the question of what "for which str is a well-formed template argument" specifical... |
62,853,650 | 62,853,699 | Array-in-struct initialization in C and C++ | I have the following code in C that works just fine
typedef struct { float m[16]; } matrix;
matrix getProjectionMatrix(int w, int h)
{
float fov_y = 1;
float tanFov = tanf( fov_y * 0.5f );
float aspect = (float)w / (float)h;
float near = 1.0f;
float far = 1000.0f;
return (matrix) { .m = {
[0] = 1.0f /... | You're attempting to use a designated initializer which is allowed in C but not C++.
You'll need to explicitly initialize the individual members:
return (matrix) { {
1.0f / (aspect * tanFov ),
0, 0, 0, 0,
1.0f / tanFov,
0, 0, 0, 0,
-1.f,
-1.0f,
0, 0,
-(2.0f * near),
0
}};
|
62,853,800 | 62,854,125 | How can I create a typesafe handle that behaves almost exactly like int64_t, but disallow implicit conversions between handle types? | Context:
I have created a generic container called "ComponentManager". It looks roughly like this:
typedef uint64_t handle;
template<typename T>
class ComponentManager {
std::vector<T> components; // stores the elements themselves
std::unordered_map<handle, unsigned int> handles; // maps handles to indices
... | You can create a method to do implicit conversions from handle to a uint64_t.
template<typename T>
class handle
{
public:
operator uint64_t() { return key_; }
explicit handle(uint64_t key) : key_(key) {}
private:
uint64_t key_;
}
This will automatically convert a handle<T> to a uint64_t when the context ca... |
62,854,051 | 62,854,436 | Oddity of explicitly marking dependent names as typename and template | Please have a look at this code snippet:
template<typename T>
struct s {
template<int Index>
using type_alias = s<typename T::template identifier<Index>::type>;
};
This is compiling but only due to the explicit typename and template 'markers' for the dependent names at the s::type_alias type-alias.
I wonder ab... | In the syntax:
typename T::template identifier<Index>::type
the typename keyword isn't saying that T is a type - it's saying that the whole thing T::template identifier<Index>::type is a type. When it's not introducing a template parameter, typename always comes before a qualified-id, something containing at least one... |
62,854,825 | 73,774,834 | SFML drawing text causes crash? | #include <SFML/Graphics.hpp>
int main(){
sf::RenderWindow app(sf::VideoMode(800, 600), "SFML window");
sf::Text test;
test.setString("Hello world");
sf::Font font;
font.loadFromFile("Monospace.ttf");
test.setFont(font);
// Start the game loop
while (app.isOpen())
{
// P... | This actually turned out to be an issue with outdated hardware. I bought a new laptop and this was resolved.
|
62,854,830 | 62,942,887 | Error by wrapping C++ abstract class with pybind11 | I'm trying to make a simple example to wrap an abstract C++ class with pybind. The code is:
#include <pybind11/pybind11.h>
#include <ostream>
#include <iostream>
namespace py = pybind11;
using namespace std;
class Base
{
public:
virtual void test() = 0;
};
class Derived: public Base
{
public:
void test() {cou... | You need to "wrap" Base as well. Otherwise you are going to get following exception at import time:
ImportError: generic_type: type "Derived" referenced unknown base type "Base"
Also, wrapping order of Derived is wrong:
py::class_<Derived, Base>(m, "Derived")
Full example:
PYBIND11_MODULE(example,m) {
py::class_<Ba... |
62,855,023 | 62,855,068 | C++ Custom Comparison Functors | I am trying to pass a custom functor into std::map.
So, I declare the following functor and the class whose member is a map in a HEADER file.
class Comp {
bool g;
public:
Comp(bool greater) : g(greater) {}
bool operator()(float lhs, float rhs) const {
... | You need to use initializer list syntax to construct the members:
OrderBook::OrderBook(u_char bookType) :
OrderBookType{bookType},
OrderBookData{Comp{bookType == 'B'}} { }
At the point where you are trying to construct the map, it is already default-constructed. The syntax you're using looks like a function c... |
62,855,087 | 62,855,088 | OpenMP offloading says 'fatal error: could not find accel/nvptx-none/mkoffload' | I'm trying to compile the following simple OpenMP GPU offloading program with G++ 9.3.0:
#include <iostream>
int main(){
const int N=1000;
int d[N];
for(auto i=0;i<N;i++)
d[i] = 1;
#pragma omp target teams distribute parallel for map(tofrom:d[0:N])
for(size_t i=0;i<N;i++){
d[i] *= 3*i+1;
}
for... | You haven't installed GCC's offloading capabilities. On Ubuntu/Debian systems you can do so with:
sudo apt install gcc-offload-nvptx
Or install for a specific version of GCC with, e.g.
sudo apt install gcc-9-offload-nvptx
|
62,855,396 | 62,865,366 | C++ question: User think a number 1-100, program asks questions no more than 6 times to get answer. can't get correct | User has to think of a number from 1 - 100. Computer keeps asking not more than 6 times to get what
the user think number. I could not get the logic right, I don't know how to fix anymore. Please somebody help me.
#include "std_lib_facilities.h"
// this program is not correct
// try 24 you will see it
int main()
{
... | As has already been pointed out in the comments section, there are at least 3 bugs in your code:
Your question states that the user should think of a number between 1 and 100, but the variables min and max are initialized to 0 and 100, as if the user was supposed to think of a number between 0 and 100. Therefore, you ... |
62,855,721 | 62,855,860 | How to send python list to C++ application awaiting input? | I am writing a python script that generates a list of integers and is supposed to send this list to a concurrently running C++ program that is constantly awaiting input. What is a quick and painless way to design the link between these two languages?
I have considered possibilities such as:
writing the python result t... | You could set up a Socket and an OutputStream in the python app to send the data, and another Socket and an InputStream in the C++ program to receive the data.
|
62,855,777 | 62,855,800 | Why do we need to use a stringstream when splitting a string? | Please note, I've never used streams before today, so my understanding of them remains rather vague. Apologies when I say something appallingly stupid.
Here I have a short bit of code that splits up a stringstream into a bunch of strings at each space.
vector<string> words;
stringstream ss("some random words that I wro... |
What's storing "some random words that I wrote just now" as a stringstream going to do to help us here? Is it just making a stream of characters so that we can check through them? Is this necessary?
std::stringstream just allows you to use the usual input/output operations such as >> and std::getline on a string. You... |
62,855,785 | 62,856,187 | Karatsuba Implementation C++ | So I've decided to take a stab at implementing Karatsuba's algorithm in C++ (haven't used this language since my second coding class a life time ago so I'm very very rusty). Well anyhow, I believe that I've followed the pseudocode line by line but my algorithm still keeps popping up with the wrong answer.
x = 1234... | There are a lot of problems in your code...
First, you have a wrong coefficient here:
int q = b + c;
Has to be:
int q = c + d;
Next, the implementation of splitHalves doesn't do the work. Try that:
tuple<int, int> splitHalves(int x, int power)
{
int divisor = pow(10, power);
re... |
62,855,820 | 62,856,009 | How to enhance this YUV420P to RGB conversion in C/C++? | I'm trying to write an YUV420P to RGB888 for when I have the entire thing as one giant buffer with Y (of size width*height) then Cr (of size width*height/4) then Cb (of size width*height/4). The output should be an RGB buffer with size width*height*3.
I think my function below is very inefficient. For example, I use th... | Is it just me, but but shouldn't you be reading from the yuv array and writing to the rgbData array? You actually have it reversed in your implementation.
There's not need to invoke ceil on an integer expression such as i/4. And when you implement an image processing route, invoking a function call on every pixel is ... |
62,855,836 | 62,855,886 | convert tuple types to decay types | I'm playing with C++17, and I have a std::tuple of const &T types. For ex:
template <typename... members>
auto make_cr_tuple(members const &...args) -> decltype(auto) {
return std::make_tuple(std::cref(args)...);
}
int main() {
std::string s;
int i = 0;
auto crt = make_cr_tuple(s, i); // std::tuple<con... | Maybe you can declare (no definition needed) a function as follows
template <typename ... Ts>
constexpr auto decay_types (std::tuple<Ts...> const &)
-> std::tuple<std::remove_cv_t<std::remove_reference_t<Ts>>...>;
and use it through std::declval() and decltype().
Maybe you can also add an using alias to simplify th... |
62,855,871 | 62,856,327 | Populating array with unique int | I have an Arduino sketch which generates random numbers. I need to populate an array with 5 unique generated numbers. In order to do that inside the loop() I did the following:
for (int i=0; i<5; i++){
number=mappedForNumber(50);
if (isUnique(number)==true){
numbers[i]=number;
}
}
where number is a global int a... | You are using a for loop to populate your numbers array.
This for loop will populate the selected index with a number if it is unique and not change the data inside the index if it isn't.
To fix your code:
int i = 0;
int number;
while(i < 5)
{
number = mappedForNumber(50);
if (isUnique(number) == true)
{
numb... |
62,856,155 | 62,856,182 | c++ no suitable constructor exists to convert from "int" to "std::pair<int, int>" | I am having trouble resolving this error. I am not having any luck on Google when I search for this error.
no suitable constructor exists to convert from "int" to "std::pair<int, int>"
#include <utility>
using namespace std;
pair<int, int> solve(int s, int g)
{
return s % g != 0 ? (-1, -1) : (g, s - g);
}
The... | (a, b) is not a pair, it's an expression using the comma operator. It evaluates both the a and the b, but the result of the expression is the b only. That's why it's complaining that it cannot convert your single int into a pair.
For example:
d = (a++, b+=3, c);
will:
add one to a;
add three to b; and
set d to whatev... |
62,856,209 | 62,856,568 | Attributes in c++ and their use | The most recent c++ feature(that is also quite modern) that I found about is attributes. They seem quite useful for signalling the compiler, but apart from that, what other more specific uses can attributes have? How can custom attributes be created and used and what is the main idea behind the use of c++ Attributes? I... | Attributes (that is, attributes as a feature of the C++ language, not compiler-specific __declspec or __attribute__ attributes) are kind of a C++ hack. They're a solution to meta-problems with the evolution of the C++ language.
For example, keywords. There's a lot of C++ code out there, and any new version of the langu... |
62,856,584 | 62,856,978 | heap-use-after-free when declaring a variable as a reference | The pasted code below returns a heap-use-after-free error. When I remove the reference symbol '&' on the line with coord &c = q.front(); q.pop();, the error is resolved.
From what I understand, the C++ garbage collector deletes the coord I retrieved from q.front() when there are no more references to it. Though it seem... | coord &c = q.front();
^^^ This line sets c to refer to the pair<int,int> that is currently at the front of the queue.
q.pop();
^^^ This line removes the item at the front of the queue, destroying it in the process). So after this line returns, your c reference is pointing to an invalid object, which means that tryi... |
62,856,671 | 62,859,840 | Find the index of the closest number that is greater than the current number | For each integer in an array of positive integers, find the index of the closest integer that is greater than the current integer. Also, we need to search for the answer only to the left of the current integer.
For example -
Input array - [ 5, 4, 3, 6, 2, 3]
Output array - [ -1, 0, 1, -1, 3, 3]
Assign -1 to those numb... | I believe one popular O(n) solution is to use a stack, maintaining a descending sequence (hopefully the algorithm is clear enough from the commented code):
function f(A){
let stack = []
let output = []
for (let i=0; i<A.length; i++){
// While there are lower or
// equal elements on top of
// the st... |
62,856,894 | 62,858,236 | How to register SFML Vector2 operators with AngelScript? | I'm working on a game engine that uses SFML. I'm currently working on adding scripting with AngelScript, however, I'm having trouble registering sf::Vector2 with AngelScript. I have the basic constructor set up, I can use sf::Vector in AngelScript, but I need to add operators, since Vector2 foo = Vector2(10.0f, 5.0f); ... | sf::Vector2 is a template class, SFML contains a typedef for a Vector2 that uses floats called Vector2f
https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Vector2.php
|
62,856,976 | 62,856,997 | Class does not name a type error in C++ Code | I'm trying to make a small game in C++ and I'm already running into problems adding adding my Player class into my Game class. I thought this was a circular dependency issue, but forward declaring the class didn't help the issue!! I've looked everywhere and just can't figure it out so hoping to get some understanding a... | You have a class Player and a member of Game named Player. Once the member declaration is encountered, all references to Player within the Game class will be to the member variable, not the global type.
There are ways to get around this (e.g., ::Player *GetPlayer) but the best and least confusing fix would be to rename... |
62,857,397 | 62,887,505 | Fail-safe code in c++ after access is denied | I am very new to programming. I want to run a program with C++ which will prompt administrative permission to the user in windows. Is there any way to run another bunch of code if the permission is not granted??
system("setup.exe");//This will prompt administrative permission to the user. If permission is denied then I... | As I told I am very new to programming. So U was trying different codes without knowing what actually they are supposed to do. So finally a simple code servrd my purpose though I dont know what actually happening there. The code is
if(system("setup.exe")){printf("Give administrative permission next time");}
|
62,857,452 | 62,857,974 | libssh's functions couldn't be found on qt and cmake error while building libssh | I want to use libssh library in Qt and my os is ubuntu 18.04 .
so I cloned the library's file and tried to build it with cmake.
I followed the tutorial in INSTALL folder but the building process can't be completed.
at first I had this error :
Could NOT find CMocka (missing: CMOCKA_LIBRARIES CMOCKA_INCLUDE_DIR)**
i use... |
file INSTALL cannot copy file
"/home/heydari.f/libssh-mirror/build/libssh.pc" to
"/usr/local/lib/pkgconfig/libssh.pc"
This is a permissions issue. Use sudo make install to solve this. sudo gives root privileges to a command. Use it carefully.
** error: undefined reference to 'ssh_session_is_known_server'**
un... |
62,857,523 | 62,857,715 | Modular operation (%) provides false output | With a function, getNextIdx, I want to receive a new index for an array that depends on the current index and the value of the array at that index.
I want the function to return the new index by summing the current index with the value of the array at that index, modular to the array size.
#include<vector>
using names... | The modulus operator rounds towards zero (even for negative numbers). Your math expects modulus to round towards negative or positive infinity. See Modulo operation with negative numbers
int getNextIdx(int currentIdx, vector<int> array){
int jump = array[currentIdx];
int nextIdx = currentIdx + jump;
if (nextIdx <... |
62,857,762 | 62,857,811 | Delete objects created during object construction? | If objects are created during the construction of a class like this:
class MyClass
{
private:
std::vector < MyObject*> MyObjects = { new MyObject };
...
Do I need to delete the objects in the vector during the destructor?
| Yes, std::vector < MyObject*> MyObjects contains pointers to objects. The vector assumes it does not own the objects, so it does not delete them by default.
If you want the objects to be destroyed automatically either change the type:
std::vector <std::unique_ptr<MyObject>> MyObjects
Or, delete all the pointers in the... |
62,858,621 | 62,858,690 | Assignment in an 'if' statement. How is the output correct? | Code in case if the image not is visible.
#include <stdio.h>
int fun(int n)
{
if(n=4)
return n;
else
return 2*fun(n+1);
}
int main()
{
printf("%d", fun(2));
}
This is the code snippet and the output is given as 4 by the professor.
How is the output correct?
Is it possible that n=4 is assi... | The answer is correct, and there aren't any syntax errors.
= is an assignment operator, and in C/C++, (n = 4) is a valid expression that evaluates to true as long as the expression is not (n = 0), because n will then be considered as false by C. Note that in C/C++, 0 is false and everything else is true.
Hence, if (n =... |
62,859,060 | 62,861,865 | Error using auto for return type of specialised template function | consider the following code snippet (simplified from a more complex code):
#include <typeinfo>
#include <iostream>
struct A{
template<int S>
void print(){ std::cout << S << std::endl; }
};
struct B{};
template <class T>
A foo(int);
template<>
A foo<B>(int){ return A{}; }
template<class T>
int bar(int){
a... | For all the compiler knows, somewhere in the program it has not yet seen there exists a specialization of foo for some T that returns something other than A. So it cannot assume res is always A. Therefore, the type of res does in fact depend on the template parameter T, and then res.print is a dependent name after all.... |
62,859,575 | 62,859,899 | Execute Command with QProcess and Store result in QStringList | I have written the following function which executes a windows enumeration command for getting shared folders and store the result in a QString.
QProcess p;
p.setProgram("wmic");
p.setArguments({"share", "get", "name"});
p.start();
if (!p.waitForFinished()) {
return;
}
const QStrin... | You could just use qstring split:
QStringList list = output.split("\n", QString::SkipEmptyParts);
If you need a more "intelligent" split that you can pass in a regex:
list = output.split(QRegExp("...some regex..."));
The skip empty parts just "removes"/ignores any values that would be empty - I don't think you need t... |
62,859,596 | 62,860,781 | Difference between std::atomic and std::condition_variable wait, notify_* methods | I was looking through 'Atomic operations library' and came across a new c++20 feature of atomic 'wait' and 'notify_' methods. I am curious on what the differences are in regards to std::condition_variable's 'wait' and 'notify_' methods.
| std:atomic wait, notify_all and notify_one methods are similar to methods of conditional variables. They allow the implementation of the logic that previously required conditional variable by using much more efficient and lightweight atomic variables without using a mutex.
The wait function blocks the thread until the ... |
62,859,624 | 62,860,063 | Parsing long strings of binary data with C++ | I am looking for idea how to parse long binary data, so for example :"10100011111000111001"
bits: 0-4 are the id
bits 5-15 are the data
etc etc...
the binary data structure can be change so I need to build a kind of data-base will store the data how to parse each string.
illustration (it could be 200~ bits) :
Ideas h... | Options available
To manage a large structured set of bits, you have the following options:
C++ bit-fields: you define a structure with bitfield members. You can have as many members as you want, provided that each single one has no more bits than an unsigned long long.
It's super easy to use; The compiler manages the... |
62,859,649 | 62,949,356 | How to sort point cloud data? | I would like to try priority queue from point cloud data.I think need to insert pointers to array.But there seems to be no way.How do I solve this problem?Thanks~~
typedef struct tagNode
{
double point_X;
double point_Y;
double point_Z;
} Node;
struct classcomp
{
bool operator() (const Node& a, con... | Why do you need to define your own point type? PCL already has pcl::PointXYZ. And cloud->points is actually an std::vector of pcl::PointXYZ.
So what you're looking for is:
struct classcomp
{
bool operator() (const pcl::PointXYZ& a, const pcl::PointXYZ& b) const
{
return a.x < b.x;
}
};
pcl::PointCl... |
62,859,822 | 62,859,850 | Why is std::valarray non-arithmetic? | I've noticed that std::is_arithmetic<std::valarray<float>> evaluates to false. Isn't the entire point of valarrays to facilitate overloading scalar code to 'auto-vectorise' without resorting to boost etc. ?
Why does it not inherit the arithmetic properties of its templated type?
My question isn't necessarily a problem,... | std::is_arithmetic tells you if the type is a fundamental numeric type like an integer or a float. It does not work for classes. And you are not allowed to specialize it yourself, so you can't "fix" it, but you can write your own type traits that do whatever you want.
By the way, std::is_array<std::array<int, 5>> is ... |
62,859,934 | 62,859,975 | How can i make shared pointer from a class object with move semantics | This is my class for Mesh object
struct texture
{
std::string textureName;
unsigned int textureId;
};
class Mesh
{
public:
/* Mesh data */
std::vector<texture> textures;
/* Functions */
Mesh(std::vector<texture> &text);
Mesh(const Mesh& mesh) = delete;
Mesh& operator = (const Mesh&... | If you add a move constructor then the default copy constructor is implicitly deleted and std::make_shared<Mesh>(m) uses the copy constructor. That's the reason why you get an error message like this:
error: use of deleted function 'constexpr Mesh::Mesh(const Mesh&)'
-> decltype(::new((void*)0) _Tp(std::dec... |
62,859,937 | 62,860,189 | when does a function will include stack _Unwind_Resume call in c++? | I am now studying c++ exception and a trouble comes to me, program show as below
#include<iostream>
#include<unistd.h>
#include<string>
#include<thread>
#include<vector>
#include<exception>
using namespace std;
vector<int> vec(20);
void fn()throw() {
vec.at(10);
}
int main(){
fn();
return 0;
}
I... | Since fn2 only calls fn, which is declared as throw(), no exception can propagate to an active stack frame for fn. GCC recognizes this situation and optimizes the exception handler away.
In the original case, this is not possible because std::vector::at(size_type) can throw. The exception handler is only needed because... |
62,860,185 | 62,860,934 | Algorithm for max number of pairs with two limits | I guess that such an algorithm already exists.
I have two (or more, but two is sufficient for this problem) limits, e.g. limit_a=20 limit_b=18. Then I have some (a, b) pairs, e.g.
(5, 5), (3, 3), (4, 2), (1, 7), (3, 2), (5, 9), (7, 4)
The answer should be 5. An example of a solution: (7, 4), (3, 2), (1, 7), (4, 2), (3,... | It is a 2D knapsack problem, just the profits are all 1. The usual approach of generating subsets interleaved with pruning where a partial subsolution obviously dominates another applies.
Some quick code below, using sorting instead of a merge for convenience.
#include <algorithm>
#include <iostream>
#include <tuple>
#... |
62,860,606 | 62,860,755 | multiple threads for vector processing | I have 2 vectors with some filenames and function that process this files:
vector<string> vecFilenames1; // {filename1_1, filename1_2, filename1_3, ...}
vector<string> vecFilenames2; // {filename2_1, filename2_2, filename2_3, ...}
This vectors have same size. How I process now:
// function for processing
void doSomeSt... | You should partition vector into ranges and process each range in a threadpool thread.
C++17 parallel algorithms is an easy way to accomplish this. By using std algorithm, you don't need to do things like partitioning vector, and calling thread pool manually.
You can use Intel TBB library or Open MP directives to achie... |
62,860,623 | 62,860,679 | Recursive unordered_map | I have a tree structure that internally uses unordered map
#include <unordered_map>
struct Node {
std::unordered_map<int, Node> children;
};
int main() {
Node a;
}
It works just fine on Apple clang 11.0.3 and MSVC v19.24, but it fails to compile on clang 10.0.0 and gcc 10.1
While regular std::map wor... | STL containers are not required to work with incomplete types. If you don't mind extra indirection, then the workaround is std::map<int, std::unique_ptr<Node>>
|
62,860,772 | 62,860,803 | CHECK(call) function get error in Google Colab | I just copied a function from normal CHECK(call) function in CUDA and run with nvcc_plugin in Google Colab
#define CHECK(call)
{
const cudaError_t error = call;
if (error != cudaSuccess)
{
printf("Error: %s:%d, ", __FILE__, __LINE__);
printf("code:%d, reason: %s\n", error, cudaGetErrorString... | #define CHECK(call) \
{\
const cudaError_t error = call;\
if (error != cudaSuccess)\
{\
printf("Error: %s:%d, ", __FILE__, __LINE__);\
printf("code:%d, reason: %s\n", error, cudaGetErrorString(error));\
exit(1);\
}\
}
You have to add backslashes, if you want to have a multi-line... |
62,861,185 | 62,861,674 | C++ Vector iteration | I have a vector of int P=[n1,n2,n3]. what is the most efficient way to generate another vector of , the same size as P, call it v1=[m1,m2,m3]. Step:
vector < int> P[N], N ,contains n0, n1, n2
for each n_i in N , generate a vector of normal random variable with size n0, then n1, n2
Take the sum of each new vector ind... | You probably need something like this:
vector<vector<int>> vec;
vector<int> v;
v.reserve(p.size());
for (auto &&i : p) {
vector<int> temp(i);
for (auto &&j : temp)
j = U.RandomNormal(4000, 7000);
v.push_back(accumulate(temp.begin(), temp.end(), 0));
vec.push_back(move(temp));
}
In place of
fo... |
62,861,510 | 62,866,932 | Take a reference to a pointer with erased type (void*) | I can take a T*& from a T*. Now I need to store my T* in a type-erased way, more specifically as a void*. Can I take a T*& from a void* ? (knowing, of course, that my void* does point to Ts)
Example:
#include <iostream>
#include <cstdlib>
#include <numeric>
int main() {
int n = 10;
void* mdbuf = malloc(n*sizeof(do... | I'm going to take your second example and rewrite parts of it using aliases to better illustrate what you're asking for.
using V = void*;
using K = double*;
double d;
V v_ptr = reinterpret_cast<V>(&d);
V &v_ptr_ref1 = v_ptr; //Refers to the `V` object denoted by `v_ptr`.
K d_ptr = &d;
K &d_ptr_ref1 = d_ptr; //Refers t... |
62,861,523 | 62,862,398 | Calculate SHA1 hash like Git with Qt C++ | I'd like to hash a file in the same way that git hash-object does, so I can compare it to an existing hash, but using Qt and C++.
The answers to this question show how to get the same hash, but none of the examples use C++.
So far this is what we've tried:
QString fileName = entry.toObject().value( "name" ).toString();... | The problem is that on the one hand, QString ignores \0 as termination string, on the other hand, QByteArray always appends extra \0. From Qt's docs:
Using QByteArray is much more convenient than using const char *.
Behind the scenes, it always ensures that the data is followed by a
\0 terminator, and uses implicit sh... |
62,861,752 | 63,035,657 | Cast to reference type | Chapter 4.11.3 of the book C++ Primer says the following:
A named cast has the following form: cast-name<type>(expression);
where type is the target type of the conversion, and expression is the value to be cast. If type is a reference, then the result is an lvalue.
Can anyone give an example of this? Is conversion t... |
Is conversion to a reference even possible?
Yes, depending on the object you begin with.
Most simple example is one lvalue reference converted to another. This can even be an added cv-qualifier (or removed, with const_cast), such as:
int const & foo(int & i) {
return static_cast<int const &>(i);
}
the derived-to... |
62,861,893 | 62,862,067 | Qt C++ Is static thread_local QNetworkAccessManager good choice for threaded application? | I'm using threaded application written in Qt (C++).
I need to make get/post request very often from separate threads.
Qt doc says:
One QNetworkAccessManager instance should be enough for the whole Qt
application. Since QNetworkAccessManager is based on QObject, it can
only be used from the thread it belongs to.
Is st... | No, not a good choice.
You shouldn't create static or global QObject subclass instances, because you generally need them to be created after the Qt application object has been created (a lot of Qt stuff depends on the application object existing already). C++ does not really provide very good control over when static o... |
62,862,294 | 62,862,390 | How does object pointer works in c++? | I was trying to understand how a objects are stored in memory (heap) and how reference variable works. I wrote a simple program to understand the concept. But Why I am getting dereferenced address i.e. *(&cat) but not the &cat when function callBar() returns the address?
#include<iostream>
using std::cout;
using std::s... |
It is still not clear to me why I am getting dereferenced address i.e. *(&cat) but not the &cat when function returns?
Inside callBar the relevant bits are...
Cat* callBar(...unused argument...){
cat = new Cat();
cout << &cat << "\n";
cout << *(&cat) << "\n";
return cat;
}
You're not getting &cat bac... |
62,862,562 | 62,862,790 | Can we rethrow exception using constructor if yes then why? | class A
{
int a,b;
public:
A(int X,int Y)
{
X = a;
Y = b;
try
{
if (b == 0)
throw b;
else
cout << a / b;
}
catch (int a)
{
cout << a; //throw;can we rethrow??then what is purpose of ... | An exception in the constructor means something really bad happened, and since constructors can't return a (invalid) value to indicate failure in proper object construction, there are 3 options: to initialize the object in some special state in a hope that somewhere else in the caller code it'll be checked and handled ... |
62,862,688 | 62,863,117 | How to flatten a 3D array where the 3d dimension is not fixed size into 1D array? | Given a 2D array where each (x,y) cell contains a vector of strings (for simplicity) of different size.
What's the most efficient way to flatten this data structure into 1D array, i.e. creating a function mapping injectively each string to {1,...,n} where n is the total number of strings in the data structure.
| You can map an index i, j, k to linear position p in O(1) and back in O(log N), where N is the size of the 2D array, not the total number of strings.
First, let's treat your 2D array as a 1D, since that just makes things much easier. Index i is the index of a vector in the array. Index k is the position of a string in ... |
62,862,776 | 62,863,009 | using methods with parameter(s) in void_t for SFINAE | I'm trying to build a struct is_container for using it on SFINAE template
template<typename T, typename = void>
struct is_container : std::false_type {};
template<typename T>
struct is_container<
T,
std::void_t<
typename T::value_type,
typename T::reference,
typename T::const_referenc... | You already used declval once to get something for a member function access. So just use it again to get an lvalue argument.
decltype(std::declval<T>().swap(std::declval<T&>()))
|
62,863,102 | 62,867,549 | C++ atomic CAS(compare-and-swap) operation does not change value | In the following example, what actually happens? Why value does not changes after successful exchange?
Live: https://wandbox.org/permlink/f5VYSKfQ9UJqa8FQ
std::atomic<bool> flag{false};
int main()
{
std::thread thread([](){
while(true){
// wait until flag not becomes true
{
... | Consider what happens with:
bool expect = true;
while(!flag.compare_exchange_strong(expect, false, std::memory_order_acq_rel)){
std::cout << "wait" << std::endl;
}
when the flag is false. The first time the test in the while loop runs, expect will be true, so does not match... |
62,863,614 | 62,864,942 | gcc app runs irregularly but clang works fine | I have written a simple stack based virtual machine you can view it's source at https://github.com/radinParsaei/VM
when I compile it with clang it works well but if it compiles with GCC in bytecodes I have coded like pop() / pop() it work irregular and it returns stack[stack.size() - 2] / stack[stack.size() - 1] i fix ... | As @IlCapitano says, your second pop() may be called first:
There is no concept of left-to-right or right-to-left evaluation in C++. This is not to be confused with left-to-right and right-to-left associativity of operators: the expression a() + b() + c() is parsed as (a() + b()) + c() due to left-to-right associativi... |
62,863,726 | 62,863,785 | Why does const std::pair<K,V>& in range-based for loop on std::map not work? | When accessing the elements of a std::map via const auto& entry in a range-based for loop I get a reference to the actual data in the map. Using const std::pair<K,V>& on the other hand does not give a reference to the data in the std::map
Consider this example (compiled with gcc 7.4, -std=c++14)
#include <map>
#include... | std::map<K, V>::value_type is std::pair<const K, V>, not std::pair<K, V> (see cppreference)
#include <map>
#include <string>
#include <iostream>
int main(void)
{
std::map<std::string, int> my_map {{"foo", 42}};
for(const auto& entry : my_map)
std::cout << entry.first << ' ' << entry.second << ' ' << &(... |
62,863,786 | 62,863,833 | Implement a template function that iterates over collection | How do I implement this template function which in future selects the fast vehicles by iterating over the collection that is provided?
void select(T test, std::list<const Vehicle*>& vehicles): a
template function that iterates over the vehicles stored in the m_vehicles, and adds to the second parameter all vehicles fo... | You have to test a vehicle, so you have to pass a vehicle to the test function.
So the call to test should be inside your loop, not outside, and you pass the dereferenced iterator to it. I.e.
for (auto it = m_vehicles.begin(); it != m_vehicles.end(); ++it)
if (test(*it)) // perform the test on a vehicle
veh... |
62,863,875 | 62,864,159 | Why won't cmake permit <> style include? | I am very new to cmake, but I am using it on Visual Studio to develop a program that has to run on linux. I need to include the following in this manner:
#include <xscontroller/xscontrol_def.h>
#include <xscontroller/xsdevice_def.h>
#include <xscontroller/xsscanner.h>
#include <xstypes/xsoutputconfigurationarray.h>
#in... | The simplest way to achieve this is using include_directories command. Simply add the following to your ANT/CMakeLists.txt:
include_directories(${CMAKE_CURRENT_SOURCE_DIR})
Though I would highly recommend using target_include_directories() instead. The difference between the two is that target_include_directories() sp... |
62,864,084 | 62,864,553 | Template class not recognizing friend operator | So I'm trying to include two friend declarations for the input and output operator in a template class but every time I compile the code it doesn't seem to recognize the operator.
here is my header file.
ERROR:Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external sy... | friend std::ostream& operator<< <> (std::ostream&, Screen&);
--
Without these two characters, the friend declaration declares a non-template. That is, when you instantiate Screen<3,5>, it will attempt to find a function with this signature
std::ostream& operator<< (std::ostream&, Screen... |
62,864,164 | 62,868,602 | How to get keyboard layout in Mac OS X with C/C++ | I need to get the keyboard layout being used on Mac OS X. I've found old restonces to this but they all are something like this:
How to change the Mac OS X Keyboard Layout programmatically?
which doesn't work any more. Any help would be much appreciated.
| In case someone is interested, I was finally able to get the keyboard layout with the following code:
#include <Carbon/Carbon.h>
int main() {
char layout[128];
memset(layout, '\0', sizeof(layout));
TISInputSourceRef source = TISCopyCurrentKeyboardInputSource();
// get input source id - kTISPropertyInput... |
62,864,301 | 62,864,573 | Exponential compilation times with simple typelist implementation. Why? | I am trying my hand at C++ type lists. Below is a trivial implementation of a type list filter function. It seems to work except that compilation times in both gcc and clang are horrific beyond say 18 elements. I was wondering what improvements I could make to make this practical.
#include <type_traits>
// a type list... | using type = typename std::conditional<
// Does the predicate hold on the head of the input list?
P<Head>::value,
// The head of the input list matches our predictate, copy it
typename filter_tl_impl<tl<Tail...>, tl<Ts2..., Head>, P>::type,
// The head of the input list does not match our ... |
62,864,410 | 62,864,650 | Nested function inherit value from outer scope without passing | I have defined a function inside of another function. I would like to access a variable in the outer functions scope while in the inner functions scope. I do not want to pass the variable x into the function, I want for it to be known.
#include <iostream>
int main() {
double x = 1;
auto f = []() {std::cout << ... | This is called lambda capture and it's what the leading square brackets in a lambda expression are about. You basically have two options:
By-value capture:
auto f = [x](){ std::cout << x; };
Lambda object receives its own private copy of the object so any subsequent changes to the outer x have no effect on the lambd... |
62,864,434 | 62,865,270 | Recursion calls in Merge sort | Running merge sort and printing the left part gives me the following output for given input, I am not able to understand why it is printing 2 at the end. Please help me with how this recursive calls are
Input: (size of array and in the next line is the array)
5
8 5 4 2 1
and the output is
8
5 8
4 5 8
2
1 2 4 5 8
her... | That's because you call cout only on the left side of the vector (for each recursion call) in a depth first visit: you always print what happens on the left and only for the left nodes (and after the left side has been sorted). This drawing should help you understanding:
85421 represents your first call to merge_sort... |
62,864,626 | 62,864,678 | Compare templated type to certain class/type in C++ | I am trying to find the type of thee class passed into a template as such
template<typename ret>
ret copy(ret var){
if(ret == int){ //problematic line
cout << "int" << endl;
}
return var;
}
int main()
{
int a = 5;
auto b = copy(a);
cout << b << endl;
return 0;
}
But it is returnin... | Unlike python, in C++ int is not an object of type class (or something along those lines). You can't compare it like that. Instead, you can use
template<typename ret>
ret copy(ret var)
{
if constexpr(std::is_same_v<ret, int>)
{
std::cout << "int\n";
}
// and so on....
Edit: (in response to com... |
62,864,755 | 62,872,603 | What is the fastest way to pass data arrays through the JNI? | I am developing an Android app using native code for Oboe. I generate data on the c++ side and need to draw that data to a custom View. I also generated data for Oboe from that data.
I could also generate the data on the Java side and pass it to c++, and generate the Oboe data from there. The app is not real time, but ... | First of all, measure to see if you can live with the copy (by means of Set*ArrayRegion). It is by far the simplest architecture.
If you cannot, a direct byte buffer shared between Java and C++ would indeed be the optimal solution. Keep in mind that creating a direct byte buffer is potentially expensive, so strive to r... |
62,864,802 | 62,864,844 | How to 'NULL' a string in c++ | I am new in C++ and now I am learning how cin and cout works. The case is, as you can see in the code below I create a string, and a char * in order to compare the C way to read a string and the C++ way. In C++, it makes sense that if I create a string then I worry about to set this string to NULL?
#include <iostream>
... | You don't have to worry about setting a std::string object to NULL.
And you don't have to clear() it if it is just going to go out of scope right afterwards. Its destructor will handle freeing any memory used for the character data for you.
|
62,864,918 | 62,898,149 | idiomatic C++14/C++17 approach to enumerating environment variables | Here is the code to enumerate all the environment variables.
#include <iostream>
#include <cstdlib>
int main (int argc, char *argv[], char *envp[]) {
char **p = nullptr;
p = envp;
while (*p) {
std::cout << *p << std::endl;
p++;
}
return 0;
}
i have referred to the e... | There is no other way to enumerate the environment variables than you have in your question or in the linked answers. The reason is that the interface to environment variables is defined in such a way that C code can access them, so you have to do it "the C way" even in C++. C++ does not define its own way to access en... |
62,864,970 | 62,865,186 | C++ array[size] greater than 65535 throwing inconsistent overflow | Building a struct array with size [x>65535] throws 0xC00000FD error, even if x is declared as int64_t, but inconsistently. Will work fine in one line, not in the next.
int64_t length;
length = (pull from other code);
Foo foo[length];
//^ this works
Foo2 foo2[length];
//^ this one doesn't
Is this a problem with array c... | Problem 1
VLA (Variable Length Arrays) aren't in standard C++. This means the following is illegal (even if it works):
int length;
cin >> length;
int array[length];
Problem 2
What is 0xC00000FD error code? It means stack overflow exception. That means you exceeded the stack limit set by your operating system. Since yo... |
62,865,168 | 62,865,296 | Is this example from a book a bad? | I'm reading through A Complete Guide to Programming in C++ written by Ulla Kirch-Prinz and Peter Prinz, published by Jones & Bartlett. In it, there is an example of a class (page 246) with what I think is a major problem--not in that it is an error but something I've heard you are never supposed to do:
// account.h
//... | Yes, these are reserved names, though you are unlikely to actually run into a problem.
Note that in this case it's only reserved because it is followed by an uppercase letter. +account would be fine.
And yes, I would agree that books really should not be perpetrating this style. It basically stems from people having go... |
62,865,920 | 62,902,573 | C++ accepts wrong return-type | I have the following code, which, in my opinion, should not compile:
(In a class Vector (not the std::vector, but a Vector that I defined myself)):
Vector operator*(double factor)
{
// some element-wise multiplication here
return factor;
}
I am defining this operator to return a Vector, but inside the method i ret... | Basing this answer on received comments:
Non-explicit conversion-operators are not the only way in which a return-value that initially has the wrong type may "become" the type needed for the function-signature.
The constructor
Vector(size_t dimension);
Takes one numerical value as an argument, which itself is not a do... |
62,866,373 | 62,874,839 | how to switch windows between cpp files? in Qt | I have problem with my small app in Qt framework C++
I have a first window which there's two buttons where you can choose to play music or video. The music button will close the "choose window" and should open "music window" and similarly for video button.
I don't know how to do this... I know a way which I've leant an... | I found my answer in Qt Forum:
https://forum.qt.io/topic/68602/child-window-in-taskbar/3
@Radek(Qt Forum): Try passing 0 (zero) as parent when you create them.
FirstWindow.cpp:
void FirstWindow::on_musicChoose_clicked()
{
this->hide();
mw = new MusicWindow(0); // passing nullptr as parent
mw.show();
}
void... |
62,866,487 | 62,866,680 | Qt5: Strange compilation error while using QCommandLineParser class | For my application I had to derive QtCoreApplication and use QCommandLineParser. I declared QCommandLineOptions instances in a separate namespace and wanted to declare the parser in this namepsace as well. However I get an error that I don't quite understand.
namespace
{
QCommandLineParser parser;
const QC... | You can't have expressions like parser.addOption(optA) or options << optA in a namespace declaration. This is just C++ thing and has nothing to do with Qt. I would suggest you rather put the parser and optA variables in your MyApp class and initialize them in the MyApp constructor
class MyApp : public QCoreApplication
... |
62,866,924 | 62,867,494 | Download XLS files in a Cpp loop | Developing from my previous question, wanted to generalize the behavior so that would download files within a specific data range.
So, modified the code to look like this
#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include <ctime>
#include <iostream>
#include <iostream>
#include <stdio.h>
#incl... | You assign to date only once:
mytm date(2007, 1, 1);
And never modify that. So of course it doesn't change.
Update date before you format the new filename.
|
62,866,927 | 62,867,232 | Time complexity while with unknown value | I have a queue with an unknown size queue<int> q;
What is the time complexity of this while loop?
while(!q.empty())
{
count<<q.front();
q.pop();
}
I don't know the size of q, how could I know the time complexity?
| You time complexity is determined in terms of a variable, in your case that is the number of elements in the q, it's call it n. So you need to visit each element once and only once, so you get O(n).
|
62,867,113 | 62,867,194 | cmake error for header-only library: `include could not find load file` | I've been trying to change a makefile c++ project into a cmake project, and I've been having som difficulty. cmake seems to be looking for stuff in /usr/local/lib/ instead of /usr/local/include/ and I'm not sure why that is.
This library is header-only, and so I've been following this tutorial My header-only library in... | Your install prefix is specified as /usr/local/include so the files would be installed as:
headers into /usr/local/include/include
libraries into /usr/local/include/libs
cmake stuff into /usr/local/include/share/${PROJECT_NAME}/cmake
Those paths are just wrong. Just set CMAKE_INSTALL_PREFIX=/usr/local (ie. remove inc... |
62,867,261 | 62,867,400 | Why doesn't the icase flag for regex work correctly | This function is supposed to return the first instance of a vowel in a string, but it only works on lowercase. I thought regex_constants::icase was supposed to handle uppercase letters as well. Also, feel free to suggest a better way to do this.
The following returns 0 (it now returns -1) for "HAPPY" and 3 for "GREaT":... | Please do not use that library icase: C++11 regex::icase inconsistent behavior
it is terrible....
Instead switch the string to lowercase like so:
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c); });
If you are using non-standard ASCII chars t... |
62,867,337 | 62,877,694 | Canon EOS SDK download taken picture directly to a buffer or stream | It is quite easy to obtain the Image during live view operation using the method
EdsDownloadEvfImage(CameraRef, ImageRef);
This is quite handy to perform further image processing (with OpenCV etc)
In the same way, I would like to obtain the image data on taking a photo. In the documentation, I could only find a way to... | There isn't, but it's also not that difficult to do either. Because there is more than one way to obtain an image, it can't be as easy as downloading a live view image.
If you want to get the image directly after taking it, do the following:
Set the SaveTo property to Host and listen to the ObjectEvent.
Once the event... |
62,867,508 | 62,867,540 | Two string are not equal in c++ | I have a problem with comaparing two strings from std library on marked line of code. After this line output is "NO", although the strings after sort are the same with equal lenght. In sort I used bubble sort with swap function.
#include <iostream>
#include <algorithm>
#include <string>
void sort(int n, std::string s... | Your sort function is not actually modifying the string s1 being passed in. You need s to be a reference to the argument passed in:
void sort(int n, std::string &s);
and now changing s is the same as changing s1.
You need to change the signature in the function definition as well.
Also, you don't need to pass in the l... |
62,867,705 | 62,867,781 | Top question`s answer gets shift operator wrong? | In the following question:
Why is processing a sorted array faster than processing an unsorted array?
the accepted answer explains a way of avoiding branch prediction for the given example.
He/she goes on to replace a conditional statement with some bitwise operators:
Replace:
if (data[c] >= 128)
sum += data[c];
... | If data[c] >= 128, then data[c] - 128 will be non-negative, so it's sign bit will be 0. Otherwise, if data[c] < 128, then data[c] - 128 will be negative, so it's sign bit will be 1.
If we shift right by 31 (assuming an int is 32 bits, and right shifts are arithmetic, so yes implementation defined but pretty common), t... |
62,868,505 | 62,868,550 | A problem of function declaration and function definition in Visual Studio | I am a beginner in C++ and I got some problems. I'll appreciate it a lot if anyone helps me. My English is not very good.
I write the code in the Visual Studio.
When I use the overloaded function and default parameter at the same time, it' OK as follows:
double max(double a, double b, double c, double d = 3.1415926... | Default value you specify only once - in function prototype:
int max(int a, int b, int c, int d = 20);
int main()
{
// code...
}
int max(int a, int b, int c, int d)
{
// code...
}
The same with double version
|
62,868,631 | 62,868,692 | C++: no value is printing when passing array for loop? | I'm new to C++ programming. Whenever I run this, it doesn't print anything.
What I want is to ask the user for their names infinite times and only break after typing "quit". And after typing "quit" it must print all the items in the array. But it's not printing anything. Where am I wrong?
Here's my code:
#include <iost... | arr in my_funct() and arr in if-else statement are two different arrays. You are declaring local version in if-else, which after each iteration of loop is destroyed. You also declared it as an array of zero length - meaning it cannot hold any elements. What you want in your case is std::vector (you even included approp... |
62,868,708 | 62,868,874 | User-Defined Deduction Guides in C++20 | I'm working with std::variant and std::visit using the "overload" pattern that looks like this:
#include <iostream>
#include <variant>
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main(void) {
std::variant<int, float>... | This change was added by P1021R4, specifically P1816R0, which added support for class template argument deduction for aggregates.
The specific wording can be found in [over.match.class.deduct]/1 which adds, basically, an implicit deduction guide for aggregates:
In addition, if C is defined and its definition satisfies... |
62,868,889 | 62,868,940 | How to move object towards an angle in degrees? (C, C++) | I'm trying to move a bullet object towards a player position. I found this angle function online, and it seems to convert it to those coordinates in the comments. But i can't make the bullet follow in the direction.
float Angle(int p1x, int p1y, int p2x,int p2y)
{
//Make point1 the origin, make point2 relative to t... | You are explicitly calculating angles in degrees, yet sin and cos expect radians, not degrees.
Without analyzing whether or not the Angle function is correct, your code will make more sense if you change the function to return a value in radians. You even have the required line there commented out.
So, something like ... |
62,869,138 | 62,869,258 | effectively use std::unordered_map to insert or increment value of a key | Given an unorder map M, a key K, an init val V. I want to set M[K] to V if K is not in M; ++M[K] if K is in M. (e.g. use a map to count occurrence of elements)
There are several ways to achieve this, but when we separate find and insert/increment into two steps, at least we need hash(K) twice (How to make hints help? ... | The insert() member function returns a pair that contains an iterator and a bool; the iterator points either to the inserted pair or to the pair that already exists, and the bool tells you which it is (if true, a new map element was inserted; if false, the returned iterator points to something already present and the v... |
62,869,307 | 62,869,318 | How to print the objects specific member using only object name? | string var = "Hello";
cout << var << endl;
We get the result using only the object, without the help of a member variable. I want to implement a class that will work like string. For example:
class Test {
public:
int x = 3;
};
Test var2;
cout << var2 << endl;
How can I get implement the class so the cout line pr... | The std::string class has operator << overloaded, that's why when you write:
std::string text = "hello!";
std::cout << var1 << std::endl; // calling std::string's overloaded operator <<
Prints the text held by it simply.
Thus, you need to overload the << operator for the class:
class Test {
int x = 3;
public:
... |
62,869,738 | 62,873,655 | Using struct object for a binary search operation | I'm trying to use a struct object for a binary search count function and I'm trying to get the code compiling with no luck.
What the binary search count function is doing is that it's counting the number of values there are before the limit has been reached. I have to use structs instead of classes as the code is going... | You have to change the types:
int binarySearchCount(volatile TEST_SAMPLE arr[], float n, float key)
binarySearchCount(braketest.dataPoints, n, braketest_trig_level_pedal);
And change accesses to arr[mid] to arr[mid].loadcell, like:
if (arr[mid].loadcell == key)
You size calculation is wrong then:
sizeof(brak... |
62,869,821 | 62,869,899 | How to get the line number from the call site using __LINE__ or some other method? | Consider this short program that I wrote:
#include <iostream>
template<bool Debug = false>
constexpr int add(const int& a, const int& b) {
if (Debug)
std::cout << __FUNCTION__ << " called on line " << __LINE__ << '\n';
return (a + b);
}
int main() {
std... | You can call it like this instead:
template<bool Debug = false>
constexpr int add(const int& a, const int& b, int loc = __LINE__) {
if (Debug)
std::cout << __FUNCTION__ << " called on line " << loc << '\n';
return (a + b);
}
int main() {
std::cout << add(3, 7) << '\n';
std::cout << add<true>(5... |
62,870,536 | 62,870,690 | Why does this code using __LINE__ compile under MSVC in Release mode, but not in Debug mode? | Consider this program:
#include <iostream>
template<bool Debug = false, int Line = __LINE__>
constexpr int adds(const int& a, const int& b) {
if (Debug)
std::cout << __FUNCTION__ << " called on line " << Line << '\n';
return (a + b);
}
int main() {
std::cout << adds(3, 7) << '\n';
std::cout <... | Seems like it was reported: __LINE__ cannot be used as an argument for constexpr functions.
We have a known bug for this issue on the C++ team here.
[...]
We have determined that this issue is not a bug. Please refer to comments of Jonathan.
And Jonathan says:
This is a side-effect of the compilers support for Edit-... |
62,870,669 | 62,895,033 | How to automatically put newline at text's end in FLTK Multiline_Input? | I am using FLTK 1.3.5 and I would like to use the Multiline_Input object. I wonder if there is a way to automatically put a newline when the inserted text reaches the end of the input field, instead of doing it manually (check the uploaded images for an example). Moreover, the newline should be put at the end of a word... | Following Basile's suggestion, I investigated more on handling events and then I came up with a solution.
I derivated a class from the original Fl_Multiline_Input which basically controls that the char[] in Fl_Multiline_input->value() does not overcome the maximum width given by the geometry (considering the current Fl... |
62,870,737 | 62,870,838 | C++ program giving weird int value after looping | So i tried below program with its expected output,
int main()
{
int x = 0;
int a[5];
int len = *(&a + 1) - a; //length of array
cout << "LEN:" << len << endl;
//len = 20;
for (int i = 0; i < len; i++) {
a[i] = i;
}
cout << "X :" << x << endl;
return 0;
}
Which gives expec... | In general, writing beyond the end of an array results in undefined behavior. This can cause unrelated code to change in unexpected ways.
The undefined behavior in your second example can be reduced to:
int main() {
int a[5];
for (int i=0; i<20; i++)
a[i] = i; // undefined behavior once i reaches 5.
}
If you'r... |
62,870,784 | 62,871,028 | In a template function, How do I use std::underlying_type just if type of the input is enum class? | I have a piece of code that returns the value of some bits of a given number (I counted enum classes as a number too, using a static_cast).
template<typename Type>
bool get_bits(Type input, uint8_t offset, uint8_t n, Type* destination)
{
if (offset + n> sizeof(Type) * 8)
return false;
Type bitmask = 0;... | If you need it often, it's possible to write an adapter over std::underlying_type. Something like this
namespace detail {
template<typename T, bool = std::is_enum<T>::value>
struct underlying_type { using type = T; };
template<typename T>
struct underlying_type<T, true> : ::std::underlying_type<T> {};
}
When ... |
62,871,148 | 62,871,375 | Count ways to n'th stair(order does not matter) | There are N stairs, and a person standing at the bottom wants to reach the top. The person can climb either 1 stair or 2 stairs at a time. Count the number of ways, the person can reach the top (order does not matter).
Note: Order does not matter means for n=4 {1 2 1},{2 1 1},{1 1 2} are considered same.
https://practi... | Consider that you have N stairs. First of all you have to understand if N is odd or even.
If is even than it will be a multiple of 2: N = 2*S, where S is the number of pair of stairs.
Suppose N = 6 and S = 3. Your first solution is {2,2,2}. than you can change the first 2 stairs with 1 + 1 stairs and you have your seco... |
62,871,162 | 62,871,240 | C++ what is the correct way to access public static vector from another class? | Considering following example:
//Source.cpp
#include <vector>
#include "MyHeader.h"
class A
{
public:
static std::vector<B*> objects;
};
//MyHeader.h
class B
{
public:
B()
{
A::objects.push_back(this);
}
};
I want for each object of type B to be inserted in the vector in class A upon creation... | The solution to your problem should look something like that:
//Source.cpp
#include <vector>
#include "MyHeader.h"
class B
{
public:
B()
{
A::objects.push_back(this);
}
};
//MyHeader.h
class B;
class A
{
public:
static std::vector<B*> objects;
};
The idea is to declare the class A first, but ... |
62,871,312 | 62,874,958 | Remove Node from Binary Search Tree Iteratively | Been working on this for a while. There is a segmentation fault around the case where there are two child nodes. I'm not sure how to fix the problem. I'm pretty sure the other cases are correct but I am currently struggling with the case where the node to be deleted has 2 child nodes.
bool BinarySearchTree::remove(Bina... | You are dereferencing pointers without checking for null:
while(!(*cur==val)){
if(val.priority < cur->priority){
parent = cur;
cur = cur->left;
}
else{
parent = cur;
cur = cur->right;
}
}
If ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.