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 |
|---|---|---|---|---|
64,133,626 | 64,155,826 | Which of the Merge sort implementation is preferred...Why? | I was implementing Merge sort in C++ and I came across an implementation on GeeksforGeeks.
In my implementation, I calculated and passed the size of the array on each call.
The implementation I saw on GFG was done by passing start and end indices on each call. This was the implementation on most of the websites.
Which ... | There are 2 main differences between these implementations:
in the first merge function the r index is included in the slice, whereas in Merge you pass different arrays, each with its size. Passing the index to the last element is not idiomatic in C and C++ as it requires error prone +1/-1 adjustments and does not all... |
64,133,835 | 64,134,237 | Why time since measurement on empty function has few nanoseconds error? | While doing benchmarking on a fast target code that runs in nanoseconds, I found now()-start introduces roughly 16ns measurement error on my target machine. Given the following code snippet:
#include <iostream>
#include <chrono>
void empty() {}
int main() {
int n = 1000000;
for (int j = 0; j < 10; j++) {
... | If you want to measure the average time it takes to call your function, don't sum up the time in the loop. Start measuring outside the loop and stop the counter after it. That way the impact of the overhead of calling now() is reduced to one call instead of 1000000 calls.
Example:
#include <iostream>
#include <chrono>
... |
64,133,964 | 64,145,951 | What is the correct specialization for distinguishing between value template class and lvalue template class? | I need to make a template specialization which distinguish between a template class with (only) value parameters like the following:
template<auto ... __vz>
struct values{};
and a template class with (only) reference parameters like the following:
template<auto& ... __lvz>
struct lvalues{};
But with following special... | If you're solving this for types, you can use
std::is_lvalue_reference to do this for a single type. Since you seem to be using C++17, you can use fold expressions to apply this to a parameter pack:
template <typename... Ts>
using are_types_lvalues = std::integral_constant<bool, (std::is_lvalue_reference_v<Ts> && ...)>... |
64,135,332 | 64,135,379 | Is there any order exists in unordered_set in c++? | int main(){
unordered_set<int> S;
S.insert(1);
S.insert(10);
S.insert(100);
S.insert(64);
for(auto &x: S){
cout<<x<<" ";
}
cout<<endl;
S.erase(S.find(1),S.end());
for(auto &x: S){
cout<<x<<" ";
}
}
Output:
64 1 100 10
64
This is same for every IDE and... | Indeed it's a poor name. I believe the C++ standards committee wanted to call it std::hash_set but there were too many so-called std::hash_sets in circulation prior to standardisation in C++11. The same applies to std::unordered_map: see the hash_map of the Boost distribution targeting C++03 and earlier.
They are indee... |
64,135,348 | 64,136,150 | Boost::asio to Struct (like recv) | i wanted to ask, if there is a possibility to receive from boost::asio::ip::udp::socket the data directly into a struct like in standard BSD Sockets:
struct T;
size = recv(sock,&T,sizeof(T));
Since i receive a lot of fixed size data,, i really do not want to copy the data into a buffer first and from there i... | Reading the documentation:
socket.receive(boost::asio::buffer((void *)&T, sizeof(T)));
|
64,135,495 | 64,135,666 | How to call a python built-in function in c++ with pybind11 | I am using pybind11 to call a python built-in function like range in c++ code. But I only found way to call a function in module like this:
py::object os = py::module::import("os");
py::object makedirs = os.attr("makedirs");
makedirs("/tmp/path/to/somewhere");
But a python built-in function like range needn't import a... | You could fetch range from the globals dict.
|
64,135,749 | 64,136,289 | How to create a 2D array using a function? | I am trying to define a 2D array, but I want to do it in a function,
here is my code:
int** createArray( int columns, int rows)
{
int** array[rows];
for(int i = 0; i < rows; i++)
{
array[i] = new int*[columns];
}
for(int i = 0; i <columns; i++)
{
for(int j = 0; j < rows; j++)... | Prefer std::vector over manual memory management:
std::vector<std::vector<int>> createArray(int columns, int rows)
{
return std::vector<std::vector<int>(rows, std::vector<int>(columns));
}
int main()
{
int COLUMNS = 5;
int ROWS = 3;
auto myArray= createArray(COLUMNS, ROWS);
/*
Do stuff
... |
64,136,235 | 64,136,678 | Is extern class declaration usage C++ standard compliant? | class My_Container
{
/*...*/
class iterator
{
extern class const_iterator;
Node* _ptr;
public:
bool operator==(const iterator& other) {return _ptr == other._ptr;}
bool operator==(const const_iterator& other) {return _ptr == other._ptr;}
};
class const_iterator
... |
Is extern class declaration usage C++ standard compliant?
No, this is not standard compliant. Classes cannot have a storage class specifier.
Can an inner class access to private members of another inner class?
Same way as any other class; it can access public members. The example accesses private member outside of ... |
64,136,850 | 64,137,173 | Is there assign_or_inserter/insert_or_assigner in C++20? | std::inserter suffers from problem that it calls insert that for map is noop if key already exists.
There is std::map::insert_or_assign, but I was unable to find an inserter that uses that.
Is there something like this in C++20?
note: I know I can c/p it from somewhere on the SO/internet, I am interested in STL/boost s... | No, there is no corresponding inserter that use insert_or_assign. In fact, the wording explicitly says there are only 3 such functions:
back_inserter, front_inserter, and inserter are three functions making the insert iterators out of a container.
|
64,137,150 | 64,137,922 | How calculation of std::distance works when multiple values with same value are part of the std::vector | vector<int> arr;
max = *max_element(begin(arr), end(arr));
min = *min_element(begin(arr), end(arr));
auto it = find(arr.begin(), arr.end(), max);
auto it2 = find(arr.begin(), arr.end(), min);
dis1 = distance(arr.begin(), it);
dis2 = distance(arr.begin(), it2);
I wanted to find the indexe... | You can provide a custom compare operator for std::max_element and for std::min_element. Using std::less_equal instead of the default std::less allows you get the last occurrence instead of first:
auto it = max_element(begin(arr), end(arr), std::less_equal<>());
auto it2 = min_element(begin(arr), end(arr), std::less_eq... |
64,137,176 | 64,137,501 | return value iterator of std::generate_n, what can you do with it? | Out of curiosity!
What can you do with the returning iterator of std::generate_n?
Return value
:
Iterator one past the last element assigned if count > 0, first otherwise.
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto iterator = std::generate_n(std::back_inserter(v), 10, [&]() {return j++;});
st... | Suppose you want to generate elements for the first half and then use a different generator for the second half, then you can simply write:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
int j = 0;
std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto iterator = std::generate_n(v... |
64,137,361 | 64,137,474 | How to assign a default (empty) value to the reference of a std::unordered_map in the declaration of a function? | I have a question, I've been doing some googling but I can't find a solution (yet).
I have a function that may / or may not receive a value of type std::unordered_map, as I indicate, on some occasions this std::unordered_map will be received empty and no processing of any kind will be executed on it, to achieve this, I... |
I have a function that may / or may not receive a value of type std::unordered_map [...]
As your function may or may not receive an argument for a given parameter, you may want to consider changing the interface of the function to take a std::optional second parameter, which wraps you std::unordered_map type.
#includ... |
64,137,560 | 64,137,929 | Methods for opening a specific file inside the project WITHOUT knowing what the working directory will be | I've had trouble with this issue across many languages, most recently with C++.
The Issue Exemplified
Let's say we're working with C++ and have the following file structure for a project:
("Project" main folder with three [modules, data, etc] subfolders)
Now say:
Our maincode.cpp is in the Project folder
moduleA.cpp i... | At some point the program has to make an assumption where the file(s) are. Either by getting it from user input or a relative path with the presumed filename. As already said in the comments, C++ recently got std::filesystem added in C++17 which can help you making cross-platform code that interacts with the hosts' fil... |
64,137,781 | 64,138,052 | C++ maths not working as expected when running | I am trying to do this C++ program which adds the natural numbers between two numbers. The code:
#include <iostream>
using namespace std;
int main()
{
int number, limit, sum = 0;
char ch;
do {
cout << "Enter the initial number: ";
cin >> number;
cout << "Enter the last number: ";
... | Your variable declarations and initialization:
int number, limit, sum = 0;
all happen one time before you enter the loop. So you're actually keeping a running sum over multiple runs!
To fix this, you can just make sure to reset sum to 0 at the beginning of each loop:
do {
sum = 0;
cout << "Enter the initial n... |
64,138,264 | 64,138,617 | passing a temporary lambda by const std::function reference should fail but seems to work | This is a simplified version of what I am doing:
#include <iostream>
#include <functional>
class thing
{
public:
void register_fn(const std::function<void()> &fn)
{
m_fn = fn;
}
void run()
{
m_fn();
}
std::function<void()> m_fn;
};
int main() {
// Create a thing object... | This works principally because you make a copy of the function object. In
void register_fn(const std::function<void()> &fn)
{
m_fn = fn;
}
you assign fn to m_fn which makes a copy and and even though fn is a reference to the local lambda, making a copy means m_fn does not refer to fn, but will get a copy of the f... |
64,138,371 | 64,138,372 | vcpkg port of Boost.Test fails to link | We've just switched from our own Boost compilation to vcpkg's one (1.73.0), with the automatic vcpkg integration with Visual Studio. We are not using CMake.
Everything was compiling fine but some projects using Boost.Test, more specifically with linker errors like:
boost_unit_test_framework-vc140-mt-gd.lib(boost_unit_... | After I realized that some projects using Boost.Test were compiling successfully, I started comparing them with the failing ones, and discovered the root of the problem: the file defining the main of the test application was using the included version of the framework:
#define BOOST_TEST_MAIN
#include <boost/test/inclu... |
64,138,682 | 64,138,782 | How can we get the size of an array that is passed into the function? | This is my program, can someone tell me how to get the right value of 'n'(which is size of array) here without passing it to function?
#include <iostream>
using namespace std;
char * findFrequency (int input1[],int input2)
{
int n = sizeof(input1) / sizeof(input1[0]);
int count = 0;
for(int i = 0; i <... | Of course you can always use a template:
#include <iostream>
using namespace std;
template<typename T, std::size_t N>
void findFrequency (T(&input1)[N], int input2)
{
// input1 is the array
// N is the size of it
//int n = sizeof(input1) / sizeof(input1[0]);
int count = 0;
for(int i = 0; i < N; i... |
64,138,770 | 64,140,106 | cannot insert breakpoint x in shared object library , (python using .so library from c++) | I'm trying to analyze c++ which is made into a .so file using pybind11.
The .so file has python API so the main python program uses the python API and calls functions in the .so file. I use two debugger for python (pdb) and c++ (gdb).
When I set breakpoint in the gdb, I get this error :
Cannot insert breakpoint 1.
Cann... |
for gdb : ddd /usr/loca/.../dlib...gnu.so 10498
Your DDD invocation is incorrect: the process 10498 is not running your dlib...gnu.so binary, it is running python3 binary with the .so loaded into it.
You need to invoke it like so: ddd python3 10498.
|
64,138,957 | 64,139,098 | Making personalize stack with personalized class but error shows up | Hi I wanted to make my personal stack class with template
and make a stack with personal class.
template <class T>
class stack{
public:
stack(T);
~stack();
void insert(T);
T pop();
void printstack();
private:
int top;
int capacity;
T *list;
};
template <class T>
stack<T>::stack(T first)... | You wrote this
deck::deck(){
stack<card> decklist(card(1,1));
}
but that just declares a variable in your constructor called decklist which is different from the decklist in your class.
To initialise the decklist in your class you should use an initialiser list. Like this
deck::deck() : decklist(card(1,1)) {
}
|
64,139,435 | 64,139,670 | Get keys from map based on their value c++ | I have map with strings as keys and vectors as values:
map<string,vector<int>> myMap;
//("key", value):
("a", {1})
("b", {2,3})
("c", {1})
("d", {1})
("e", {2,3})
Is it possible to get keys based on their values? I want the keys that have the same value i.e
(a,c,d) and (b,e).
| You have to look at every element
std::vector<std::string> keys_matching(const std::map<std::string, std::vector<int>> & map, const std::vector<int> & value) {
std::vector<std::string> result;
for (auto & [k, v] : map) {
if (v == value) {
result.push_back(k);
}
}
return resul... |
64,139,547 | 64,140,444 | How to detect whether there is a specific PRIVATE member variable in class? | This question is based on this post.
Goal: I would like to know if a class has the member variable x. I would like to receive true regardless whether or not this variable is private, public or protected.
Approach: You can get the information if a class has a member variable using the following code:
template <typename... | Well... not sure about correctness and limits of this solution... but...
If you define an helper struct with an x element accessible
struct check_x_helper
{ int x; };
you can write a template struct that inherit from both check_x_helper and the class you want to see if contain a x member
template <typename T>
struct ... |
64,139,873 | 64,140,071 | How to draw a 4 pointed star using glut openGL | I want to draw a 4pointed star using GLUT and openGL in C++. Here is my code
glBegin(GL_TRIANGLE_FAN);
glVertex3f(0.0f,6.0f,0.0f);
glVertex3f(1.0f,4.0f,0.0f);
glVertex3f(3.0f,3.0f,0.0f);
glVertex3f(1.0f,2.0f,0.0f);
glVertex3f(0.0f,0.0f,0.0f);
glVertex3f(-1.0f,2.0f,0.0f);
glVertex3f(-3.0f,3.0... | The 1st point of the the GL_TRIANGLE_FAN primitiv is always held fixed (See Triangle primitives). Just start the GL_TRIANGLE_FAN primitiv at one of the "inner" points:
glBegin(GL_TRIANGLE_FAN);
glVertex3f(1.0f,4.0f,0.0f);
glVertex3f(3.0f,3.0f,0.0f);
glVertex3f(1.0f,2.0f,0.0f);
glVertex3f(0.0f,0.0f,... |
64,139,903 | 64,140,062 | Should operator<=> synthesize array comparisons? | I've been playing with my own implementation of std::array and noticed libc++'s version uses explicitly defined operators for each of the comparisons (==,!=,<,>,<=,>=). I figured I could simplify my code by implementing C++20's spaceship operator (<=>). However, when I replaced the non-member comparison operators with ... |
Should operator<=> synthesize array comparisons?
Yes. This is what the standard (final working draft) says:
[class.compare.default]
A defaulted comparison operator function (12.6.2) for some class C shall be a ...
The direct base class subobjects of C ... followed by the non-static data members of C, in the order of... |
64,140,928 | 64,141,457 | Why is this symbol undefined for architecture x86_64 when the rest of the library loaded fine? | I'm trying to use an open source library to read wav/mp3 files in c++, but can't get it to compile when I try to use the init function for said library. When I run cmake --build . --config Release I get:
Undefined symbols for architecture x86_64:
"_drwav_init_file", referenced from:
_main in audiotests.cpp.o
ld... | From the documentation of the library you are using:
This is a single file library. To use it, do something like the following in one .c file.
#define DR_WAV_IMPLEMENTATION
#include "dr_wav.h"
Looks like you are missing that one. This is a common technique to bundle implementations in one translation unit, and keepi... |
64,141,034 | 64,143,457 | How to hook Delphi function using C++ | I am trying to hook a user-defined function of a program written in Delphi using C++ and Detours library. (DLL Injection)
However, I can't hook it because Delphi's and C++'s function calling conventions don't match.
Delphi uses the fastcall function calling convention, and C++ also provides a fastcall function calling ... | I solved this problem using __declspec(naked)! Thanks to everyone who helped me!
#include <iostream>
#include <Windows.h>
#include <detours.h>
using namespace std;
__declspec(naked) void __fastcall originFunction(char arg) {
__asm {
push ebp
mov ebp, esp
sub esp, __LOCAL_SIZE
}
__as... |
64,141,126 | 64,141,394 | How to pass callback from C# to C correctly? | I am working with Unity and I need to pass callback delegate from C# unity script to .dll
There is a api (MyApi.h) that I have on .dll side
typedef void(__stdcall * FuncPtr) (const char * str);
static FuncPtr DebugLog = nullptr;
static void debug_in_unity(std::string message)
{
if (DebugLog)
{
DebugLog... | You are breaking the one definition rule. You will need to have one translation unit (.c or .cpp file) defining DebugLog, and the header declaring it extern. Similarly your functions are also defined in multiple translation units.
MyApi.h
typedef void(__stdcall * FuncPtr) (const char * str);
extern FuncPtr DebugLog;
v... |
64,141,556 | 64,141,627 | Why is possible to pass a function pointers as template parameters in C++? | Let us consider the excerpt:
void myFunc(int a, int b) {}
template<void(*function_pointer)(int, int)>
class TakeFunctionPointer {
public:
TakeFunctionPointer() {
function_pointer(5, 6);
}
};
int main() {
TakeFunctionPointer<myFunc> tfp{};
}
This code is compiled finely and it works out, but I am concerned... | There is a difference between class type template arguments and value type arguments. When you have a template in which the actual type is already given, e.g.
template<std::size_t N> /* class or function... */
you are dealing with a value parameter. This is also true for specific pointers to functions, e.g.
template<v... |
64,141,779 | 64,141,825 | Passing cin values from a function to the main function | The program allows the user to choose what operation to use first before the user can input 5 numbers.
im trying to lessen my line of codes by creating a function that will get 5 numbers of user inputs so i can just call that function every time it is needed instead of typing it all 4times inside my if else statement.
... | If you want a function to change the parameters passed to it, you should pass by reference
void inputs(int& num1, int& num2, int& num3, int& num4, int& num5) {
No obvious reason for the function to return an int so I changed that to void.
Also I think you need to decide between int and double, code above seems a littl... |
64,142,007 | 65,015,068 | VS 2017 & 2019 cannot find the WinRT header files, even on a fresh solution | So I'm trying to update a Win32 application to UWP using a "Windows Application Packaging Project", I'm hitting filesystem issues, which I expected and am trying to resolve them. In order to do this, I need access to the WinRT libraries so that I can deal with UWP paths to get at my assets and resources.
I installed th... | this has been fixed by https://github.com/microsoft/cppwinrt/pull/781
Update your MSIX and NuGet packages
|
64,142,911 | 64,144,619 | Count File in a folder (include subfolder) | hi i use Qt and i want to know how much file are in a folder (include subfolder)
i find some code in internet but all of them only count file in a folder and not its subfolder
like this codes
#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("Usage: ./cou... | sumit_smk code is ok but its need a little edit for your case
here is the code you can use
int file = 0;
QDirIterator it("/Your_folder/", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext())
{
if(it.next() > 0 )
{
file++;
}
}
qDebug() << file;
|
64,143,694 | 64,144,655 | Partially overwriting the contents of a file descriptor | I am trying to create a file, and later partially overwrite the contents. The following program captures the gist of what I am trying to do
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
#include <unistd.h>
#include <stdlib.h>
using namespace std;
int main() {
string tmpFile... | This is an (externally) undocumented feature of glibc.
The source code of fdopen says:
/* The May 93 draft of P1003.4/D14.1 (redesignated as 1003.1b)
[System Application Program Interface (API) Amendment 1:
Realtime Extensions], Rationale B.8.3.3
Open a Stream on a File Descriptor says:
Although not explic... |
64,143,939 | 64,144,032 | QDateTime::toSecsSinceEpoch() seems not to work | Some theory first:
According to the Qt Documentation the QDateTime::toSecsFromEpoch() function:
Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00.000, Coordinated Universal Time.
and:
[...] for all valid dates, this function returns a unique value.
Here is the link to this spe... | QDateTime doesn't continually update. It stores a particular date and time. So no matter how long you wait, it will always give you the same value. To fix your code, you could do something like this:
QDateTime time1 = QDateTime::currentDateTime();
QString secs1 = QString::number(time1.toSecsSinceEpoch());
s... |
64,144,127 | 64,144,378 | Why isn't ConstexprIterator from std::array bidirectional/random-access? | I have a library function that works on arbitrary containers. Basically it prints elements. For a bidirectional/random-access container it prints first and last, for unidirectional only first. Recognizing and using bidirectionality hinges on a working --container.end(). This worked for std::array in C++17, but in C++20... |
in c++20 std::array has ConstexprIterator instead of LegacyRandomAccessIterator
Not "instead of".
https://en.cppreference.com/w/cpp/container/array (bold mine)
iterator — LegacyRandomAccessIterator and ConstexprIterator (since C++20) that is a LiteralType (since C++17)
WHY isn't ConstexprIterator random access or... |
64,144,233 | 64,150,386 | Build CGAL Mesh_criteria one by one | I used to build my CGAL MeshCriteria as follows, and that works well.
auto criteria = Mesh_criteria(
CGAL::parameters::edge_size=edge_size,
CGAL::parameters::facet_angle=facet_angle,
CGAL::parameters::facet_size=facet_size,
CGAL::parameters::facet_distance=facet_distance,
CGAL::parameters::cell_radi... | I don't see any solution but knowing the default values and use the ternary operator ?:.
Here is a copy paste from the code that will give you the default values:
template <class ArgumentPack>
Mesh_criteria_3_impl(const ArgumentPack& args)
: edge_criteria_(args[parameters::edge_size
|... |
64,144,398 | 64,144,624 | draw shifts in QGraphicsView | I have a weird shift when I draw in a QGraphicsView object,
The black square with inner red squares should be drawn in the upper left corner.
The .ui file :
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
... | If you want the topleft to be (0, 0) then you must set the alignment of the QGraphicsView to Qt::AlignLeft | Qt::AlignTop:
ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
|
64,144,667 | 64,155,579 | Getting "No Python class registered for C++ class" error, passing C++ object to Python function | I tried to write a simple embedded python program, following the tutorials and samples I found. It should simply create a class in C++, pass it to a python function, which calls its only method:
class TestClass
{
public:
void f() { std::cout << "Hello world!" << std::endl; }
};
typedef boost::shared_ptr<TestClass>... | You need to initialise your test module. Simply declaring it doesn't work.
The best way to do it is to append the init function to the inittab with PyImport_AppendInittab.
PyImport_AppendInittab("test", PyInit_test);
This should be called before Py_Initialize().
Now test is available for import like any other Python m... |
64,145,097 | 64,145,725 | Is there a way this lambda can capture a copy of the pointer? | In a lambda I'd like to capture a copy of a pointer, but can't because it's a static variable (can't capture it):
#include <iostream>
#include <string>
#include <functional>
class Window
{public:
Window(std::string name) : name(name) {}
std::function<void(int)> eventHandlerFunction;
std::string name;
};
W... | You can copy the current value of ptr with the lambda syntax [local_copy=variable_to_copy_from]:
#include <iostream>
#include <string>
#include <functional>
class Window {
public:
Window(std::string name) : name(name) {}
std::function<void(int)> eventHandlerFunction;
std::string name;
};
Window* ptr;
aut... |
64,146,048 | 64,215,962 | C++Rest SDK Passing a long data type into request body results in 400 Bad Request | My Swagger document defines a long data type expected to be sent in request like:
size:
type: integer
format: int64
description: 'Some size'
I create request using following code in C++:
web::json::value postData = web::json::value::object();
If I pass a hardcoded value (i.e 50 or so) in the bod... | The problem was that I use MockLabs to create mock calls.
So, in there I had POST request body defined to be like:
{ "size":1 }
So, if my incoming POST request had a value different than 1 (i.e 50), I would get 400 Bad Request; otherwise, I would get 200 OK. If you keep this POST request body, then you can only send ... |
64,146,257 | 64,146,974 | C++20 concept which requires the existence of an exact function signature | Consider the following example for the calculation of the absolute difference between two values.
template<class T>
auto abs_diff(const T _a, const T _b) {
return (_a > _b) ? (_a - _b) : (_b - _a);
}
For some build-in types std::abs provides superior performance, so if std::abs(T x) exists I want to use it (let's ... | We can test instead if the overloaded function address expression &std::abs can convert to a pointer to function with the desired signature. Or we could, except that C++20 doesn't allow forming pointers to most standard library functions.
Leaving this original answer here for information. It would be a valid pattern fo... |
64,146,686 | 64,147,114 | Capitalize a single letter instead of the entire sentence | How do I uppercase for example letter "i"? I tried transform, convert. Now, I think using a for loop may be the best option, but cannot seem to figure it out!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "this is a test, this is also a test, this is yet another test";
int strLen =... | Here is an std:: way:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
string s = "this is a test, this is also a test, this is yet another test";
char ch = std::toupper('i');
std::replace(s.begin(), s.end(), 'i', ch);
cout << s << endl;
return 0;... |
64,146,919 | 64,147,082 | How to redirect program output as its input | I've written a simple C++ program for tutorial purposes.
My goal is to loop it infinitely.
#include <iostream>
#include <string>
int main()
{
std::cout << "text";
for(;;) {
std::string string_object{};
std::getline(std::cin, string_object);
std::cout << string_object;
}
return 0;
}
After compila... | First, you need to output newlines when printing to std::cout, otherwise std::getline() won't have any complete line to read.
Improved version:
#include <iostream>
#include <string>
int main()
{
std::cout << "stars" << std::endl;
for(;;) {
std::string string_object;
std::getline(std::cin, string_object);
... |
64,147,464 | 64,154,146 | C++11 uniform initialization: ambiguity between initializer list and multiple-parameter constructors? | Currently trying to wrap my head around C++11's uniform initialization. I came upon this ambiguous case: consider a class which can either be constructed from either a two-argument constructor or an initializer list of any length:
class Foo {
public:
Foo(int a, int b) {
std::cout << "constructor 1" << std::... |
it seems like the compiler interprets Foo b {1, 2} as a list
initialization, and calls constructor 2. Is the () syntax the only way
to force the compiler to consider other kinds of constructors when an
initializer-list constructor is present?
Quotes from standard draft explains this well:
9.4.5.2 [dcl.init.list] (emp... |
64,147,487 | 64,147,530 | C++ VSCode Cannot convert '(classname)' to 'int' | I made a simple program to test an error I'm getting. Don't know why it doesn't compile even if the code shows no problems. It seems to be something with the included libraries cos if I delete the "include B.h" line from A.h file it solves the problem.
main.cpp:
#include "A.h"
#include "B.h"
int main()
{
A a;
... | The int is named because the C++ compiler assumes a type it does not know to be an int.
In the header files you have to work with forward declaration of the class.
C++ does not handle cyclic includes.
B.h
#pragma once
class A;
class B
{
public:
void funcion(A a);
};
B.cpp
#include "A.h"
#include "B.h"
vo... |
64,147,529 | 64,155,805 | Atomic and lock-free write of arbitrary sized data/vector/array | I am trying to implement the following functionality:
Atomic and lock-free write or read-modify-write of a data type with arbitrary size (in my case usually a float/int vector with up to 6 elements).
Atomic read from above data type that doesn't block the writing thread. The read operation may be blocked by the write ... | Strictly speaking your code is not lock-free, because you effectively use the LSB of protector to implement a spinlock.
Your solution looks very much like a sequence lock. However, the actual read operation auto ret = data; is strictly speaking a data race. To be fair, it is simply not possible to write a fully standar... |
64,147,698 | 64,147,730 | C array of objects that allow for dynamic allocation | If I have a class with dynamic allocaton like std::vector. How much sense does it make to create an array with elements of that object?
I tested the following:
std::vector<int> array[2];
array[0].push_back(10);
array[0].push_back(20);
array[0].push_back(30);
array[1].push_back(40);
array[1].push_back(50);
array[1].p... | There is no undefined behavior here.
How much sense does it make to create an array with elements of that object?
This is entirely up to you, and your design considerations. It's perfectly fine to have an array of vectors.
So when we create an array with two elements, is any memory allocated at all?
Yes, memory fo... |
64,147,877 | 64,147,944 | How do you access another class using a link list insert function? | I have an existing program that takes in a input with 5 parameters. The inputs are a video title, url, comment, length, and rating. All contained in video.cpp and video.h.
My new task is to insert each video into a linked list in sorted order, according to the video title.
My problem is that I have no idea how to acces... | The members of Video are private. You cannot access them unless the class exposes public accessor functions.
class Video
{
public:
const std::string& GetTitle() const { return title; }
// ...
private:
std::string title;
};
Then in your list:
void Vlist::Insert(Video* video)
{
if (m_head == NULL || m... |
64,148,021 | 64,148,067 | how to split the first, middle and last names, and print it as last name, first initial middle initial c++ | I have to intput first, middle and last name of a person and the output should be last name,
first initial and middle initial if the name has one, but I am having problems trying to take
out the middle initial and when I don put a middle name the code prints last name, first initial
and last initial any solutions?
#in... | You can try using firstSpace == secondSpace for the if statment.
str.find_fisrt_of and str.find_last_of returns the index of them. So if there is only 1 space in between, it will return true and enter that logic. For the same reason, firstSpace and secondSpace should probably be declared int instead of char.
Also you a... |
64,148,564 | 64,149,545 | Cannot solve this error in my TCP server code | So, I was trying to code this simple TCP server, but I'm stucked with this error
error: 'inet_ntop' was not declared in this scope; did you mean 'inet_ntoa'
I know that I have to use ntop and not ntoa. But I can't find out how to get rid of this error. I searched everywhere and couldn't find anything. I hope someone ... | inet_ntop() requires Windows Vista and later at runtime, but you are setting _WIN32_WINNT to 0x501, which represents Windows XP, so the declaration of inet_ntop() in <w32tcpip.h> gets disabled at compile-time to prevent the program from failing to start at runtime.
You need to set _WIN32_WINNT to at least 0x600 instead... |
64,148,666 | 64,149,378 | Switch not carrying over parts of an input? | My assignment for my class is to convert letters to numbers from an input file, like an old phone's keypad. i.e ABC are 2, DEF are 3, etc.
So, in the input file, one of the inputs is 1-800-ARID.
Using switch, I was able to successfully change the characters into numbers, but am unable to carry over the 1-800, or rather... | You are outputting ONLY the characters you convert, nothing else. Simply add a default block to the switch to output all other characters as-is.
Also, your use of input.eof() is wrong.
Try this:
while (input.get(ch)){ // <— fixed
switch (ch) {
case 'A': case 'B': case 'C': output << '2'; break;
case... |
64,149,017 | 64,162,835 | Leetcode question 489. Robot Room Cleaner - why my solution doesn't work | I am trying to solve the Leetcode question 489. Robot Room Cleaner using backtracking. Specifically, I try to move the robot in each of 4 directions and backtrack if all four directions are blocked or cleaned.
The code below doesn't work and I am trying to debug it with this simple example:
grid = [[1,1,1],
[1,... | The problem was that the Robot class interface doesn't put the robot back automatically when backtracking (Robot object is passed by reference and keeps its position). Adding a specific function to move the robot back after backtracking fixed the problem:
void go_back(Robot& robot, int dir) {
// Keep mind that the ... |
64,149,096 | 64,149,302 | How to initialize a pointer appropriately to avoid segmentation fault in c++? | I have started learning c++ (coming from java background) and barely reached pointers and got stuck. When I debug this program it says, program received segmentation fault (SIGSEGV signal) at line
*previous = head;
in the following code.
#include <iostream>
using namespace std;
struct Node
{
int data;
Nod... | First problem:
Node *previous;
*previous=head;
First line declares that previous will hold the address of a Node. It is not initialized, so whatever value happens to be on the stack will be picked up as the bit pattern it holds.
Unfortunately, the 2nd line then dereferences the pointer (which points to garbage) and a... |
64,149,561 | 64,149,773 | C++ - print error message if account number not found | So I'm creating a program that will implement various classes which represent a bank, its customers and its bank accounts. The Bank object stores a collection of Customer objects, as well as a collection of Account objects. Each Customer will have their own separate collection of the accounts that belong to them.
Below... | you can easily do it by altering your credit() and debit() functions, all you need is check if the control got out of your for loop(line 51 in back.cc for(int i = 0; i < numberOfBankAccounts; ++i)) or not with the required value.
you can simply do it by creating/initialising a boolean value in the beginning and change ... |
64,149,638 | 64,149,755 | How to distribute a console application? | I am new to C++ and recently made a Tic-Tac-Toe game, which is a console application (no graphics). I have built my project in Release mode in Visual Studio 2019. I want this application to be transferred from one computer to another. I have zipped the Release folder of Visual Studio and tried to transfer it into anoth... | You don’t mention the exact error, but a first order possibility is a missing dependency.
Odds are you are missing the Visual Studio C++ runtime on the target machine (the one you are coping to). Windows does not install them by default, but Visual Studio does install them.
To download the runtime, go to https://visual... |
64,150,002 | 64,150,061 | Local variable definied in an if statement hehaves unexpectedly | Originally I wanted to pack a bunch of statement into a single line so my stuff can be used as a simple macro inside an if.
I needed to do 3 things:
Create a local variable
Update that with a function
Check if the updated variable matches something else
Here's my quick draft code:
#include <iostream>
#include <stdint... | Your condition is really:
uint64_t generatedElement = (123456 && MyMockedFunction(&generatedElement) && global_should_match_this == generatedElement)
Which means you initialize generatedElement with the boolean result. And also lead to undefined behavior as you use the uninitialized (and indeterminate) value of genera... |
64,150,182 | 64,151,002 | Combining multiple boost property_tree | Very basic question: does Boost's PropertyTree support addition of any kind?? For example, can I:
boost::property_tree::ptree pt0;
boost::property_tree::ptree pt1;
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini("config0.ini", pt0);
boost::property_tree::ini_parser::read_ini("config1.ini", p... | This class appears to have a range insert that you can use to copy all the parameters at once
This is how you can use that method to create the + operator overload you're looking for:
boost::property_tree::ptree operator +(const boost::property_tree::ptree& lhs, const boost::property_tree::ptree& rhs) {
boost::prop... |
64,150,415 | 64,150,700 | How do i apply lower_bound to a range of unsorted vector elements? | I have a vector of integer scores = 10, 23, 29, 77, 8, 43, 56, 3
along with a number predict = 42
and a start index = 2
I'm searching for two numbers, (more than and less than) close to predict = 42 within range of start index = 2 and end index = 7
scores = {10, 23, 29, 77, 8, 43, 56, 3} (only search within range i=... |
How do i use std::lower_bound and std::upper_bound functions on unsorted range?
No, they expect the range to be partitioned with respect to the value (all entries less than value must come before all the entries greater). https://en.cppreference.com/w/cpp/algorithm/lower_bound
How do i sort a part of a vector tempor... |
64,150,812 | 64,151,544 | Lost connection to MySQL server when deleting initid->ptr, MySQL aggregate function (UDF) | I created a MySQL aggregate UDF in C++.
I am returning char* from the final function of MySQL aggregate UDF.
In the void xxx_deinit(UDF_INIT initid) I am releasing any memory used by my function.
I am releasing the memory by deleting the init->ptr.
My deinit function:
extern "C" void xxx_deinit(UDF_INIT * initid)
{
... | There is no memory leak, as "demo" is a pointer to static memory.
You are trying to delete a pointer to memory that was not allocated with new. Your runtime has every right to blow up.
The simplest solution is to simply remove the delete in your deinit function. If you will always put a static string there, that is suf... |
64,150,968 | 64,151,133 | why my second function (push2() ) not working? | **when i take head reference as function argument it is working but when i take head not working
where i did mistake ?
help me out
**
#c++ =====================================================================================================================================================================================... | First problem:
void push2(node *head,int dat){ //it is no working ?
Okay, push2's first parameter is supposed to be a node *.
node *head = new node();
And head is a node *.
push1(&head,8);
Uhh, what? Why &head? If push2 takes a node *, and head is a node *, why are you passing &head to push?
Second problem:
void pu... |
64,151,043 | 64,151,425 | Why does binary_search() and find() work differently here? | If I run the following code, I get the error as prog.cpp:7:39: error: no match for ‘operator==’ (operand types are ‘bool’ and ‘std::vector::iterator {aka __gnu_cxx::__normal_iterator<int, std::vector >}’)
if(binary_search(v.begin(),v.end(),3) == v.end()) cout<<"not found";*
But if I use find() instead of binary_search(... | std::find and std::binary_search do different things.
std::find returns an iterator to the found element (or end() if it's not found). It does not require the range to be ordered.
std::binary_search returns a bool, true or false. It requires the range to be ordered.
If you'd like a combination of both a binary search... |
64,151,121 | 64,151,188 | I need declare a global array, but y my variable does not work, i have something like this: | I tried with a #define but i don't know how use it in this context
the console print: 'array bound is not an integer constant', If you can help me I would appreciate it very much
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
//I get the value of my enviroment varia... | You can't use run-time calls and data for global variable initialization. All global variables must be initialized with compile-time constants.
And (standard) C++ doesn't even have variable-length arrays, which means you can't create an array using variables whose values are set only at run-time.
The natural solution i... |
64,151,359 | 64,184,704 | FillRect Wont draw to the screen | Im doing a tetris clone to learn how the WinApi works:
const int sm = 30, //screen multiplier
fWidth = 12, fHeight = 20;
char field[fHeight][fWidth];
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
retur... | OK, the problem was fixed after changing the DispatchMessage to InvalidateRect.
|
64,151,596 | 64,159,307 | How am I getting a read access violation thrown with unordered_map .find()? | After stepping through many times with my debugger, I still cannot figure out how I am getting a read access violation. I have a std::unordered_map<std::string, int> with 8 pairs stored at the time of error. The faulty line of code reads as follows:
auto it = this->mapRegisters.find(param);
Where :
string param = "3";... | After stepping through all of my allocations, I recognized that one of them was not large enough for what I was using it for elsewhere in the program. This was causing the program to read and write to a location that it did not have access to. While this would not necessarily affect the map and .find() function mention... |
64,152,542 | 64,154,459 | Having class X, how to pass X as a template argument to itself? | I'm trying to implement a Red-Black Tree that inherits from a BS Tree. BST uses BSNode as its nodes while RBT (Red-Black Tree) uses RBNode which in turn inherits from BSNode. The code looks like this, the problems arise in the code:
#include <iostream>
#define _BST BST<K, T, RBNode<K, T>>
// attempt 1
//template <typ... | You need to separate both Node and Tree from the specific BSNode, RBNode, BSTree and RBTree types
template <typename K, typename T, template<typename, typename> typename NODE>
struct Node
{
K key;
T value;
NODE<K, T>* left;
NODE<K, T>* right;
// ...
};
template <typename K, typename T>
struct BSN... |
64,152,675 | 64,291,696 | How XCTest is loaded to process memory along with iOS App (Heap Corruption issue)? | I have a quite strange crash in my XCTest suite.
The test target is Application tests with Allow testing Host Application API checkbox enabled. Build for active arch only is YES.
Now I have only ONE test in my test suite, and it still crashes.
Xcode says that the cause of crash is "Heap corruption".
I've seen the poss... | The reason of the problem was that the object code for Test Target and Main Target was slightly different.
A custom_ptr looked like this:
//file custom_ptr.h
template<class T> class custom_ptr
{
#ifdef DEBUG
T* some_debug_pointer;
#endif
};
And I passed DEBUG=1 in Preprocessor Definitions only for Main Target.
... |
64,153,387 | 64,154,051 | Reintepret cast and Pointer deletion | I find the following error in my recent implementation.
#include<iostream>
using namespace std;
void main()
{
string header="apple"
float* p = new float[10];
double*Data = NULL;
p = reinterpret_cast<float*>(reinterpret_cast<char*>(p) + header.length());
//fetch data from an another call// - it doesn't matter here ... | This somehow sounds like OP tries to prepare binary data consisting of a header and a sequence of floats. To achieve this (and overcome the alignment issues mentioned by M.Salters), I would use a std::vector<char>, resize it to the resp. full size of expected binary output, and then std::memcpy() the contents (header a... |
64,153,803 | 64,155,049 | Overloading of functions in C++ code when using extern "C" | I want to load libraries at run time. I have a base class "Base" and two derived classes "Derived1" and "Derived2" which should be loaded at runtime. I am using the approach from this answer with some small modifications. The code compiles perfectly when I define only one derived class, but it fails to compile when sev... | What you're trying to do is to have the same function in two different loadable modules. But what you're doing instead is putting both implementations (with the same name and signature!) of this function into the main module, which of course results in multiple definition error.
What you should do instead is put the cr... |
64,154,086 | 64,154,404 | Exercise about pointer to function in C++ | I have an exercise like that. The requirement is to write code in the section
#include <iostream>
int minus (int a, int b) {
return a - b;
}
void calculate(int a, int b)
{
int (*myfunc)(int, int);
// STUDENT ANSWER BEGIN
// STUDENT ANSWER END
int ans = (*myfunc)(a, b);
printf("Output... | When you write:
int (*myfunc) (int, int) = add;
you are creating a new variable named myfunc. If you do it inside the same scope as the original myfunc, it is a compilation error, but if you write it inside a new scope (which the indentation of the code you pasted suggest, even if you haven't showed the brackets), you... |
64,154,215 | 64,154,263 | Why am I not able to access a public member when inheriting? | #include <iostream>
using namespace std;
class BaseClass
{
private:
int privateInt;
protected:
int protectedInt;
public:
int publicInt;
};
class ChildClass : public BaseClass
{
publicInt = 0;
};
int main()
{
ChildClass c;
cout << c.publicInt;
}
As you can see, ChildClass is inheriting from B... | The assignment is simply misplaced. Instead of trying to assign a value to publicInt in the class definition (where you should only put member declarations or type aliases), you can do so e.g. in the constructor of ChildClass (or any other member function):
class ChildClass : public BaseClass
{
public:
ChildClass... |
64,154,376 | 64,165,367 | Recursively replace type by other type in a templated type | I'm looking for a way to recursively replace a type in a template. More specifically, turn T[N] into std::array<T, N>. The problem is doing this recursively if non-type template parameters are included.
Currently, I have the following code:
template<typename T>
struct replaced {
using type = T;
};
template<typenam... | First off, cool idea!
But as much as it sucks, as of C++20 there's no way to handle a generic, variadic mix of type and non-type elements. You just have to start carving out corner cases like with std::array.
This seems to fix that specific problem, but of course it only helps for classes that follow the same pattern a... |
64,154,416 | 64,154,587 | Stubbing a C function that has a a parameter with the same name in C++ | int stat(const char *__restrict__ __file, struct stat *__restrict__ __buf);
This function needs to be stubbed in order to cover more branches in an unit test made using Google Unit Test.
In file stubs.h
I have to stub this function, so I provide the following prototype:
int stat_stub(const char *__restrict__ __file,... | You can use a macro with parameters.
#define stat(p1,p2) stat_stub(p1,p2)
|
64,154,834 | 64,169,742 | How to find the closest number to a given number | I have a vector:
std::vector<int> vec = { 10 , 115 ,15, 35 , 55 , 75 };
I need to find the two numbers closest to a given number.
The first number would be less than the given number and hte second would be greater than the given number.
For example if the given number is 40 the two numbers would be 35 and 55.
This i... | You asked :
first I search all the numbers smaller than the given number.
Then I search for the greatest of them all.
I wanted to know if we can do it more efficently?
Answer:
Besides using a pre-sorted vector, then yes it can be done more efficiently, just iterate once over the vector and find both at once instead o... |
64,155,448 | 64,229,434 | 1D Heat Equation using DFT produces incorrect results (FFTW) | I am trying to solve the 1D heat equation using a complex to complex IDFT. The problem is that the output after a single timestep does not seem to be correct. I have included a simple example below to illustrate the problem.
I initialize the temperature state as follows:
The initial modes in the frequency domain are:
... | Your problem is that you don't resolve the needed frequencies, getting instead the following Fourier image of the function after multiplication by the decay coefficients:
The above result is too far from what you should get instead—a Gaussian—at least something like this (using 80 points instead of 8):
Notice how the... |
64,155,770 | 64,259,262 | Edge First Tab Error when Opening via System() | When doing
const std::string LaunchStr = "C:\\\"Program Files (x86)\"\\Microsoft\\Edge\\Application\\msedge.exe --profile-directory=\"Profile 1\" C:\\Users\\redacted1\\redacted4.html";
System(LaunchStr.c_str());
Microsoft Edge launches as expected, the loaded profile is the correct one and there is a new tab on redact... | I suggest you try to refer to the sample code below that may help you to launch the MS Edge browser correctly with the correct profile and with the specified URL.
#include <windows.h>
int main()
{
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
SHELLEXECUTEINFOW sei = { sizeof sei };
sei.lpVerb = L"ope... |
64,155,924 | 64,156,056 | Weird "e+08" values doing resizing of an 2D dynamic array | Im trying to do a function that resizes a matrix made of dynamic arrays given 2 parametres: the new amount of rows and the new amount of columns. My problem is that when I size it to a larger matrix than the original one the new values that should be 0 are something like -4.31602e+08. Shouldn't be 0 if i don't set a va... | You incorrectly assume that a float is initialized at 0.
Try to compile the following code
float f;
std::cout << f;
.. compiler at least says "warning: 'f' is used uninitialized". But probably prints 0 after all.
Now try
float* fp = new float;
std::cout << *fp;
delete fp;
Compiler doesn't warn, but you are printing r... |
64,155,948 | 64,156,650 | Converting std::type_identity object to a type | Suppose that we create two type_of functions that return std::type_identity, like:
template<auto VAR>
auto type_of() {
return std::type_identity<decltype(VAR)>{};
}
template<typename T>
auto type_of() {
return std::type_identity<T>{};
}
The way to get an actual type from std::type_identity seems a bit cumbers... | Getting the type from an std::type_identity object can be encapsulated into the following expresion:
template<auto x>
using type = typename decltype(x)::type;
This would allow to replace the cumbersome expressions:
decltype(type_of<int>())::type i1;
decltype(type_of<int{}>())::type i2;
With a more simple expression:
... |
64,155,962 | 64,156,077 | error: use of class template 'blocked_range' requires template arguments | I'm using TBB library like this:
// Concurrency.hpp
#include <tbb/spin_mutex.h>
#include <tbb/mutex.h>
#include <tbb/parallel_for.h>
#include <tbb/parallel_reduce.h>
// Restrict templates to work for only the specified set of types
template<class T, class O = T>
using IntegerOnly = std::enable_if_t<std::is_integral<T... | tbb::blocked_range is a class template, and you are attempting to use class template argument deduction (CTAD) by omitting any explicit template arguments when constructing it.
template<typename Value>
class blocked_range {
public:
//! Type of a value
/** Called a const_iterator for sake of algorithms that nee... |
64,156,297 | 64,156,691 | Wrapper function for template<> in C++ | I am currently trying to create a wrapper interface that can translate C++ to C, and while studying on the possibilities to do that, I came across the template functions (and classes). Knowing that these functions can take any data type and return any data type as well, I find it hard to create a corresponding caller f... | You may use function templates to simplify both implementing and maintaining the actual code that does the work but to provide a C interface, you'll still need to explicitly instantiate the functions for the types you aim to support.
If you'd like a C++ user to have the same restricted access to the functions as a C us... |
64,156,328 | 64,156,662 | How to create a number with (f)16 repeating n times? | I need to create a number where (f)16 repeats n times. 0 < n <= 16.
I tried the following for example for n = 16
std::cout << "hi:" << std::hex << std::showbase << (1ULL << 64) - 1 << std::endl;
warning: shift count >= width of type [-Wshift-count-overflow]
std::cout << "hi:" << std::hex << std::showbase << (1ULL <<... | For n = 1 to 16, you could start with all Fs and then shift accordingly:
0xFFFFFFFFFFFFFFFFULL >> (4*(16-n));
(handle n=0 separately)
|
64,156,346 | 64,156,516 | Why lambda function doesn't work in std::lower_bound while using references in key type? | I write this code:
std::vector<std::pair<std::string, std::string>> map_ = {{"b", "1"}, {"a", "2"}};
auto iter = std::lower_bound(map_.begin(), map_.end(), key,
[](auto p1, std::string& rhs) { return p1.first < rhs; });
and get such compile error:
error: no matching function for ca... | If you look at the requirements for the predicate in std::lower_bound you will see that it should look like
bool pred(const Type1 &a, const Type2 &b);
So you can't use reference. Only with const qualifier(or pass key by value).
|
64,156,448 | 64,164,874 | How to convince CMake to use the CUDA fmax function instead of the std cmath function? | Say I have the following function:
__global__ void testFunction(double *a, double *b) {
unsigned int index = blockIdx.x * blockDim.x + threadIdx.x;
a[index] = fmax(b[index], 0.0f);
}
then building gives the error:
error: calling a constexpr __host__ function("fmax") from a __global__ function("testFunction") is... | The problem has nothing to do with CMake or linking.
CUDA uses template overloading to provide native math library functions in device code. As per the documentation, exactly two versions of fmax are provided (here and here). They are
float fmax(float, float)
double fmax(double double)
Your code is requesting
double f... |
64,156,656 | 64,156,929 | ifelse Vs Map? [C++] |
I have a class that receives key and value parameters from other classes.
Both key and value are std::string.
Right now the function setParameter uses a chained if-else if -else if - else logic:
void setParamater(std::string key, std::string value){
if(key == KEYPARAM_1)
{
//Do something
}
else... | You don't need to declare a function for std::function. The alternative is to use a lambda. That lambda can go straight into your map initialization.
It would look something like
std::map<std::string, std::function<void(std::string)> funcs {
std::make_pair(KEYPARAM_1, [](std::string s) { std::cout << s; },
std::m... |
64,156,725 | 64,158,370 | Do I need writer/reader synchronization if I don't care if reader will read stale data? | Let I have a reader thread. Reader has a vector of bools. Size of the vector isn't changed and always known. Reader reads some data from another source, calculates an index from the data and checks if vector[index] == true. If true, Reader sends data further. If not, drops data.
Let I have a writer thread. Writer make... | Reading and writing the same value, however small, from multiple threads without synchronization, is a data race, a form of undefined behavior.
Even if the hardware guarantees cache coherency (as in x86), the C++ memory model is defined such that in the absence of synchronization each thread is assumed to be executing ... |
64,156,729 | 64,156,771 | C++ program stops translating the text as soon as it reaches whitespace | I'm taking Codecademy's learn C++ course and one of the projects is "whale translator" that takes in a text and translates into its whale equivalent.
There are a few simple rules for translating text to whale language:
There are no consonants. Only vowels excluding the letter y.
The u‘s and e‘s are extra long, so we m... | That's because >> stops reading as soon as it finds white space. If you want to read a whole line of text use getline.
getline(std::cin, input);
|
64,156,798 | 64,159,598 | Including opencv with fetchcontent does not work | I'm trying to include opencv in my c++ project. I want CMake to handle this for me.
Currently I'm at the point where I need to include opencv with the tag: #include <opencv2/opencv.hpp>
The files in the _deps/opencv-src directory throw the following error though:
Scanning dependencies of target VisionC
Building CXX obj... | I found the solution, this is my cmakelists now:
cmake_minimum_required(VERSION 3.17)
project(VisionC)
set(CMAKE_CXX_STANDARD 20)
# Fetch from git
include(FetchContent)
FetchContent_Declare(
opencv
GIT_REPOSITORY https://github.com/opencv/opencv.git
GIT_TAG 4.4.0
)
FetchContent_GetProp... |
64,156,861 | 64,157,078 | Difference between '<<' and 'put()' for output filestreams | I am trying to understand the difference between the '<<' operator and the 'put()' function for writing characters to an output file.
My code:
#include <fstream>
using namespace std;
int main() {
ofstream out ("output.txt");
int x = 1;
// This produces the incorrect result ...
out.put(x);
//... | int x = 1;
// This produces the incorrect result ...
out.put(x);
No, it converts the int to a char and outputs one char, with the value 1.
// ... while this produces the correct result
out << x;
That does formatted output and outputs the the representation of the value x holds. Most probably it'll show the character... |
64,158,032 | 64,158,233 | Why do big projects like Unreal Engine write their own container classes? | I've gone through the Unreal Engine source code and I found that they use their own container classes, for example an in-house dynamic array. But the C++ STL provides (almost) all the necessary container classes that will be required. So why do they spend time developing the same containers again? Wouldn't it be easier... | There are several reasons why a project might not use STL containers:
The containers used in the project are tailor-made to have certain performance characteristics that are different from the STL versions.
The STL containers might not even have existed when the custom containers were designed, and it's not worth the... |
64,158,484 | 64,158,853 | Ambiguous call after adding a template parameter that has a default type | #include <iostream>
template<typename T>
class A
{
};
template <typename T, typename T2, typename...Ts, typename = void >
//^remove this compiles
void func(T &&expr, T2 &&case1, Ts &&... args)
{
std::cout << "General\n";
}
template <typename T, typename A_Type, typ... | GCC Bug 96976 (Resolved; implemented in GCC 10.2, GCC 11)
This looks like GCC resolved bug
Bug 96976 - g++ reports "call of overloaded '...' is ambiguous" when universal reference is used
which was recently marked as resolved
Jonathan Wakely 2020-09-08 11:56:59 UTC
Fixed on trunk by r11-1571
It's also fixed on the ... |
64,158,603 | 64,159,419 | Painter not active on inherited QOpenGLWidget class | I would like to draw very efficiently basic 2D shapes (squares) in Qt, hence I inherited QOpenGLWidget as the following:
WatorOpenGLWidget.hpp
#include <QOpenGLWidget>
#include <QPainter>
#include "Environment.hpp"
#ifndef WATOROPENGLWIDGET_HPP
#define WATOROPENGLWIDGET_HPP
class WatorOpenGLWidget : public QOpenGLWi... | You should not invoke paintGL() directly but rather call the update() method that will invoke the paintEvent() method and this in turn will call paintGL().
void MainWindow::updateGUI(){
opengl_widget->setEnvironment(environment);
opengl_widget->update();
tick++;
ui->tickLabel->setText(QString("tick %1")... |
64,159,086 | 64,159,163 | operator<< overload in C++ not working as expected | I have defined a class template MyVector and overloaded the operator<< to print the vector that it holds.
//MyVector definition
template<int n, typename T>
class MyVector{
private:
vector<T> vetor;
public:
//Several Methods
MyVector operator+(MyVector& v){
//Adds 2 vectors
}
template<t... | Your operator+ on MyVector returns a temporary:
MyVector operator+(MyVector& v);
// ^^^^^^^^ temporary
which can't bind to a non-const reference which operator<< expects:
ostream& operator << (ostream& o, MyVector<m,U>& v);
// ^^^^^^^^^^^^^^ non-const reference
You can fix this by ... |
64,159,321 | 64,161,438 | If buffer of bytes should be unsigned char do I have to keep casting all the time? | According to these answers a buffer of bytes should be unsigned char, either because of convention or maybe the padding guarantees, I'm not sure. I have a function that looks something like:
saveDataToFile(const unsigned char* data, size_t size);
I find that I keep having to cast when I have a vector of char or an std... | Perhaps the simplest way, as you have suggested yourself, is to make the function's first argument a const void* and then cast that to whatever is needed inside the function. This way, you also avoid using a reinterpret_cast and can safely use a static_cast:
void saveDataToFile(const void* data, size_t size)
{
cons... |
64,159,461 | 64,159,884 | Non-capturing lambda lifecycle | I'm having a trouble finding a definitive answer if the following code is correct in both cases, with non-capturing lambda and with call of a static function. I'm pretty sure the latter is fine, what I'm concerned about is the lifetime of a lambda when "defined" inside another block/function call, etc. The code seems t... | Okay, so your nested Listener definition is this.
using Listener = void(void* arg);
Listener* listener_;
Basically, you deal with good old function pointers. Now when you pass an argument for the function pointer, you do this
producer.attachListener([](void* userArg) { static_cast<Listener*>(userArg)->event(); }, &lis... |
64,159,983 | 64,160,513 | Interfacing C++ with Python | I have a c++ (C++ 17) library and a function dependent on this library. I want to call this function from python(python 3). How can it be done?
I have read some tutorials using swig and ctypes but I don't know how can I make it work for an external shared library.
Details:
I have this libclickhouse-cpp-lib.so .so file ... | In your case it may be best to keep it simple and not use binding generators, because all you have here is a simple function that doesn't receive any parameters and simply returns an int.
Your goal can be achieved as follows:
In cpp_reader.cpp, prepend the following line before the reader definition:
extern "C" __attri... |
64,160,749 | 64,177,840 | can we verify that boostlog core did remove sink? | I am using boost log to make logging system for my program.
I understand boost log mechanism like this:
the core singleton registers sink ,this leads to raising shared pointer count of sink by 1,then we backend raising this count to 2 in addition to main count of shared pointer of sink as 0 .
In my code I remove sink f... |
is there any way I can verify that core has removed front end sink?
The sink is considered removed when remove_sink returns. That is, it will not receive any future log records.
It may not be released by the library at that point because there may be log records in progress at the point of the remove_sink call, and r... |
64,160,933 | 64,170,135 | CMake link Qt5::Svg but not see by QImageReader | I recently change my computer (Windows 10), so I reinstall CLion and Qt (using CMake compilation). But one of my project doesn't work anymore.
I have add Qt5::Svg into CMake, it compile but no SVG appears in application. And if I try a QImageReader::supportedImageFormats(), "SVG" is not listed.
I have Qt5Svgd.dll in bu... | To display SVG images (ie. icons) in your application, you need the corresponding imageformat plugin, which is being loaded runtime (that's why it's not shown by DependenyWalker). Look into your QTDIR/plugins/imageformats dir, and look for qsvg.dll or libqsvg.dll, and if needed, copy it into your runtime dir. See https... |
64,161,146 | 64,161,224 | How to free memory with move constructor | I am trying to create my own vector and here is a minimal example to introduce the problem I have:
class DemoVector {
public:
DemoVector() : capacity_(1), size_(0) {
data_ = new int[1];
}
DemoVector(DemoVector&& rhs) {
data_ = std::move(rhs.data_);
size_ = rhs.size_;
capacit... | Because std::move is basically just a cast that doesn't actually move anything! You need to update the values in the other object yourself:
DemoVector(DemoVector&& rhs) {
data_ = rhs.data_;
size_ = rhs.size_;
capacity_ = rhs.capacity_;
rhs.data_ = nullptr;
rhs.size_ = 0;
rhs.capacity = 0;
}
Or ... |
64,161,811 | 64,162,012 | C++ Windows Owner Drawn Main Menu -- itemID | I am attempting to create an owner-drawn main menu, in Windows. I understand setting:
menuiteminfo.ftype = MFT_OWNERDRAW
I also know about handling the WM_MEASUREITEM and WM_DRAWITEM messages.
However, how do I know which main menu item is sending the message? (so that I can fill-in the appropriate box size and text) ... | The itemID field of the MEASUREITEMSTRUCT and DRAWITEMSTRUCT structs tells you exactly which menu item is being measured/drawn. This is the ID that you specify when you create/modify a menu item. That ID is specified via either:
the uIDNewItem parameter of AppendMenu(), InsertMenu(), or ModifyMenu().
the item parame... |
64,161,826 | 64,161,885 | What is this construct : template <int> void funcName(int i)? | I accidentally made a mistake coding a template function specialization, and the resulting construct passed compilation with VS17. ( The third construct in the included code below )
Is this a valid construct?
How would I call this function?
template <class T> void tempfunc(T t)
{
cout << "Generic Template Version\n... | Yes, it's a valid construct. It's a template overload, that is templated on a non-type template parameter of type int.
You can call it like this:
tempfunc<42>(42);
Note that calls without the template syntax will still call the versions that are templated on a type parameter:
tempfunc(42); // calls specialization
te... |
64,161,921 | 64,162,312 | Initialize multidimensional array dynamically in c++ | How can I initialize ptr dynamically with new:
int values1[4][2] = {{2,3},{-4,0},{3,-7},{2,2}};
int values2[4][2] = {{1,1},{-2,-3},{4,12},{-5,25}};
int (*ptr[2])[4][2] = {&values1,&values2};
I tried the following but I get a mistake:
int *ptr = new int[2*4*2]{&values1,&values2};
| A typedef can help with this kind of tricky code
int values1[4][2] = { { 2, 3 }, { -4, 0 }, { 3, -7 }, { 2, 2 } };
int values2[4][2] = { { 1, 1 }, { -2, -3 }, { 4, 12 }, { -5, 25 } };
typedef int(*xxx)[2];
int main()
{
xxx* ptr = new xxx[2];
ptr[0] = values1;
ptr[1] = values2;
return 0;
}
I honestly ... |
64,162,006 | 64,162,100 | What is the importance of `&` when overloading the `[]` operator for a container class? | Let's say I have this simple container class
class Array{
private:
int m_l{};
int *m_d{};
public:
Array() = default;
Array(int len)
: m_l{len}
{
assert(len >= 0);
if (len > 0)
{
m_d = new int[len]{};
}
}
~Array(){
delete[] m_d;
... | Without the reference in the subscript operator overload, you are returning a temporary rvalue from the function. An rvalue cannot occur on the left side of an assignment operation.
Specifically, when you write arr[0], without the reference in your overload that would just return an integer (as whatever the value of ar... |
64,162,201 | 64,162,254 | How to match strings to objects? | I am fairly new to C++ (In VS2019), and am trying to make a simple console program. It asks for a bean name, then rates it with a rand() function. My friend said I should use groups and objects to add some ratings of my own into the mix. I now have a group with a few example beans as objects and have ran into an issue.... | You should use a std::map<std::string, bean> beans to perform object lookup at runtime.
It appears to me that you need to learn about std::map and std::string at the very least.
The usage would go something like:
string name;
cin >> name;
beans[name] = <your bean>;
Then later on, you can lookup for beans like
string ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.