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 |
|---|---|---|---|---|
71,616,025 | 71,616,124 | C++ Storing constant varibale names within a vector | My task is to write a preprocessor that replaces the constant variable with its actual value. To do this, I have created a struct and a vector to store the constant name and value. But unfortunately, I'm getting all kinds of compile errors. Can anyone spot any potential issues? Thank you in advance
using namespace std;... | Simply use a new local variable inside your reading loop like this:
while(stream >> token)
{
if(token == "#define")
{
constantVariable addconstant;
stream >> token;
addconstant.constantName = token;
stream >> token;
addconstant.constantValue = tok... |
71,616,430 | 71,619,665 | QWebEngineView::renderProcessTerminated signal not working in QT C++ | I am trying to connect a signal and slot in qt c++. What I want to achieve is that when the browser finishes rendering the page I want it to emit the signal and receive it in my slot. I initially wrote it for urlChanged() signal and it works fine but when I change it to renderProcessTerminated, it doesnt output the sta... |
What I want to achieve is that when the browser finishes rendering the page I want it to emit the signal
RenderProcessTerminated doesn't mean "finished rendering the page". It means that the operating system's process that was used for rendering has terminated abnormally. It happens e.g. when the renderer crashes. Qt... |
71,616,781 | 71,616,927 | Where are the Microsoft Visual C++ 2015-2022 Redistributable (x64) packages installed? | I know visual C++ 2015-2022 is installed because:
A. I see it in Apps & Features (Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.31.31103
B. I see it in registry HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\X64
but %VCINSTALLDIR% is not set on my path, and I cant find the d... | For me they are at
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Redist\MSVC
Do note that %VCINSTALLDIR% only works in the Visual Studio Developer Command Prompt. That should be located under the Visual Studio XXXX folder in your start menu or it can be launched directly from inside visual studio. ... |
71,618,039 | 71,618,096 | Which header to include for size_t | According to cpprefernece size_tis defined in various headers, namely
cstddef , cstdio, cstdlib, cstring, ctime, cuchar and (since C++17) cwchar.
My question is why is there not a single definition of size_t? Which header do I include, if I just want size_t?
|
My question is why is there not a single definition of size_t?
There is a single definition for std::size_t. It's just defined in multiple headers since those headers themselves use that definition.
Which header do I include, if I just want size_t?
Any of the ones that are specified to define it.
My choice is typic... |
71,618,336 | 71,618,527 | CSTDDEF file not found in GTest macOS | I'm trying to create a project in C using Gtest for unit tests.
For this, I have installed Xcode developer tools (because I'm in macOS big sur environment). and after this, I am cloning gtest and adding to submodules.
But, when I am trying to run test, the error appear :
googletest/googletest/include/gtest/gtest.h:52:1... | You are attempting to compile C++ code (in gtest.h) with a C compiler. (CMake chooses a C compiler for source files whose names end with .c.) C and C++ are different languages, not, generally speaking, source compatible in either direction. You must compile C with a C compiler, and C++ with a C++ compiler.
If conside... |
71,618,469 | 71,635,802 | Can not surpress QDebug output in relesae build | I work on a Qt project and I use cmake. In my CMakeLists.txt I have:
target_compile_definitions(${PROJECT_NAME} PUBLIC
QT_DEBUG_NO_OUTPUT
QT_NO_INFO_OUTPUT
QT_NO_WARNING_OUTPUT
)
and to test that in my main.cpp I have:
#ifndef NDEBUG
qDebug() << "QDEBUG IS ACTIVE!";
std::cout <<... | Change the typo QT_DEBUG_NO_OUTPUT to QT_NO_DEBUG_OUTPUT in order to use qDebug.
If you want to disable qDebug, qInfo and qWarning for a Release build only, then add the following condition to CMakeLists.txt:
string(TOLOWER ${CMAKE_BUILD_TYPE} build_type)
if (build_type STREQUAL release)
target_compile_definitions(... |
71,618,792 | 71,619,544 | How to call template operator? | How can I call declared operator of the class as following code;
class CChQuAuth
{
public:
CChQuAuth()
{
}
};
class CChQuCached
{
public:
CChQuCached()
{
}
template <typename _ChClass>
operator bool();
};
template <typename _ChClass>
CChQuCach... | There is no direct way
There is no syntax to form a template-id ([temp.names]) by providing
an explicit template argument list ([temp.arg.explicit]) for a
conversion function template
But there are options to choose from.
Use a general member-function template instead. That's how std::tuple works.
Create own templa... |
71,619,196 | 71,619,559 | C++ moodycamel concurrent queue - enqueue pointers | I am trying to use ConcurrentQueue to log items into a file on a separate thread:
https://github.com/KjellKod/Moody-Camel-s-concurrentqueue
This works:
// declared on the top of the file
moodycamel::ConcurrentQueue<MyType> q; // logger queue
. . .
int MyCallbacks::Event(MyType* p)
{
MyType item = (MyType)*p;
q.en... | The following code:
int MyCallbacks::Event(MyType* p)
{
MyType item = (MyType)*p;
q.enqueue(&item);
have a major flaw: You enqueue a pointer to the local variable item.
As soon as the Event function returns, the life-time of item ends, and it is destructed. The pointer to it that you saved will be invalid. Deref... |
71,619,411 | 71,619,923 | C++ multithreading locking a mutex before assigning to an atomic | In C++ do you need to lock a mutex before assigning to an atomic? I tried implementing the thread pool as shown here https://stackoverflow.com/a/32593825/2793618. In doing so, I created a thread safe queue and used atomics. In particular, in the shutdown method (or in my code the waitForCompletion) requires the thread ... | You have your dead lock while waiting for the condition. The condition although is only notified when there is a new job added. Your thread is waiting that condition to be notified. You may have non deterministic (from your point of view) checks of a condition "condition" but you may not rely them to exist.
You need ... |
71,620,158 | 71,620,986 | ffmpeg - avcodec_receive_frame returns -11, why and how to solve it? | I'm learning to use ffmpeg in my engine,
and I wanna decode the first frame of video stream and output it to an image file.
I tried and just can't figured out why it returns -11.
My code:(error in last 5 lines of code, line 70-74)
Link to my code
| This is your code (line 70 - 74):
res = avcodec_receive_frame(pCodecContext, pFrame);
if (res != 0)
{
return EXIT_FAILURE;
}
Let's see, what the documentation has to say about the related function (avcodec_receive_frame):
Returns
0: success, a frame was returned
AVERROR(EAGAIN): output is not available in this st... |
71,620,620 | 71,620,818 | Differences between assignment constructor and others in C++ | Consider:
std::shared_ptr<Res> ptr=new Res();
The above statement doesn't work. The compiler complains there isn't any viable conversion....
While the below works
std::shared_ptr<Res> ptr{new Res()} ;
How is it possible?!
Actually, what are the main differences in the constructor{uniform, parentheses, assignments}?
| The constructor of std::shared_ptr taking a raw pointer is marked as explicit; that's why = does not allow you to invoke this constructor.
Using std::shared_ptr<Res> ptr{new Res()}; is syntax that allows you to call the an explicit constructor to initialize the variable.
std::shared_ptr<Res> ptr=new Res();
would invok... |
71,620,808 | 71,620,833 | return pointer with new operator. Where to put delete? | Im fairly new to C++.
So I learned that new allocates memory and returns a pointer of my datatype. But can I use this in a function and return the pointer? If so then where should I place the delete operator?
Is the following code legal?
int *makeArray(int size)
{
int *result = new int[size];
delete[] result;
... |
Is the following code legal?
int *makeArray(int size)
{
int *result = new int[size];
delete[] result;
return result;
}
int main()
{
int *pointer = makeArray(10);
/* code ... */
return 0;
}
Definitely not! This is Undefined behavior because you return a deleted pointer. After using the delet... |
71,620,911 | 71,622,311 | C++ template default argument based on next argument | I need to do something like this:
template<class A=B, class B>
A fn(B x) { return A(x); };
int main()
{
int i = fn(5); // Error, no matching overload found
double d = fn<double>(5);
};
Hence, a function template which deduces the types automatically from the function arguments, but the caller can change t... | You can simply use constexpr if in such cases like:
struct NO_TYPE;
template<class RET_TYPE = NO_TYPE, class IN_TYPE>
auto fn(IN_TYPE x)
{
if constexpr ( std::is_same_v< RET_TYPE, NO_TYPE> )
{
std::cout << "1" << std::endl;
return IN_TYPE(x);
}
else
{
std::c... |
71,621,002 | 71,649,322 | Concise RAII for Trompeloeil mocks | I have classes like this:
/* "Things" can be "zarked", but only when opened, and they must be closed afterwards */
class ThingInterface {
public:
// Open the thing for exclusive use
virtual void Open();
// Zark the thing.
virtual void Zark(int amount);
// Close the thing, ready for the next zarker
vir... | I would have tendency to create function instead of RAII class there:
std::unique_ptr<std::pair<MockThing, trompeloeil::sequence>>
MakeMockedThing(std::function<void(MockThing&, trompeloeil::sequence&)> inner)
{
auto res = std::make_unique<std::pair<MockThing, trompeloeil::sequence>>();
auto& [mock, sequence] =... |
71,621,612 | 71,622,261 | C++ Finding minimum in vector of structs using custom comparator | I have a vector of structs:
struct element_t {
int val;
bool visited;
};
With a custom comparator:
bool cmp(const element_t& lhs, const element_t& rhs)
{
return ((lhs.val < rhs.val) && (!lhs.visited) && (!rhs.visited));
}
Used with:
std::vector<element_t> vct_priority(n_elems, {2147483647, 0});
In my alg... | It is evident that you need to define the comparison function correctly.
Here you are.
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
struct element_t {
int val;
bool visited;
};
std::vector<element_t> vct_priority =
{
{ 1, true }, {... |
71,621,737 | 71,621,738 | size of exe file made using cmake too large | I was making a cpp program using Visual Studio. The size of the executable was 490 KB.
But when i make the same executable by creating CMake Project in visual studio, the size of the executable is 1140 KB.
Both works, however.
| It was found that CMake was building RelWithDebInfo
set(CMAKE_BUILD_TYPE Release)
solved my problem. Size of executable was reduced to 483 KB.
|
71,622,093 | 71,622,182 | warning: converting to non-pointer type 'int' from NULL | I need to write a dictionary in c++
There is a function that returns the value of a dictionary by key, but if there is no value, then I want to return something like NULL. The value 0 is not suitable because it could be the value of some other key.
What can i use instead of 0?
TValue getByKey(TKey key)
{
for (unsig... | NULL is specifically a value for pointers. If the object that you return is not a pointer (or a smart pointer), then returning NULL is wrong.
If you return an int, then you can only return a value that int can represent, i.e. 0 or 1 or 2 ...
If you want to return a value that represents "no value", then you can return ... |
71,622,488 | 71,623,124 | arithmetic operator overload c++ for different types | I have a class 'number' with one member 'm_value' of type int64_t. I already overloaded += operator, there is code:
number& operator+=(const number& right);
and it works fine with different types (e.g. int, int64_t, short, etc). In same way I overloaded + operator:
number operator+(const number& right);
But when I tr... | You have implicit conversions between your type and int64_t that go both ways. This is asking for trouble, possibly in more ways than what you have just discovered.
Assuming
number x;
int64_t y;
the expression x + y can be resolved two ways, as x + (number)y and as (int64_t)x + y. Neither one is better than the other,... |
71,622,573 | 71,622,649 | Are dedicated std::vectors on the heap threadsafe? | This should be a simple question, but I'm having difficulty finding the answer.
If I have multiple std::vectors on the heap which are only accessed by one thread each are they thread-safe? That is, because the vectors will be dedicated to a particular thread, I am only concerned about memory access violations when the... | Access to different objects is thread-safe, new used by std::vector's allocator is of course thread-safe too.
Of course I could just stick each vector on its thread's stack, but they will be very large and could cause a stack overflow in my application.
I think you misunderstand how vector works. The object itself co... |
71,622,764 | 71,625,199 | C++: numpy/arrayobject.h: No such file or directory CMake VSCode | I want to include Python.h and numpy/arrayobject.h in my C++ script. But it cannot open these source files.
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(myProj VERSION 0.1.0 DESCRIPTION "myProj")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
find_package(PythonLibs REQUIRED) ... | I'm not seeing a lot of documentation for FindPython3 or FindPython for CMake 3.0.0 so I'm not sure if that module included before CMake 3.12.0. Version 3.12 is the first occurence I could find in the cmake documentation.
The most likely thing is that you just need to change to using
cmake_minimum_required(VERSION 3.12... |
71,623,024 | 71,623,060 | Calling functions inside of const references | Hi I am trying to have a getter in my class that returns a "read-only" reference to a vector of objects. Each of those objects its own variables and functions, that I need to call. The way that I am trying to set this up is to have the getter in the main class return a const reference. However, I don't seem to be able ... | You need to declare getVal() as const:
inline int getVal() const { return val; }
instead of:
inline int getVal() { return val; }
|
71,623,389 | 71,623,473 | RAII locking with condition | I have a piece of code which needs to be protected by a lock only if some condition is true.
if(condition) {
std::lock_guard<std::mutex> guard(some_mutex);
// do a bunch of things
} else {
// do a bunch of things
}
Although I can move all of the // bunch of things in a separate function and call that, I... | You can switch to using a std::unique_lock and use its std::defer_lock_t tagged constructor. This will start with the mutex unlocked, but you can then use its lock() method to lock the mutex, which will then be released by the destructor. That would give you a code flow that looks like this:
{
std::unique_lock<st... |
71,623,716 | 71,623,819 | Sorting complex numbers by their argument | I have a vector of complex numbers and I need to sort them by their argument. Sadly, the numbers have type complex<int>, so function arg(c) returns an integer in range [-3,3] instead of a float and the numbers can't be sorted properly.
I've tried also
typedef complex<int> ci;
typedef complex<double> cd;
vector<ci> a;... | You get the error because there is no converting constructor from std::complex<int> to std::complex<double> you have to construct the std::complex<double> by passing real and imaginary parts to the constructor:
#include <vector>
#include <complex>
#include <algorithm>
int main() {
std::vector<std::complex<int>> a... |
71,624,001 | 71,624,060 | Deleted function error after using random lib in struct | I'm trying to write a simple struct around an std random number generator. According to the compiler I can initialize this class but when I try to use the function it gives the following error:
Error C2280 'RandNormGen::RandNormGen(const RandNormGen &)':
attempting to reference a deleted function
I don't fully unde... | std::random_device is not copyable or movable. So your class also cannot be copied or moved.
However, there isn't really any point to keeping the std::random_device instance around. You (hopefully) use it only to seed the actual random number generator. So remove it from the struct and instead in the constructor:
gen =... |
71,624,163 | 71,624,368 | How do I combine hundreds of binary files to a single output file in c++? | I have a folder filled with hundreds of .aac files, and I'm trying to "pack" them into one file in the most efficient way that I can.
I have tried the following, but only end up with a file that's only a few bytes long or audio that sounds warbled and distorted heavily.
// Now we want to get all of the files in the fol... | These files have an internal structure: header, blocks/frames, etc. and the simple presence of multiple headers within the concatenated file will mess up the expected result.
Take a look at the AAC file format structure, you'll see that it's not so simple.
Your best try should be to use FFMPEG, since it has a feature t... |
71,624,515 | 71,628,701 | Visual Studio SDL2.dll The code execution cannot proceed because SDL2.dll was not found | I am trying to make a window with c++ and SDL, But when I launch my code, it says "The code execution cannot proceed because SDL2.dll was not found." And yes, it is confusing because I have SDL2.dll in my source files. Do anyone know how to fix it.?
Code:
#include "SDL.h"
int main(int argc, char *argv[])
{
SDL_In... | You may either manually copypaste it to your final build folder, or add this file to a project and specify its build action as Copy to Output (it used to work for me).
I think there may be option to set up a working directory in a project settings as well.
|
71,624,581 | 71,624,601 | unexpected address for a referenced indirected pointer in a struct as opposed to same declaration with a plain variable? | I have a struct containing a byte array and several typecast references to various points in the array. Bytes 4:7 may be interpreted as a float, int32_t, or uint32_t as determined by other fields in the packet being received over a serial connection. To make access simple (e.g. message.argument.F for a float interpreta... | There are two major, fundamental differences between the two alternative chunks of code.
void* argp = &bytes[ARG_I];
float& argf = *static_cast<float*>(argp);
Here, this constructs and initializes argp first, then argf.
float& argf = *static_cast<float*>(argp);
void* argp = &bytes[ARG_I];
And here, it doe... |
71,624,811 | 71,625,048 | How to retrieve the value at a given index? | I am fairly new to programming and I am working on a project that involves shifting nodes. How can I get a node at a particular position denoted by user input and increase its value by one? To better explain:
here is my code...or my attempt:
#include <iostream>
struct Node {
int data;
struct Node* next;
};
cla... | try traverse
actually there is no need to write a answer, but...I am a newcomer :)
your function place_node should add a parameter:
int place_node(int idx)
then...traverse from your head node for "idx" times, modify the value of current node, that's it.
here's the complete code for function place_node to achieve your ... |
71,625,041 | 71,650,368 | I want to run two function simultaneously in program In Arduino | void a(){
delay(3000)
# other statement
}
void b(){
delay(3000)
# other statement
}
Now I want to run these function in parallel but I when I call first function then it should cancel the delay time of other function and other functionality of function b and vice versa. My aim to run it in paralle... | As a real Arduino does not run an operating system, you have to do some sort of multitasking by yourself. Refrain from writing blocking functions. Your function void a() should look similar to:
void a() {
static unsigned long lastrun;
if (millis() - lastrun >= 3000) {
lastrun=millis();
... |
71,625,125 | 71,626,173 | CMake: How to prevent 64 bit build? | I have a cmake project comprising of two subprojects, say Project 1 and Project 2.
Project 1 is an executable and is supposed to be 32 bit.
Project 2 is a library (MODULE) and i need both 32 bit and 64 bit versions of it.
I am using visual studio 2022. Now, if i select 64 bit (via x64 Release), i am afraid cmake will b... | Just emit a fatal error during the cmake configuration.
if(NOT CMAKE_SIZEOF_VOID_P EQUAL 4)
message(FATAL_ERROR "Project 1 must not be build for 64 bit; choose a configuration using 32 bit")
endif()
Usually you'll want to avoid logic like this in your CMake files though. One of the greatest benefits of CMake is th... |
71,625,376 | 71,629,010 | after Adding header file to dependency, makefile didn't work for main.cpp | CPPFLAGS = -std=c++11
SRC_DIR := src
HEADER_DIR := include
BIN_DIR := bin
OBJ_DIR := $(BIN_DIR)/obj
EXECUTABLE := $(BIN_DIR)/main
OBJECTS = $(addprefix $(OBJ_DIR)/,main.o admin.o number.o SHA256.o signatures.o user.o)
all: $(EXECUTABLE)
directories:
mkdir $(OBJ_DIR)
$(EXECUTABLE): $(OBJECTS)
g+... | This rule:
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(HEADER_DIR)/%.h
tells make how to build an object file if and only if it can find an appropriately named .cpp file and an appropriately named .h file. If either of those files cannot be found, and make can't find a rule to build them, then this rule doesn't match and make... |
71,625,395 | 71,625,405 | How to enable auto nontype template parameter pack for same type of parameters | I have the following code:
template<auto... args> struct Custom
{
};
int main()
{
Custom<1, nullptr> s; // i want this to succeed only when all the template arguments are of the same type
}
As is evident from the above code, i can pass template arguments of different types. My question is that is there a way t... | You can make use of the decltype construct as shown below:
template<auto T1, decltype(T1)... Args> struct Custom
{
};
Working Demo
|
71,625,481 | 71,625,534 | C++ does compiler automatically use std::move constructor for local variable that is going out of scope? | #include <iostream>
#include <string>
using namespace std;
class Class1 {
string s;
public:
Class1(const string& s_) : s(s_) {}
};
class Class2 {
string s;
public:
Class2(string s_) : s(std::move(s_)) {}
};
class Class3 {
string s;
public:
Class3(string s_) : s(s_) {}
};
int main()
... | s_ is a lvalue in the initializer s(s_). So the copy constructor will be used to construct s. There is not automatic move like e.g. in return statements. The compiler is not allowed to elide this constructor call.
Of course a compiler can always optimize a program in whatever way it wants as long as observable behavior... |
71,625,832 | 71,625,996 | Program to print Factorial of a number in c++ | Q) Write a program that defines and tests a factorial function. The factorial of a number is the product of all whole numbers from 1 to N.
For example, the factorial of 5 is 1 * 2 * 3 * 4 * 5 = 120
Problem: I am able to print the result,but not able to print like this :
let n = 5
Output : 1 * 2 * 3 * 4 * 5 = 120;
My C... |
I am able to print the result,but not able to print like this : let n
= 5 Output : 1 * 2 * 3 * 4 * 5 = 120;
That's indeed what your code is doing. You only print the result.
If you want to print every integer from 1 to N before you print the result you need more cout calls or another way to manipulate the output.
Thi... |
71,626,672 | 71,626,806 | How to pipe/redirect the final stdout of a NCurse command? | I have a command that displays Ncurses stuffs (initscr, printw, addch, ...). That's okay.
At the end (endwin), I want to "output" (std::cout << "some string") a string to be processed by other command (or maybe redirected to a stream).
I want to do something like this :
my-ncurse-command | any-other-command
my-ncurse-c... | Instead of initscr(), use newterm(). If you are already using newterm it's just a matter of supplying a different output stream than stdout.
initscr() is equivalent to:
#include <cstdlib>
WINDOW* myinitscr() {
newterm(getenv("TERM"), stdout, stdin);
return stdscr;
}
so
#include <cstdio>
#include <cstdlib>
st... |
71,627,268 | 71,669,814 | Couldn't Reproduce non-friendly C++ cache code | I'm playing with some chunks of code that intentionally tries to demonstrate ideas about CPU Cache, and how to get benefit of aligned data and so on.
From this article http://igoro.com/archive/gallery-of-processor-cache-effects/ which I find very interesting I'm trying to reproduce the behavior of these two loops (exam... | Your mistake is not using any optimization. The overhead of the non-optimized code masks any cache effects.
When I don't use any optimization, I get the following:
$ g++ -O0 cache.cpp -o cache
$ ./cache
Using std::vector
Step: 16 Elements
Array Elements: 67108864
Array Size: 64 MBs
Int Size: 4
[F... |
71,627,519 | 71,627,856 | Multiple inheritance from a pack expansion | I recently saw this in production code and couldn't quite figure out what it does:
template <class... Ts>
struct pool : pool_type<Ts>... {
//...
};
I've never seen pack expansion happening for parent classes. Does it just inherit every type passed into the varargs?
The parents look like this:
template <class T>
struct... |
Does it just inherit every type passed into the varargs?
Yes. It inherits publicly from each of the passed arguments. A simplified version is given below.
From Parameter pack's documentation:
Depending on where the expansion takes place, the resulting comma-separated list is a different kind of list: function parame... |
71,627,889 | 71,627,945 | deduced class type 'Pair' in function return type | I need to write a dictionary in c++. I wrote a Pair class which contains 1 key + value pair. I also wrote a Dictionary which contains vector pairs. I want to overload the [] operator, but it gives me an error.
template <typename TKey, typename TValue>
class Pair
{
public:
TKey key;
TValue value;
Pair()
... | The compiler needs to know what kind of Pair you're returning.
Pair<TKey, TValue> operator[] (unsigned index)
{
...
}
You may want to add a type alias to shorten the declarations:
template <typename TKey, typename TValue>
class Dictionary
{
public:
using EntryType = Pair<TKey, TValue>;
private:
vector<Ent... |
71,627,959 | 71,628,662 | How can I modify the code fragment in order to remove all specified elements from array in c++? | I have this code
#include <iostream>
using namespace std;
int deleteElement(int mas[], int pos, int x)
{
int i;
for (i = 0; i < pos; i++)
if (mas[i] == x)
break;
if (i < pos)
{
pos = pos - 1;
for (int j = i; j < pos; j++)
mas[j] = mas[j + ... | Using remove_if is probably the best solution here, but assuming you aren't allowed to use it, then you need to keep track of whether an item was removed, and how many elements are being removed. Currently, you find the first element, then modify the array to remove only that element.
Using your method, you could make ... |
71,628,233 | 71,632,648 | the questions about scanf() and cin | I met a questions. the link ->
the problem
here is my solution.If i use scanf, the code can be accepted on codeforces, but replace cin then not,it occurs wrong answer,but in my local interpreter using cin is ok.
why?
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
scanf("%d", &t);
nt :
... | You have another scanf in line 5 which you have to replace too. Otherwise they each have their own buffers of the input and get mixed up.
|
71,628,693 | 71,628,802 | Dividing a number in c++ by 3 long's | I'm currently writing a program where an user can input an amount that is dividable by the numbers 50, 20 and 10.
The way I'm trying to get it to work is that for example a user fills in the amount of 180, the program will calculate something like
"3 tickets of 50 have been used"
"1 ticket of 20 has been used"
"1 ticke... | What I believe you want is a divide and reduce schema:
#include <iostream>
int main() {
std::cout << "enter amount: ";
if(long ui; std::cin >> ui) {
long c50s = ui / 50; // divide
ui -= c50s * 50; // reduce amount
long c20s = ui / 20; // divide
ui -= c20s * 20; // redu... |
71,629,300 | 71,629,316 | How to strlen in constexpr? | I'm using clang++ 13.0.1
The code below works but it's obviously ugly. How do I write a strlen? -Edit- Inspired by the answer, it seems like I can just implement strlen myself
#include <cstdio>
constexpr int test(const char*sz) {
if (sz[0] == 0)
return 0;
if (sz[1] == 0)
return 1;
if (sz[2] ... | You can just use C++17 string_view and get the length of the raw string through the member function size()
#include <string_view>
constexpr int test(std::string_view sz) {
return sz.size();
}
Demo
Another way is to use std::char_traits::length which is constexpr in C++17
#include <string>
constexpr int test(const ch... |
71,629,529 | 71,630,224 | Test if elements are sorted with C++17 fold-expression | I am looking for a way to check that arguments are sorted using a c++ fold expression.
The naive approach:
template <typename... Args>
bool are_strictly_increasing(Args const&... args) {
return (args < ...);
}
Does not work as it expands to ((arg0 < arg1) < arg2) < ... which ends up comparing bool to whatever the ... | It seems to me that is better if your first argument is isolated anyway
template <typename A0, typename... Args>
constexpr bool are_strictly_increasing(A0 const & a0, Args const&... args)
Supposing there is a common type for the arguments
using CT = std::common_type_t<A0, Args...>;
and given two variable of common ty... |
71,629,571 | 71,629,707 | bitand : keyword vs function in C++ | I've tried using the alternative bitwise operator 'bitand' in below simple code. Its appears that I can use bitand as a keyword as well as a function in Visual C++, both yielding different results, can anyone explain this discrepancy?
int d = 12, e = 37;
std::cout << (d & e) << std::endl; //4
std::cout << (d bitand e) ... | Despite appearances, bitand(d, e) is not invoking a function named bitand and passing it the arguments d and e. bitand is just another way of spelling &.
So your code is actually identical to &(d, e). & isn't a function, so what's the comma doing here? It is the lesser-known built-in comma operator. It evaluates and di... |
71,629,672 | 71,630,644 | std::atomic<bool> execution guarantee? | I know std::atomics are supposed to have well defined behavior, but I can't find an easy-to-digest online answer to this question: Do std::atomic.load() and .store() have execution guarantees?
If two threads attempt a concurrent write or read on the same std::atomic object, are both the write and read guaranteed to be... | It is a basic assumption that the compiler and processor ensures that the programmed operations are executed. This has nothing to do with std::atomic<>. The guarantee which std::atomic<> offers is that single operations happen atomically.
So what does that mean?
Consider two threads, A and B, which both increment the s... |
71,629,785 | 71,630,332 | Is user-defined conversion to fundamental-type deletable? | template<typename Integral>
struct IntegralWrapper {
Integral _value;
IntegralWrapper() = default;
IntegralWrapper(Integral value)
: _value(value) {}
operator Integral() const {
return _value;
}
operator bool() const = delete;
};
int main() {
IntegralWrapper<int> i1,... | First of all: Deleting a function does not prevent it from being considered in overload resolution (with some minor exceptions not relevant here). The only effect of = delete is that the program will be ill-formed if the conversion function is chosen by overload resolution.
For the overload resolution:
There are candi... |
71,630,290 | 71,630,694 | C++ Nested map: accessing inner map | Why does accessing the inner map in a nested C++ map only sometimes update the value accessible through the outer map? Specifically, why do cases 1 and 3 in the code below not update the value m[500]["text"]?
My understanding is that indexing into the outer map in all of these cases returns a reference to inner map. So... | auto inner = m1[500];
...
map<string, int> inner3 = m3[500];
auto cannot deduce references. Both these statements will create copies of the inner map. Modifying those will just update the copy instead of the original value.
Use references in both cases to achieve the desired effect:
auto& inner = m1[500];
...
map<stri... |
71,630,767 | 71,630,945 | Visual Studio throwing LNK2019 and solution missing headers/source files | -- Updates --
Adding the source file settings.cpp directly to the project via Add -> Existing Item resolved the LNK2019 (as I suspected it couldnt find it).
-- Updated Question--
How to specify a source file directory without having to add all the files within it manually as described in the update above? This is cl... | You need to add all .cpp files to your project as Existing Items. Just being in a directory is not sufficient for the IDE to know to compile those files. Headers are found by directory via #include, but you should still add them to your project as Existing Items to make it easier to navigate them in the tree view.
This... |
71,630,906 | 71,631,824 | C++17 - How to deduct the variadic parameter pack of a lambda passed as a template parameter? | I have a class memoize which deducts the variadic argument list of a function pointer passed to it as a template parameter (see code below).
I would like to be able to do the same thing for a lambda, but I don't seem to find the right way to do it. Ideally it should work when uncommenting and completing the last line o... | The following should do the trick. Note that the pack_helper logic has been modified, even for function pointers.
template<typename... Ts> struct pack { };
// helper functions to retrieve arguments for member function pointers
template<class Result, class Type, class ...Args>
pack<Args...> lambda_pack_helper(Result(... |
71,631,178 | 71,632,594 | Member values not accessed in vector of instances of different subclasses | Jumping off of the above question Making a vector of instances of different subclasses : when implementing a vector of (pointers to) different subclasses (initialized as vector<Base*> objects), I expect to be able to access the correct member variables based on the subclass called.
Below is sample code:
#include <iostr... | The problem is due to a misunderstanding on inheritance. If you redefine your Mesh as follows, it would work as expected:
class Mesh : public Entity {
public:
//int index; // No don't redefine: here you'd have two different indexes
Mesh(int x) {this->index=x;};
void hit() override {} ... |
71,631,195 | 71,631,216 | I can't access to a value of my objectin C++ | I'm starting C++ : I was trying to make my "player1" attack my "player2", to make him remove health to my "player2" and finally to display the health of "player2". But it's not working and I can't find the mistake.
Here's my code I hope you will be able to help me:
PLAYER.CPP
class Player {
public:
std::string pse... | Here:
void attack(Player aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
The parameter aTargetPlayer is passed by value, this means you decreased the health of a copy, not the original one. You must pass by reference, like this:
void attack(Player &aTargetPlayer) {
aTargetPlayer.healthValue ... |
71,631,428 | 71,631,538 | reachability with std::launder | I'm trying to understand the following snippet from CPP reference. Can someone explain in a little more detail why x2[1] is unreachable from source ? Can't we reach it via &x2[0][0] + 10 for example?
int x2[2][10];
auto p2 = std::launder(reinterpret_cast<int(*)[10]>(&x2[0][0]));
// Undefined behavior: x2[1] would be r... | The reachability condition basically asks whether it is possible to access a given byte of memory via pointer arithmetic and reinterpret_cast from a given pointer. The technical definition, which is effectively the same, is given on the linked cppreference page:
(bytes are reachable through a pointer that points to an... |
71,631,523 | 71,631,543 | Implementation of a class into a header file and .cpp file | I've been learning c++ and trying to implement a class i made in a solution to a header file and source file for future use.in the header file i have implemented the following definitions and methods
#ifndef CVECTOR_H
#define CVECTOR_H
class cVector {
public:
float Xpos;
float Ypos;
flo... | This would be the correct syntax. This needs to be placed outside of main():
cVector::cVector(float x, float y, float z) { // Constructor with parameters
Xpos = x;
Ypos = y;
Zpos = z;
}
|
71,631,539 | 71,631,848 | should I check pointers in such situations? | I'm new to programming and game development in general
every time I read and hear that pointers are a nightmare I want to ask if it is necessary to check pointers in such cases as shown below?
// create a component of a certain type and return a pointer to data of this type
StaticMeshCompt = CreateDefaultSubobject<USta... | No, there's no need to check the pointer. The cases where CreateDefaultSubobject could return nullptr are :
The class passed is nullptr (It's guaranteed to be valid for any UObject).
The class has the abstract flag (Not the case for
UStaticMeshComponent).
Allocation itself fails due to lack of free memory (At that poi... |
71,631,588 | 71,631,648 | Why C++ pretends to forget previously parsed templates? | Here is data serialization program which compiles with gcc 11.1:
#include <fstream>
#include <ranges>
#include <concepts>
#include <map>
using namespace std;
void write( fstream & f, const integral auto & data ) {
f.write( (const char*)&data, sizeof( data ) );
}
void write( fstream & f, const pair<auto,auto> & p ... | In order for a function to participate in overload resolution, it must be declared before the point of the use in the compilation unit. If it is not declared until after the point of use, it will not be a possible overload, even if the compile has proceeded past the point of definition (eg, if the use is in a instatia... |
71,631,983 | 71,631,992 | What is the different between a[i+1] and a[i]++? | I am not able to understand why both values are different and how does it change?
int a[100]
for(int i=0; i<100; i++)
cin >> a[i];
int i=20;
cout << a[i+1] << endl;
cout << a[i]++;
I tried to know value of both
| a[i+1] that means value of i+1th index. which means, lets suppose if i=20 and it has value of 50 and a[21] has value of 200 then a[i+1] means a[i+1]=200
so when it's about a[i+1] then it point to the next
and a[i]++ that means increase 1 by ith index value.
so i=20 and a[i]=50 and a[i]++ means 50+1 which is 51
|
71,632,098 | 71,632,458 | Why is std::is_copy_constructible_v<std::vector<MoveOnlyType>> true? | In my version of clang and libc++ (near HEAD), this static_assert passes:
static_assert(std::is_copy_constructible_v<std::vector<std::unique_ptr<int>>>)
Of course if you actually try to copy-construct a vector of unique pointers it fails to compile:
../include/c++/v1/__memory/allocator.h:151:28: error: call to implici... | std::vector and other containers (except std::array) are specified to have a copy constructor. This is not specified to be conditional on whether or not the element type is copyable. Only instantiation of the copy constructor's definition is forbidden if the element type is not copyable.
As a result std::is_copy_constr... |
71,632,495 | 71,633,203 | C++ (cpp-netlib) http listener - how to remove headers | I created an HTTP listener that accepts POST requests for files. I followed this template almost exactly:
https://github.com/cpp-netlib/cpp-netlib/blob/main/libs/network/example/http/echo_async_server.cpp
I start my listener like so: ./build/http_listener 0.0.0.0 8000
Then post file to the listener using curl: curl --... | body__ does not get populated with header data. What you see is multipart data that you submit with --form <name=content>. If you want submit raw file data use another curl command:
curl --data-binary "@file1.txt" -H "Content-Type: application/octet-stream" http://127.0.0.1:8000/
-X POST can be omitted if is used wit... |
71,633,347 | 71,636,515 | C++ std::string attribute of a class comes up as an empty string after initialized | So i have a pretty straight foward homework that consist in creating a student class that has a name and 3 grades as attributes and a method to caluculate the final grade and append the name as well as the final grade to 2 vectors respectively, the problem comes up when i try to append the name to the vector as its app... | As the user Taekahn said in a comment, i used This -> and it now appends it perfectly.
Thank you.
|
71,633,508 | 71,633,542 | Can we have a condition to compare int and string data type? | How can i make a condition to compare int and string?
int number;
string guess;
if (guess!=number){
cout <<"You lose";
else cout<<"You win!!";
| One option would be to use std::to_string to convert the int to a std::string and then perform the comparison as shown below:
int number = 5; std::string guess = "5";
//----------vvvvvvvvv------------------------->use std::to_string
if(std::to_string(number)!= guess)
{
std::cout<<"not equal"<<std::e... |
71,634,035 | 71,634,840 | C++ Inherited class function not working in class constructor, pass by reference string not changing | I have a class named Filesys inheriting a class Sdisk
class Sdisk
{
public:
Sdisk(string disk_name, int number_of_blocks, int block_size);
Sdisk(); //default constructor
...
int getblock(int blocknumber, string& buffer); //buffer is changed but doesn't change when called by Filesys constructor
... | The ctor of Filesys should forward the parameters to the base class ctor.
Something like:
Filesys::Filesys(string disk_name, int number_of_blocks, int block_size)
: Sdisk(disk_name, number_of_blocks, block_size)
{
// ...
}
Otherwise the members of the base class (e.g. diskname) are not initialized properly,... |
71,634,469 | 71,634,497 | what is the use of keyword override in virtual function of child class? | The keyword virtual allows the derived class to override in need of polymorphism, and this can be down with or without the keyword override. How does adding override affect the program?
example code:
#include <iostream>
using namespace std;
class Base {
public:
void Print() {who();}
virtual void who() { cout <... | Adding override to a member function does not change the way your program works in any way. You merely tell the compiler that you want to override a base class function and that you'd like to get a compilation error if you somehow made a mistake, thinking that you are overriding a function, when you are in fact not.
Ex... |
71,634,710 | 71,634,934 | How to write more readable c++20 concepts? | I'm writing a template class that wraps a user-supplied class in an elaborate wrapper. I'm looking for a better way to enforce interface requirements for a target type using C++20 concepts.
(The precise application is a template class that simplifies marshalling of a co-await call onto a separate non-coroutine executio... | You can use two requires clauses, first determine whether T has a member type of return_type, which can be used to stop the concept check as early as possible
template<typename T>
concept IoCoServiceImplementation =
requires { typename T::return_type; } &&
requires (
T& t, CoServiceCallback<typename T::return... |
71,634,835 | 71,656,023 | Why does `consteval` not behave as expected? | inline consteval unsigned char operator""_UC(const unsigned long long n)
{
return static_cast<unsigned char>(n);
}
inline consteval char f1(auto const octet)
{
return char(octet >> 4_UC);
}
inline constexpr char f2(auto const octet)
{
return char(octet >> 4_UC);
}
int main()
{
auto c1 = f1('A'); // o... | This is a bug of clang 14 and has been fixed.
See: https://github.com/llvm/llvm-project/commit/ca844ab01c3f9410ceca967c09f809400950beae
|
71,634,987 | 71,635,055 | Why do I have a line break? | there is a problem with the code. Displays an error "std::out_of_range at memory location". during debugging.
The task of the code is to find all the letters "A" in the text and delete them.
**С++ code:
**
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a;
getline(cin, a);
in... | There are two problems with this do-while loop
do {
n = a.find('a',1);
cout << n;
a.erase(n, 0);
cout << a;
} while (n != -1);
The first one is that you are starting to search the letter 'a' starting from the position 1 instead of the position 0.
The second one is that if the letter 'a' is not found th... |
71,635,311 | 71,637,217 | How to copy the content of a binary file into an array | I am currently working on a chip-8 emulator and I have a method which loads in the program by copying a binary file into an array called 'memory'. However, it doesn't work as mentioned on the tutorial page and I'm a little bit confused. I've already researched this problem but I couldn't find anything helpful for my sp... | You are not reading. You need to use a "read" function to read from the file. Please read here
Replace
memory[i] = fptr[i]; // ! Does not work !
with
memory[i] = fgetc(fptr); // ! Does work !
|
71,635,516 | 71,635,546 | Priority of template constructor | I have the template class Foo:
template<class T>
class Foo {
public:
Foo() = default;
Foo(const Foo&) = default;
Foo(Foo&&) = default;
Foo& operator=(Foo&&) = default;
Foo& operator=(const Foo&) = default;
template<class U, typename = typename std::enable_if<
!std::is_same<typename ... | In your main() function, you're trying to construct a Foo<char> from a Foo<int>. A decay-based ctor will not work here, as Foo<A> does not decay into Foo<B> even if A decays into B. See the cppreference page on std::decay for a detailed explanation of what it does, exactly.
Also, I would suggest avoiding explicit (temp... |
71,635,517 | 71,636,312 | C++ polymorphism factory How to build function object from its string name and map of parameter | #include <cassert>
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <any>
#include <functional>
#include <type_traits>
using namespace std;
using MapAny = map<string, any>;
class FunctionBase {
public:
FunctionBase() {}
FunctionBase(const MapAny ¶m_maps) {}
virtual any o... | You may use an template based abstract factory. This is very generic and can be used for different types of keys and values.
Maybe the following generic code gives you an idea, how you could implement your factory.
#include <iostream>
#include <map>
#include <utility>
#include <any>
// Some demo classes -------------... |
71,635,599 | 71,635,622 | How to check if a character in a string equals "w" | I am failing to compare characters of a string in my program, I made a simpler version to showcase the problem:
#include <iostream>
using namespace std;
int main() {
string s = "Hello world!";
for(int i = 0; i<s.size(); i++) {
if(s[i] == "w") {
cout << "This is... | "w" is a pointer to the C string ['w', '\0'] in memory. You want to use single quotes instead so you are only comparing the character literal.
if (s[i] == 'w') {
cout << "This is a w!" << endl;
}
|
71,636,394 | 71,636,446 | If … change a variable’s value | I’m trying to make a tic-tac-toe program; I'm adding an if statement to change a variable's value if the condition is met. But when the condition is met, the variable that's value should be changed is 0.
I'm doing this in c++
cout <<player1 << ", which position would you like to add your X?: " << endl;
cin >> x1;
if ... | To check if variables are equal you should use == operator.
You can read more about comparison operators here
|
71,636,589 | 71,636,693 | How to get current visible portion of QGraphicsView in Qt? | I have QGraphicsView, which has multiple QGraphicsItem's. On this view, I am applying some transformation using features like Zoom-in, zoom-out, fit -In etc.
So before applying fit-in feature on my current view, I want to store view's current transformation ( view's current situation ) in a variable. And then I want t... | As revealed by source code of mapToScene, three parameters define the part of the scene that is visible on the viewport:
QGraphicsView::transform()
QAbstractScrollArea::horizontalScrollBar()->value()
QAbstractScrollArea::verticalScrollBar()->value()
To implement an undo-redo framework, those three parameters should b... |
71,636,592 | 71,642,972 | Boost::process hide console on linux | According to this question : Boost::process hide console on windows
How can I achieve the same but on Linux platform using boost::process ? (prevent console window creation on the newly spawn child process)
My use case is as followed:
I'm trying to call a cross-platform GUI app built from .NET 5.0 AvaloniaUI (C#). And ... | Linux does not create new console, like the others suggested. (unless explicitly define to)
After more investigation, I found that, it's only a misunderstanding.
If you use some GUI lib (like GTKmm, in this case), and try to spawn new process, which is a GUI window also, there might be an afterimage-like effect if you ... |
71,637,182 | 71,647,999 | Segmentation fault when logging using spdlog in an app that includes another spdlog | I have a native library that uses spdlog for internal logging.
The library is compiled as shared library and the results .so files are then used in an Android project which has its own JNI and native c++ code which also uses spdlog.
The first time a call to spdlog is made, we experience a SIGSEGV from it. After some re... | So turns out the solution was just to upgrade to a newer version of spdlog
|
71,637,486 | 71,637,566 | cannot bind non-const lvalue reference of type 'Node&' to an rvalue of type 'const Node' | I am trying to implement a linked list with struct but i have a problem. I get this error when i try to delete the node. Can someone please help me?
struct Node {
int value;
Node *previous;
Node *next;
};
// *current_node in all functions is a random address of a node in the linked list
Node get_node(size_... | The problem is that the function delete_node has its first parameter as a reference to non-const Node while the function get_node returns a Node by value. This means that the call expression get_node(2, &node1) is an rvalue. But since, we cannot bind a reference to non-const Node to an rvalue of type Node, you get the ... |
71,637,499 | 71,637,613 | Error while passing a vector to a Constructor in C++ | I'm new with C++ OOP. Seems that in my simple code i'm not passing correctly an argument to the constructor of my class. Where's the error?
This is the class that i've defined
class Bandiera
{
private:
vector<string> colori;
public:
Bandiera(vector<string> c)
{
colori = c;
}
bool biancoPresente()
{
for (short... | The class Bandiera does not meet the requirements of std::map<Key,T,Compare,Allocator>::operator[]
mapped_type must meet the requirements of CopyConstructible and DefaultConstructible.
class Bandiera must be CopyConstructible and DefaultConstructible, i.e. define a copy and default constructors, or you should use s... |
71,637,899 | 71,638,195 | Find the column with the maximum negative matrix element and the column with the minimum element | I want to know the column with the maximum negative matrix element and the column with the minimum element so that I can rearrange them. More specifically, I'm interested in return values of The column with the maximum negative element: and The column with the minimum element: But about half the time, the results about... | I assume that this is some kind of homework, since normally, we'd use vectors and algorithms to write much shorter code.
The following loop doesn't find the maximal negative:
// search for the maximal negative element
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < 0 && arr[i][j] > a... |
71,638,159 | 71,660,448 | Created from BMP texture has excess pixels in OpenGL 2.1 | I am using OpenGL 2.1 in my academic work to create a 3D scene. I have a 24-bit BMP file, a texture for a cube side, that is loaded manually into the memory.
Straight to the problem: displayed texture has some excess pixels at the lower left corner. BMP file, of course, doesn't have these pixels, it has a full black bo... | I can see an error in your code which could cause the problem you're seeing.
data = (unsigned char *) malloc (sizeof (unsigned char) * image_size);
fread (data, sizeof (char), image_size, file);
free (data);
You are allocating a buffer, reading into it, then immediately freeing it. This means that any code between fre... |
71,638,221 | 71,639,183 | OpenSSL: EVP_DigestSign() does't work on the Raspberry pi | I have trouble creating signatures with OpenSSL on a Raspberry Pi. RSA, ECDSA and EdDSA fail. Here is a small example:
#pragma once
#include <vector>
#include <string>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
void main()
{
// message to be sign
std::string msg_str = "my messsa... | solved!
this error occurs (only on ARM) when out_len is smaller than the final signature length. I need to change the code as follows:
from
if (EVP_DigestSign(md_ctx, sig_out.data(), &out_len, msg.data(), msg.size()) == 0)
{
std::cout << "EVP_DigestSign error: " << ERR_error_string(ERR_get_error(), NULL) << std::en... |
71,638,231 | 71,638,267 | math output on C++ (checked against other language) | I am writing this in C++:
int main()
{
cout<<"print "<< int(((float(979430543) - float(800445804))/2.0)+.5);
}
for output: 89492352
and checking against julia language:
print(Int64(((Float64(979430543) - Float64(800445804))/2.0)+.5))
89492370
The difference between the results is 18 - what am i missing?
| float in C++ is most likely to be 32 bits, while Float64 is, well, surely 64 bits wide. Change your float casts to double casts in the C++ version and it will surely produce the expected output.
|
71,638,236 | 71,638,284 | Memory issue when freeing 2D arrays | 2D Array creation phase :
int **table = new int*[10];
for (int a = 0; a < 10; a++)
{
table[a] = new int[10];
for(int b = 0; b < 10; b++){
table[a][b] = 0;
}
}
2D Array deletion phase :
for (int i = 0; i < 10; i++)
{
delete [] table[i];
}
delete [] table;
I noticed something while debugging my... | Yes, the data is actually being freed. If you dereference a pointer after its value is freed, you get undefined behaviour which might be its original value or some other garbage value.
|
71,638,657 | 71,639,238 | C++ How can I use values from specific rows and columns in two dimensional array? | I have two dimensional array that represents country and its medals from certain competition.
Output:
Gold Silver Bronze
Country1 1 0 1
Country2 1 1 0
Country3 0 0 1
Country4 1 0 0
Country5 ... | As noted in comments, you actually need to calculate the points total and output it.
for (int i = 0; i < COUNTRIES; i++){
int total = arr[i][0] * 4 + arr[i][1] * 2 + arr[i][2];
cout << total << endl;
}
|
71,639,234 | 71,639,354 | Can you access anonymous objects/types in C++? | I'm currently learning about references in C++. Here's something I've been wondering about:
int x = 5;
const int &ref = 3 * x + 1;
My understanding of this is that an anonymous variable is created for this expression 3 * x + 1 to be stored in it. After that, we tie our reference ref to that anonymous variable. That wa... | This is called a temporary object (it is not a variable). And it doesn't store the expression, but the result of the expression.
Normally such objects are destroyed at the end of the full expression in which they are created. However if a reference is bound to them immediately, then these objects will live as long as t... |
71,639,265 | 71,694,610 | QtWebEngine, How to Save Cookies in C++/Qt6.2.4? | Since I change Qt5 to Qt6 for my app,
What worked for Qt5 (to save the cookies, I followed this thread QT 5.6 QWebEngine doesn't save cookies),
Doesn't work now :
QWebEngineProfile::defaultProfile()->setPersistentCookiesPolicy(QWebEngineProfile::ForcePersistentCookies);
QWebEngineProfile* defaultProfile = QWebE... | The Solution is :
QWebEngineProfile *profile = new QWebEngineProfile(QString::fromLatin1("MyApplication.%1").arg(qWebEngineChromiumVersion())); // unique profile store per qtwbengine version
QWebEnginePage *page = new QWebEnginePage(profile); // page using profile
QWebEngineView *view = new QWebEngineView(... |
71,639,351 | 71,820,870 | Undefined symbols for architecture x86_64: "RtMidiIn::RtMidiIn | I'm trying to connect to a MIDI device from an existing program. RtMidi is a popular library for this. As I understand, all I should have to do is drop RtMidi.cpp and RtMidi.h in the directory with the rest of the source, and build as usual. I've done so, and added to one of the main classes that get loaded:
#include "... | @AdrianMole was right—I had to explicitly instruct CMake to build the RtMidi files. I added the files in the relevant CMakeLists.txt under SOURCES:
sp_add_sources(TARGET playback
FOLDER "src"
ROOT "src"
SOURCES
RtMidi.cpp
RtMidi.h
audio_buffered_sink.cpp
audio_buffered_sink.h
audio_container_f... |
71,639,386 | 71,639,458 | Perfect forwarding in the visitor pattern std::visit of C++ | I was watching Jason Turner C++ weekly and I came across this code snippet.
template<typename... B>
struct Visitor: B...{
template<typename... T>
Visitor(T&&...t): B(std::forward<T>(t))...{}
using B::operator()...;
};
template<typename...T>
Visitor(T...) -> Visitor<std::decay_t<T>...>;
int main(){
std::array<s... |
I can get rid of the perfect forwarding
Passing by a const reference would copy the lambdas instead of moving them.
It doesn't matter in your case, but it will matter if the lambdas capture things by value. It can hurt performance if the lambdas are expensive to copy, or cause a compilation error if the lambdas can't... |
71,640,156 | 71,640,170 | Using struct constructor to create an struct instance in C++ | I am trying to wrap my mind around this talk: https://www.youtube.com/watch?v=FXfrojjIo80
I get an error on the following part. It is the simplified version.
template<typename... Ts>
struct parms : Ts... {};
template<typename... Ts>
parms(Ts... ) -> parms<Ts...>;
struct first{};
struct second{};
int main(int argc, c... | Cppreference aptly calls it "Parenthesized initialization of aggregates".
|
71,640,163 | 71,640,433 | Is this a correct way to store different types in the same allocation? | I need to allocate a chunk of memory using malloc and then store multiple values of different plain old data types in there. Is the following a correct way to do it?
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <iostream>
struct Foo {
int32_t a;
int32_t b;
};
struct Bar {
int8_t a;
... | Implicit object creation will cause the allocated memory block to contain an array of char of suitable size and the pointer returned from malloc will point to the first element of that array.
(That is assuming std::malloc doesn't return a null pointer, which you should check for.)
Such an array can provide storage for ... |
71,640,394 | 71,640,481 | Reading from file without using string | I am doing a school project where we must not use std::string. How can I do this? In the txt file the data are separated with a ";", and we do not know the length of the words.
Example:
apple1;apple2;apple3
mango1;mango2;mango3
I tried a lot of things, but nothing worked, always got errors.
I tried using getline, but ... | There are two entirely separate getline()'s. One is std::getline(), which takes a std::string as a parameter.
But there's also a member function in std::istream, which works with an array of chars instead of a std::string, eg:
#include <sstream>
#include <iostream>
int main() {
std::istringstream infile{"apple1;ap... |
71,640,617 | 71,640,707 | Extend C++ application (executable) with dynamically linked library code? | I do not want to provide client with source code to an application (executable) but do want to allow the client to extend application functionality by modifying source written in a dynamically linked library.
The executable has a function called void handleGetResource(request, response) to handle incoming http requests... | What you are describing is a plugin model where users or customers can provide their own compiled extensions to "handle" functionality on behalf of an application.
On Windows, you specify that customers build a DLL and export a function that matches your expected function signature. On Linux, you ask them to build a sh... |
71,640,667 | 71,641,009 | C++ set how to check if a list of sets contains a subset | I have a list of sets, right now the list a vector but it does not need to be.
vector<unordered_set<int>> setlist;
then i am filling it with some data, lets just say for example it looks like this:
[ {1, 2}, {2, 3}, {5, 9} ]
Now i have another set, lets say its this: {1, 2, 3}
I want to check if any of these sets in ... | Consider using a list of set<int> instead. This allows you to use std::include. Run your loop on the vector after having sorted it by number of elements in the set (i.e. from the sets with the smallest number of elements, to the sets with the largest number of items). The inner loop will start at the current index. Thi... |
71,640,880 | 71,640,913 | error: cannot call member function without object - but I have an object? | I'm trying to compile the following code but I receive this error:
CommandProcessing.cpp:86:58: error: cannot call member function ‘bool CommandProcessor::validate(std::string)’ without object
86 | if (CommandProcessor::validate(game->currentCommand())) {
Here is the relevant code. I don't understand why it won... | If the function validate is not a static member function then you need to specify an object for which it is called as for example
if (game->validate(game->currentCommand())) {
|
71,640,946 | 71,980,273 | Reading a vector of maps with yaml-cpp fails | I want to read the following yaml data:
camera:
response_values: [[0.0: 0.0, 1.0: 1.1, 245.0: 250.1], [0.0: 0.1, 1.0: 1.3, 200.0: 250], [0.0: 0.0, 1.0: 1.1, 245.0: 250.1]]
I want to read it into a vector < map <float, float> >. In this case, the vector would have 3 maps with each 3 entries.
My attempt is this:
#inclu... | #include <assert.h>
#include <fstream>
#include <iostream>
#include <map>
#include <yaml-cpp/yaml.h>
using namespace std;
int main() {
YAML::Node camerafile = YAML::LoadFile("./camera.yaml");
YAML::Node camera = camerafile["camera"];
auto response_values_yaml = camera["response_values"];
// it is the seque... |
71,641,267 | 71,641,310 | How do I add numbers in C++ again? | Seriously, I don’t remember..
Would an integer work??
But I don’t know why its not working...
I'm trying to add integers, like this.
int main() {
i = 1;
b = 3;
}
Signed int addition() {
i + b
}
| You can't use functions and variables, including local variables, parameters, etc before they have been declared first. Though, you can initialize variables at the same time you declare them. For example:
#include <iostream>
int addition(int a, int b);
int main() {
int i = 1;
int b = 3;
int sum = addition(i... |
71,641,342 | 71,641,399 | how to simplify this pseudocode | I have this pseudocode in IDA but I don't understand the result when I compiled it
__int64 v17 = 507890351016;
__int64 v20 = 0;
auto test = *(WORD*)(*(uintptr_t*)v17 + v20);
the output of test is 48, can someone explain what's going here and what the equivalent in c++
| v17 is a 64 bit integer, v20 is a 64 bit integer. v17 seems to be a pointer and whatever is at that address is being dereferenced to a DWORD type and stored in test. Because v20 == 0, the offset from v17+v20 is 0.
The result is
int64_t v17 = 507890351016;
DWORD test = *(DWORD*)v17;
|
71,641,525 | 71,641,683 | How to print any number or random access containers? | Let's assume I have N random access containers (std::vector and std::array for example) of different types, and that all containers have the same length. I want to write to write a function that prints them in a column-ordered fashion, i.e.:
#include <vector>
#include <iostream>
#include <array>
#include <complex>
con... | You don't need to create any temporaries. Here's an implementation that requires at least one container to be present, but you can remove that requirement by adding an empty overload:
// Handles empty parameters by doing nothing
void vprint() {}
// Handle non-empty parameters
template<typename T, typename... Ts>
void ... |
71,642,084 | 71,658,008 | What is the YUV format of the decoded hevc file with using libde265 | i'm using libde265(www.libde265.org) to decode my hevc file in c++ project and try to save the decoded YUV as pictures. But i hava a problem to find the address of the Y,U,V values in c++ project.
Does anybody know, which format of YUV we get, when we use libde265 decode a hevc file? YUV420, YUV420P, YUV420SP, etc.?
Th... | I have tried many things :-) And i think that is YUV420P and has 3 planes.
Using the method
const uint8_t* de265_get_image_plane(const struct de265_image*, int channel, int* out_stride);
we can get the Y from channel 1 and u,v from channel 2 and 3.
|
71,643,040 | 71,643,128 | Synchronization with "versioning" in c++ | Please consider the following synchronization problem:
initially:
version = 0 // atomic variable
data = 0 // normal variable (there could be many)
Thread A:
version++
data = 3
Thread B:
d = data
v = version
assert(d != 3 || v == 1)
Basically, if thread B sees data =... | You might be looking for a SeqLock, as long as your data doesn't include pointers. (If it does, then you might need something more like RCU to protect readers that might load a pointer, stall / sleep for a while, then deref that pointer much later.)
You can use the SeqLock sequence counter as the version number. (ver... |
71,643,582 | 71,643,850 | why am I getting the error terminate called after throwing an instance of 'ErrorException' | I'm trying to get all the values within a vector but whenever I run this code it just gives me an Error exception I don't know where the error is.
For everyone that is asking vector.h is apart of the standford library
this is the txtfile I'm using
#include <iostream>
#include <fstream>
#include <string>
#include <cstri... | This is your error:
for(int i = 0; text.size(); i++)
{
if(text[i].find("(") != string::npos && isInteger(text[i]))
for-loop doesn't work like that, second expression is a boolean expression which is checked against true before entering loop's body. Stanford library class Vector::operator [] acts in same way... |
71,644,189 | 71,644,376 | Explicit template instantiation for a templated function parameter | I want to write the definition of a templated function in the .cpp file, instead of it being in the header.
Let's take this simple example:
// func.h
template <class T>
void print_message(T func) {
func();
}
// main.cpp
#include <iostream>
#include "func.h"
void say_hello() {
std::cout << "hello" << std::en... | The issue is not that you provide the definition in the source. You did place the definition in the header. Moreover there is only a single translation unit in your example. The error would be the same if you place all code in main.cpp.
The issue is that print_message has a type argument, but say_hello is not a type.
T... |
71,644,651 | 71,647,658 | What exactly is the problem that memory barriers deal with? | I'm trying to wrap my head around the issue of memory barriers right now. I've been reading and watching videos about the subject, and I want to make sure I understand it correctly, as well as ask a question or two.
I start with understanding the problem accurately. Let's take the following classic example as the basis... | The two mail questions you have both have the same answer (Yes!), but for different reasons.
First let's look at this particular piece of pseudo-machine-code
Let's say the instructions of thread 1 will be something like:
1 load f to register1
2 if f is 0 - jump to 1
3 load x to register2
4 print register2
What exactl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.