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;
struct constantVariable
{
string constantName;
string constantValue;
};
void defineReplace(string line)
{
vector <constantVariable> constant;
string token;
stringstream stream(line);
while(stream >> token)
{
if(token == "#define")
{
stream >> token;
constant.constantName = token;
stream >> token;
constant.constantValue = token;
break;
}
}
constant.push_back(constant);
}
| 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 = token;
constant.push_back(addconstant);
}
}
But take care with checking the input stream. It should not be done as easy as you did it... but that is another question.
|
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 statements in the slot function.
The following is a snippet of the MyClass.h file where the slot is declared:
private slots:
void onRenderProcessTerminated(QWebEnginePage::RenderProcessTerminationStatus terminationStatus, int exitCode);
The following is a snippet from the constructor of MyClass.cpp file where the signal and slot are connected:
connect(ui->webEngineView, &QWebEngineView::renderProcessTerminated, this, &MyClass::onRenderProcessTerminated);
The following is the slot function onRenderProcessTerminated from MyClass.cpp (cout is a function I created to output messages in the web engine view and works fine):
void MyClass::onRenderProcessTerminated(QWebEnginePage::RenderProcessTerminationStatus terminationStatus, int exitCode) {
cout("INSIDE RENDER PROCESS TERMINATED");
}
|
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 documentation clearly states:
This signal is emitted when the render process is terminated with a non-zero exit status. terminationStatus is the termination status of the process and exitCode is the status code with which the process terminated.
In English, the verb you'd be looking for is finished instead of terminated. The former implies the latter: when a process is finished, it has terminated. But the reverse is not necessary: a process may well terminate before it's finished with its task, e.g. if it crashes, or is terminated when the parent process exits, etc. But also: the RenderProcess doesn't mean "a task of rendering something". It literally means "the operating system process that performs the rendering". That process normally must stay alive for as long as you have any web views active.
The only signal I can see that approximates what you want is QWebEngineView::loadFinished(bool ok). Try it out.
Ohterwise, for finer notifications, you'll need to inject some javascript into the view, and interact with it. It may be more effort than it's worth.
|
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 dll's anywhere.
I need to be really specific with my IT dept to get this fixed. I want to add the dll to the system path but I have to find them first!
I managed to find VC_redist.x64.exe in C:\ProgramData\Package Cache\{2aaf1df0-eb13-4099-9992-962bb4e596d1} but I think that is pretty strange... it may be unrelated to the install.
Any help appreciated!
| 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. You can then enter
cd %VCINSTALLDIR%
in the terminal to get where the directory is located on your machine.
|
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 typically, <cstddef> because it is very small and has other definitions that I'm likely to need such as std::byte.
|
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:10: fatal error: 'cstddef' file not found
After trying to reinstall Xcode tools, download the header to set it in my env, I have no more idea.
Do you have any idea to fix this or anybody had the same ?
Thank
PS : this is my CMakeLists
cmake_minimum_required(VERSION 3.0)
project(MasterDSA)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_C_STANDARD 99)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -o3")
add_library(Addition src/addition.c include/addition.h)
add_executable(Main src/main.c)
target_link_libraries(Main Addition)
set_target_properties(Main
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}/bin")
set (gtest_force_shared_crt ON CACHE BOOL "MSVC defaults to shared CRT" FORCE)
add_subdirectory(googletest/googletest)
target_compile_definitions(gtest
PUBLIC
GTEST_LANG_CXX20
GTEST_HAS_TR1_TUPLE=0
)
add_executable(tests)
target_sources(tests
PRIVATE
test/addition_test.c
)
set_target_properties(tests PROPERTIES COMPILE_FLAGS "${cxx_strict}")
target_link_libraries(tests gtest gtest_main Core)
| 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 considerable care is exercised then it is possible to write code in the shared subset of the two languages or that use the preprocessor to adapt to the chosen language, but this is uncommon, except sometimes for headers that declare functions and external objects having (from the C++ perspective) C linkage. That evidently is not how your gtest.h is written.
Your main options are:
convert your project to a C++ project. This has significant implications, so do not do it lightly.
write C++ tests for your C code. This may or may not be viable.
choose a C test framework instead of C++-specific GTest.
|
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 << "Compiled in DEBUG\n";
#else
qDebug() << "QDEBUG IS ACTIVE!";
std::cout << "Compiled in RELEASE\n";
#endif
Does not matter if I compile in Release or Debug configuration, the line "QDEBUG IS ACTIVE!" gets printed.
P.S. I get correct cout for release and debug, so the configurations are working!
What am I doing wrong?
| 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(${PROJECT_NAME} PUBLIC
QT_NO_DEBUG_OUTPUT
QT_NO_INFO_OUTPUT
QT_NO_WARNING_OUTPUT
)
endif()
|
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>
CChQuCached::operator bool()
{
return true;
}
int main()
{
CChQuCached ChQuCached;
ChQuCached.operator bool<CChQuAuth>(); // compile error !
}
I got compile error with VS22.
to solve thanks for your help...
| 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 template type convertible to bool. Define conversion operator to that type.
Consider that you actually should do something else. Perhaps visitor pattern is what you're looking for.
Using a default template argument for a template conversion function to a non-template type OR using a template-id as target for conversion function are ONLY ways how one can pass a template-argument while instantiating and invoking said conversion function. E.g.:
class CChQuAuth {
public:
CChQuAuth() { }
};
template <typename T>
struct MyBool {
bool v;
operator bool() { return v;};
};
class CChQuCached {
public:
CChQuCached() {
}
template <typename T>
operator typename ::MyBool<T>();
};
template <typename T>
CChQuCached::operator typename ::MyBool<T>()
{
return MyBool<T>();
}
int main()
{
CChQuCached ChQuCached;
bool b = ChQuCached.operator MyBool<CChQuAuth>();
}
That's just an example and no way a proper boilerplate code. Note that conversion operator name expected to be a nested type-id first, and in this case it is given as fully qualified one, with ::.
|
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.enqueue(item);
. . .
// pthread
void* Logger(void* arg) {
MyType.item;
while (true)
if (!q.try_dequeue(item))
This doesnt (object appears to be corrupted after dequeue:
// declared on the top of the file
moodycamel::ConcurrentQueue<MyType*> q; // logger queue
. . .
int MyCallbacks::Event(MyType* p)
{
MyType item = (MyType)*p;
q.enqueue(&item);
. . .
// pthread
void* Logger(void* arg) {
MyType* item;
while (true)
if (!q.try_dequeue(item))
also tried this in the Event - still doesnt work (the &newdata always prints same address):
auto newdata = std::move(data);
printf(" - pointers - new: %p old: %p\n", &newdata, &data);
q.enqueue(&newdata);
Am I doing it wrong or is it the queue doesnt support pointers?
| 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. Dereferencing that invalid pointer will lead to undefined behavior.
There's no need to create a local copy here at all, you should be able to work with p directly instead, including adding it to the queue:
q.enqueue(p);
With that said, you don't need the cast in
MyType item = (MyType)*p;
The type of *p already is MyType. Generally speaking, when you feel the need to do a C-style cast like that you should take it as a sign that you're doing something wrong.
If you need a copy, why not create a new object to copy-initialize?
Like:
MyItem* item = new MyItem(*p);
q.enqueue(item);
You of course have to remember to delete the object once you're finished with it.
A better solution than using raw non-owning pointers would be using a smart pointer like std::unique_ptr:
moodycamel::ConcurrentQueue<std::unique_ptr<MyType>> q; // logger queue
// ...
q.enqueue(std::make_unique<MyItem>(*p));
|
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 pool loop function while loop variable to be set to true so that the thread can finish its work and join. But since atomics are thread safe, I didn't lock the mutex before assigning true to it in the shutdown method as shown below. This ended up causing a deadlock. Why is that the case?
ThreadPool.hpp:
#pragma once
#include <atomic>
#include <vector>
#include <iostream>
#include <thread>
#include <future>
#include <mutex>
#include <queue>
#include <functional>
#include <ThreadSafeQueue.hpp>
class ThreadPool{
public:
ThreadPool(std::atomic_bool& result);
void waitForCompletion();
void addJob(std::function<bool()> newJob);
void setComplete();
private:
void workLoop(std::atomic_bool& result);
int m_numThreads;
std::vector<std::thread> m_threads;
std::atomic_bool m_workComplete;
std::mutex m_mutex;
std::condition_variable m_jobWaitCondition;
ThreadSafeQueue<std::function<bool()>> m_JobQueue;
};
ThreadPool.cpp:
#include <ThreadPool.hpp>
ThreadPool::ThreadPool(std::atomic_bool& result){
m_numThreads = std::thread::hardware_concurrency();
m_workComplete = false;
for (int i = 0; i < m_numThreads; i++)
{
m_threads.push_back(std::thread(&ThreadPool::workLoop, this, std::ref(result)));
}
}
// each thread executes this loop
void ThreadPool::workLoop(std::atomic_bool& result){
while(!m_workComplete){
std::function<bool()> currentJob;
bool popped;
{
std::unique_lock<std::mutex> lock(m_mutex);
m_jobWaitCondition.wait(lock, [this](){
return !m_JobQueue.empty() || m_workComplete.load();
});
popped = m_JobQueue.pop(currentJob);
}
if(popped){
result = currentJob() && result;
}
}
}
void ThreadPool::addJob(std::function<bool()> newJob){
m_JobQueue.push(newJob);
m_jobWaitCondition.notify_one();
}
void ThreadPool::setComplete(){
m_workComplete = true;
}
void ThreadPool::waitForCompletion(){
{
std::unique_lock<std::mutex> lock(m_mutex);
m_workComplete.store(true);
}
m_jobWaitCondition.notify_all();
for(auto& thread : m_threads){
thread.join();
}
m_threads.clear();
}
ThreadSafeQueue.hpp:
#pragma once
#include <mutex>
#include <queue>
template <class T>
class ThreadSafeQueue {
public:
ThreadSafeQueue(){};
void push(T element) {
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.push(element);
}
bool pop(T& retElement) {
std::unique_lock<std::mutex> lock(m_mutex);
if (m_queue.empty()) {
return false;
}
retElement = m_queue.front();
m_queue.pop();
return true;
}
bool empty(){
std::unique_lock<std::mutex> lock(m_mutex);
return m_queue.empty();
}
private:
std::queue<T> m_queue;
std::mutex m_mutex;
};
| 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 to notify your condition when the task is completed.One possible place to do that is when you call for wait to complete or in any point where a completion state can be achieved.
I changed your code to this to illustrate:
// each thread executes this loop
void ThreadPool::workLoop(std::atomic_bool& result){
while(!m_workComplete)
{
std::function<bool()> currentJob;
bool popped;
{
std::cout<<"Before the lock"<<std::endl;
std::unique_lock<std::mutex> lock(m_mutex);
std::cout<<"After lock"<<std::endl;
m_jobWaitCondition.wait(lock, [this]()
{
bool res = (!m_JobQueue.empty() || m_workComplete.load() );
std::cout<<"res:"<<res<<std::endl;
return res;
});
std::cout<<"After wait"<<std::endl;
popped = m_JobQueue.pop(currentJob);
}
if(popped)
{
std::cout<<"Popped"<<std::endl;
result = currentJob() && result;
std::cout<<"Popped 2"<<std::endl;
}
}
std::cout<<"LEave"<<std::endl;
}
void ThreadPool::addJob(std::function<bool()> newJob){
m_JobQueue.push(newJob);
std::cout<<"before call notify"<<std::endl;
m_jobWaitCondition.notify_one();
std::cout<<"After call notify"<<std::endl;
}
I add a single job and the printed content is:
Before the lock
After lock
res:0
Before the lock
After lock
Before the lock
Before the lock
Before the lock
res:0
Before the lock
After lock
res:0
After lock
res:0
Before the lock
After lock
res:0
After lock
before call notifyres:1
Before the lockAfter wait
Popped
After lock
res:0
After call notifyres:0
Popped 2
Before the lock
res:0
res:0
res:0
res:0
After lock
res:0
After lock
res:0
Notice that last notify is called BEFORE the last "after lock" line (that precedes the condition wait)
|
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 state - user must try to send new input
AVERROR(EOF): the decoder has been fully flushed, and there will be no more output frames
AVERROR(EINVAL): codec not opened, or it is an encoder > other negative values: legitimate decoding errors
You could just do the following:
switch (res) {
default: puts("unknown result"); break;
case 0: puts("success"); break;
case AVERROR(EAGAIN): puts("output is not available"); break;
//... you get the idea
}
|
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 invoke an implicit constructor taking a pointer to Res as single parameter, but not an explicit one.
Here's a simplified example using a custom class with no assignment operators and just a single constructor:
class Test
{
public:
Test(int i) { }
// mark all automatically generated constructors and assignment operators as deleted
Test(Test&&) = delete;
Test& operator=(Test&&) = delete;
};
int main()
{
Test t = 1;
}
Now change the constructor to
explicit Test(int i) { }
and the main function will no longer compile; the following alternatives would still be viable:
Test t(1);
Test t2{1};
|
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;
return result;
}
int main()
{
int *pointer = makeArray(10);
/* code ... */
return 0;
}
It is compiling and working but logically it makes no sense because I deleted my array.
So I tried the following:
int *makeArray(int size)
{
int *result = new int[size];
return result;
}
int main()
{
int *pointer = makeArray(10);
/* code ... do some stuff with pointer */
delete[] pointer;
return 0;
}
Is this safe or does it cause a memory leak? Is there a better way of returning the pointer?
I tried both versions and they are compiling and working but I'm sure at least one of them if not both are unsafe.
|
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 delete operator you're telling your OS that it can release the memory and use it for whatever it wants. Reading or writing to it is very dangerous (Program crashing, Bluescreen, Destruction of the milky way)
int *makeArray(int size)
{
int *result = new int[size];
return result;
}
int main()
{
int *pointer = makeArray(10);
/* code ... do some stuff with pointer */
delete[] pointer;
return 0;
}
Is this safe or does it cause a memory leak?
Yes this is the correct way of using the new and delete operator. You use new so your data stays in memory even if it gets out of scope. Anyway it's not the safest code because for every new there has to be a delete or delete[] you can not mix them.
Is there a better way of returning the pointer?
YES. It's called Smart Pointer. In C++ programmers shouldn't use new but smart pointer at all. There is a C++ community Coding Guideline to avoid these calls Guideline R11
|
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 the first one if needed. Any way to do this?
| 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::cout << "2" << std::endl;
return RET_TYPE(x);
}
}
int main()
{
int i = fn(5); // Error, no matching overload found
double d = fn<double>(5);
};
|
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
virtual void Close();
};
/* RAII zarker - opens Things before zarking, and closes them afterwards */
class Zarker {
public:
Zarker(Thing& thing): m_thing(thing) {
m_thing.Open();
}
~Zarker() {
m_thing.Close();
}
void ZarkBy(int amount) {
m_thing.Zark(amount);
}
private:
Thing& m_thing;
}
I then have a Trompeloeil mock class that implements the interface:
struct MockThing: public ThingInterface {
MAKE_MOCK0(Open, void(), override);
MAKE_MOCK1(Zark, void(int), override);
MAKE_MOCK0(Close, void(), override);
};
I then wish to test a "zarking" of 42:, including the (critical) Open and Close procedure.
MockThing mockedThing;
trompeloeil::sequence sequence;
REQUIRE_CALL(mockedThing, Open())
.IN_SEQUENCE(sequence));
REQUIRE_CALL(mockedThing, Zark(42))
.IN_SEQUENCE(sequence));
REQUIRE_CALL(mockedThing, Close())
.IN_SEQUENCE(sequence));
Zarker zarker(mockedThing);
zarker.ZarkBy(42);
This works nicely and demonstrates that a Zarker does, in fact, close its Thing after use (Bad Things happen if it does not).
Now, I have a lot more tests to go, and I'd like to stay DRY and avoid duplicating the mock expectations for the Open and Close calls. In real life, these expectations are actually not just a pair of functions, there are other setup and teardown actions that have to happen in careful order, and it'll be very annoying to have to repeat this in every test.
Since this is a RAII idiom, it seems natural to also use that for the expectations. However, because Trompeloeil expectations are scoped, you have to use NAMED_REQUIRE_CALL and save the unique_ptr<trompeloeil::expectations>:
class RaiiThingAccessChecker {
public:
/* On construction, append the setup expectation(s) */
RaiiThingAccessChecker(
MockThing& thing,
trompeloeil::sequence& sequence,
std::vector<std::unique_ptr<trompeloeil::expectation>>& expectations
):
m_thing(thing),
m_sequence(sequence),
m_expectations(expectations) {
m_expectations.push_back(
NAMED_REQUIRE_CALL(m_thing, Open())
.IN_SEQUENCE(m_sequence)
);
}
/* On wrapper destruction, append the teardown expectation(s) */
~RaiiThingAccessChecker() {
m_expectations.push_back(
NAMED_REQUIRE_CALL(m_thing, Close())
.IN_SEQUENCE(m_sequence)
);
}
private:
MockThing& m_thing,
trompeloeil::sequence& m_sequence,
std::vector<std::unique_ptr<trompeloeil::expectation>>& m_expectations
}
Then you can use it like this:
MockThing mockedThing;
trompeloeil::sequence seq;
std::vector<std::unique_ptr<trompeloeil::expectation>> expectations;
{
RaiiThingAccessChecker checker(mockedThing, seq, expectations);
mockExpectations.push_back(
NAMED_REQUIRE_CALL(mockedThing, Zark(42))
.IN_SEQUENCE(seq)
);
}
Zarker zarker(mockedThing));
zarker.ZarkBy(42);
So that's functional enough, but it seems rather verbose - you have to hold
a container of expectation pointers, the sequence outside the RaiiThingAccessChecker
and you also have to pass them all in, and store references internally.
Is there a more concise way, or otherwise idiomatic way to achieve this kind
of "expectation reuse"? I have a lot of "modular" expectations that can be modelled like this.
| 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] = *res;
REQUIRE_CALL(mock, Open()).IN_SEQUENCE(sequence));
inner(mock, sequence);
REQUIRE_CALL(mock, Close()).IN_SEQUENCE(sequence));
return res;
);
And then
auto p = MakeMockedThing([](MockThing& thing, trompeloeil::sequence& sequence)
{
REQUIRE_CALL(thing, Zark(42)).IN_SEQUENCE(sequence));
});
auto& [mock, sequence] = *p;
Zarker zarker(mock);
zarker.ZarkBy(42);
Note: std::pair<MockThing, trompeloeil::sequence> might probably be replaced by template class to have nicer syntax.
|
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 algorithm, I want to iteratively find the element with the smallest value that has not been visited yet, work with it, and then "disable" it by setting visited to true, so that this element is not found in the next iteration.
it = std::min_element(std::begin(vct_priority), std::end(vct_priority), cmp);
indx_smallest = std::distance(std::begin(vct_priority), it);
// do something here
vct_priority[indx_smallest].visited = 1;
Normally I would use a priority queue, but as I need to index into this array during the algorithm, I couldn't find a better way.
The problem is, that this approach is fishy. In cases where vct_priority looks like this:
{1,true}
{0,true}
{1,false}
{0,true}
{2,false}
{2147483647,false}
{2147483647,false}
{0,true}
{1,false}
{0,true}
{2,false}
{2147483647,false}
{1,false}
The computed indx_smallest is incorrectly 0, instead of 2.
Could you help me find the error, or suggest some better suitable solution?
| 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 }, { 0, true }, { 1, false }, { 0, true },
{ 2, false }, { 2147483647, false }, { 2147483647, false },
{ 0, true }, {1, false }, { 0, true }, { 2, false },
{ 2147483647, false }, { 1, false }
};
auto less_not_visited = []( const auto &e1, const auto &e2 )
{
return ( not e1.visited ) && ( e2.visited or e1.val < e2.val );
};
auto min = std::min_element( std::begin( vct_priority ),
std::end( vct_priority ),
less_not_visited );
std::cout << std::distance( std::begin( vct_priority ), min ) << '\n';
}
The program output is
2
If you want to define a separate function instead of the lambda expression then it looks like
bool less_not_visited( const element_t &e1, const element_t &e2 )
{
return ( not e1.visited ) && ( e2.visited or e1.val < e2.val );
};
|
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 (unsigned i = 0; i < this->pairs.size(); i++)
{
if (this->pairs[i].key == key)
return this->pairs[i].value;
}
return NULL;
}
if I use NULL it gives me a warning (g++ compiler):
warning: converting to non-pointer type 'int' from NULL
| 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 instance of std::optional template instead. Example:
std::optional<TValue> getByKey(TKey key)
{
// ...
return std::nullopt;
}
P.S. You can replace your loop that implements linear search with the standard function std::find.
P.P.S If you have many values, then may want to consider using another data structure that has faster key lookup such as std::unordered_map.
P.P.P.S Don't use NULL for pointers either. It has been obsoleted by nullptr.
|
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 try to add class object with int64_t variable, it gives following error:
use of overloaded operator '+' is ambiguous (with operand types 'number' and 'int64_t' (aka 'long'))
Of course, I can overload the operator for other types, but I'm wondering if there is another solution for this problem and why, in the case of the first operator, the conversion from one type to another occurs automatically?
Thanks in advice!
UPD: Here is class header:
class number {
private:
int64_t m_value;
public:
number();
number(int64_t value);
number(const number& copy);
number& operator=(const number& other);
number& operator++();
number operator++(int);
number& operator--();
number operator--(int);
number& operator+=(const number& right);
number& operator-=(const number& right);
number& operator*=(const number& right);
number& operator/=(const number& right);
number& operator%=(const number& right);
number& operator&=(const number& right);
number& operator|=(const number& right);
number& operator^=(const number& right);
number operator+(const number& right);
number operator-(const number& right);
number operator*(const number& right);
number operator/(const number& right);
number operator%(const number& right);
number operator&(const number& right);
number operator|(const number& right);
number operator^(const number& right);
operator bool() const;
operator int() const;
operator int64_t() const;
operator std::string() const;
friend std::ostream& operator<<(std::ostream& out, const number& num);
friend std::istream& operator>>(std::istream& in, number& num);
};
| 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, hence the ambiguity.
There are several ways to resolve this.
Make one of the conversions explicit.
Make both conversions explicit and do not use expressions like x + y.
Make both conversions explicit and define (lots and lots of) overloads that take number and int64_t operands.
|
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 vectors resize themselves, not about concurrent accesses, data races, etc.
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.
Thanks!
| 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 contains just a few pointers, that's it. The memory is allocated from the dynamic storage(heap) almost always. Unless you override it with your own allocator and use alloca or similar dangerous stuff.
So if you do
std::vector<int> local_variable{1,2,3,4};
The memory for the three pointers inside local_variable will be on stack but 1,2,3,4 objects are on the heap.
|
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) <--- work
find_package(Python3 3.6 COMPONENTS Interpreter NumPy REQUIRED) <--- not work
include_directories(${PYTHON_INCLUDE_DIRS})
add_executable(myProj main.cc)
target_link_libraries(myProj ${PYTHON_LIBRARIES} Python3:NumPy)
Error
[cmake] CMake Error at CMakeLists.txt:9 (find_package):
[cmake] By not providing "FindPython3.cmake" in CMAKE_MODULE_PATH this project has
[cmake] asked CMake to find a package configuration file provided by "Python3", but
[cmake] CMake did not find one.
[cmake]
[cmake] Could not find a package configuration file provided by "Python3"
[cmake] (requested version 3.6) with any of the following names:
[cmake]
[cmake] Python3Config.cmake
[cmake] python3-config.cmake
[cmake]
[cmake] Add the installation prefix of "Python3" to CMAKE_PREFIX_PATH or set
[cmake] "Python3_DIR" to a directory containing one of the above files. If
[cmake] "Python3" provides a separate development package or SDK, be sure it has
[cmake] been installed.
Path of NumPy
(venv) cyan@linux01:~/TEMP$ python -c "import numpy; print(numpy.get_include())"
/home/cyan/venv/lib/python3.6/site-packages/numpy/core/include
Question
How can I revise my CMakeLists.txt so to include the header numpy/arrayobject.h in C++?
| 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.0)
Updating your CMake version is probably the simplest solution but again you might have good reason to limit the version and just telling you to update isn't much of a solution.
Another hackier solution would be to use one of the paths from Python_INCLUDE_DIRS or Python_LIBRARIES do some relative pathing from there. Something like
set(numpy_INCLUDE_DIR "${Python_INCLUDE_DIR}/../site-packages/numpy
/core/include")
include_directories(${Python_INCLUDE_DIRS} ${numpy_INCLUDE_DIR})
This however assumes that your python directories are setup as if they came from a python distribution and would in turn assume that everyone that uses this also has a distribution with the same file structure.
|
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 to access the values of the objects held in the vector. Is there a better way to do this? Here is a smallest reproducible example. Thank you.
#include <vector>
class Obj
{
private:
int val;
public:
Obj() { val = 10; }
inline int getVal() { return val; }
};
class Foo
{
private:
std::vector<Obj> obsVec;
public:
Foo()
{
Obj a;
Obj b;
obsVec.push_back(a);
obsVec.push_back(b);
}
const std::vector<Obj>& getConstRef() const { return obsVec; }
};
int main()
{
Foo foo;
foo.getConstRef()[0].getVal(); // Here is where I get the error
return 0;
}
The error that I get is:
Error (active) E1086 the object has type qualifiers that are not compatible with the member function "Obj::getVal"
| 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 was wondering if there is an RAII way that would allow to take the lock conditionally.
Something like
if(condition){
// the lock is taken
}
// do a bunch of things
// lock is automatically released if it was taken
| 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<std::mutex> guard(some_mutex, std::defer_lock_t{});
if (mutex_should_be_locked)
{
guard.lock();
}
// rest of code
} // scope exit, unlock will be called if the mutex was locked
|
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;
sort(a.begin(), a.end(), [](ci v, ci u) { return arg(cd(v)) < arg(cd(u)); });
but it does not work either (compilation error: no matching function for call to ‘std::complex<double>::complex(ci&)).
Can I sort these numbers without changing their type?
| 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;
std::sort(a.begin(), a.end(), [](const auto& v,const auto& u) {
return std::arg(std::complex<double>(v.real(),v.imag())) < std::arg(std::complex<double>(u.real(),u.imag()));
});
}
Note that you can also use atan2 directly without constructing the std::complex<double> as mentioned by user17732522.
Last but not least, reconsider if you really need int with std::complex. From cppreference:
T - the type of the real and imaginary components. The behavior is unspecified (and may fail to compile) if T is not float, double, or long double and undefined if T is not NumericType.
Basically this means that you need to check the implementation you are using whether it supports std::complex<int> at all.
|
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 understand what this means or what to do about it, but I think I narrowed it down to having something to do with the std::random_device rd;
here is my struct:
struct RandNormGen {
std::random_device rd;
std::mt19937 gen;
std::normal_distribution<float> normalDist;
RandNormGen() {
gen = std::mt19937(rd());
normalDist = std::normal_distribution<float>(0, 1);
}
float randFloat(float sigma, float mean = 0) {
float r = normalDist(gen) * sigma + mean;
return r;
}
};
any help or insight would be appreciated!
| 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 = std::mt19937(std::random_device{}());
or skip the constructor entirely and use default member initializers, since your default constructor does nothing but initialize the members:
struct RandNormGen {
std::mt19937 gen{std::random_device{}()};
std::normal_distribution<float> normalDist;
float randFloat(float sigma, float mean = 0) {
float r = normalDist(gen) * sigma + mean;
return r;
}
};
(The default constructor of std::normal_distribution already initializes to distribution parameters to 0 and 1 but std::normal_distribution<float> normalDist{0, 1}; would work as well.)
Be aware however of what you are doing that causes the requirement for the copy constructor in the first place.
If you actually copy rather than move the class object, you will end up with two instances of the class with the same state of the random number generator, meaning that the random numbers generated in the copy will not be different from those generated in the original.
If that is not the behavior you want, you can delete the copy constructor explicitly so that only moves will be allowed:
RandNormGen() = default;
RandNormGen(const RandNormGen&) = delete;
RandNormGen(RandNormGen&&) = default;
RandNormGen& operator=(const RandNormGen&) = delete;
RandNormGen& operator=(RandNormGen&&) = default;
or you can define a copy constructor and assignment operator with the intended semantics (e.g. reseeding the generator).
Even more generally, consider moving the random number generator out of the class. There is usually not really any point in having a random generator for each object. Usually having a generator per thread in the program is sufficient.
|
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 folder and then repack them into an aac file as fast as possible
void Repacker(string FileName)
{
string data;
boost::filesystem::path p = "./tmp/";
boost::filesystem::ofstream aacwriter;
aacwriter.open("./" + FileName + ".aac", ios::app);
boost::filesystem::ifstream aacReader;
boost::filesystem::directory_iterator it{ p };
cout << "Repacking File!" << endl;
while (it != boost::filesystem::directory_iterator{}) {
aacReader.open(*it, std::ios::in | ios::binary);
cout << "Writing " << *it << endl;
aacReader >> data;
++it;
aacwriter << data;
aacReader.close();
}
aacwriter.close();
}
I have looked at the following questions to try and help solve this issue
Merging two files together
Merge multiple txt files into one
How do I read an entire file into a std::string in C++?
Read whole ASCII file into C++ std::string
Merging Two Files Into One
However unfortunately, none of these answer my question.
They all either have to do with text files, or functions that don't deal with hundreds of files at once.
I am trying to write Binary data, not text. The audio is either all warbled or the file is only a few bytes long.
If there's a memory efficent method to do this, please let me know. I am using C++ 20 and boost.
Thank you.
| 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 to concatenate media files without being forced to reencode data. It's a bit complex because FFMPEG's command line is quite complex and not always extremely intuitive, but it should works as long as all AAC files uses the same encoding and characteristics. Otherwise, you'll need to re-encode them - but it can be done automatically, too.
Check this web research to get some base informations.
Otherwise, you may use the base libraries used by FFMPEG, for example libavcodec (available at ffmpeg.org), Fraunhofer FDK AAC, etc. but you'll have way, way more work to do and, finally, you'll do exactly what FFMPEG already do, since it relies on these libraries. Other AAC libraries won't be really easier to use.
Obviously, you can also "embed" FFMPEG within your application, call tools like ffprobe to analyze files and call ffmpeg executable automatically, as a child process.
CAUTION: Take a GREAT care about licensing if you plan to distribute your program. FFMPEG licensing is really not simple, most of the time it's distributed as sources to avoid vicious cases.
|
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_Init(SDL_INIT_EVERYTHING);
SDL_Window* window = SDL_CreateWindow("title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 600, 400, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
SDL_Delay(3000);
return 0;
}
| 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 interpretation), I made multiple references to indirected typecast pointers. But when I ran the program, I got a segfault trying to write to the references in the struct. As near as I can tell, the problem has to do with the container, as illustrated by this example snippet (cpp shell: http://cpp.sh/3vmoy):
#include <iostream>
#include <cstring>
using namespace std;
#define PACKET_SIZE 9
#define ARG_I 4
struct Message{
uint8_t bytes[PACKET_SIZE];
uint8_t* argbytes = static_cast<uint8_t*>(argp);
float& argf = *static_cast<float*>(argp);
void* argp = &bytes[ARG_I];
} message;
int main(){
// USING STRUCT
cout << "Using message struct" << endl;
cout << message.argp << endl; // the pointer at index stored in struct
cout << static_cast<float*>(message.argp) << endl; // casting the pointer to a float* - should be the same
cout << &message.argf << endl; // the address of the float reference cast from argp, ** should be the same BUT IS NOT **
// RAW VARS
uint8_t bytes[PACKET_SIZE];
void* argp = &bytes[ARG_I];
float& argf = *static_cast<float*>(argp);
cout << endl << "using raw vars" << endl;
cout << argp << endl; // a pointer to a byte in an array of bytes.
cout << static_cast<float*>(argp) << endl; // the same pointer cast as a float*
cout << &argf << endl; // the address of a float reference cast from argp, **should be the same AND IS.**
}
I expect to see the same address for the pointer, a typecast pointer, and the address of the reference for the indirected pointer. I do see that if I create an array and the pointer/reference as standalone variables, but not for the same declarations in a struct. What arcane knowledge do I lack to explain this behavior (or what silly thing have I overlooked?)
My thoughts for fixing this are to a) ignore it and just typecast the pointer as necessary instead, or b) make some setter/getter functions to access the argument portion of the serial "packet".
| 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 does not.
This initializes argf first, then argp. The consequences of this should be quite apparent.
Note: I'm ignoring all the aliasing rule violations here, that are likely to be a source of further undefined behavior.
|
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;
};
class LinkedList {
private:
Node* head;
public:
LinkedList()
{
head = NULL;
}
void print()
{
Node* current = head;
if (head != nullptr)
{
do
{
std::cout << current->data << " ";
current = current->next;
}
while (current != head);
}
}
};
int main()
{
LinkedList link_one;
int nodes;
std::cout << "nodes ";
std::cin >> nodes;
for (int index = 0; index < nodes; index++){
link_one.print();
}
link_one.print();
std::cout << std::endl;
}
| 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 goal:
int place_node(int idx) //no need to return
{
Node* current = head;
int count, index = 0;
for(int i=0;i<idx;++i) current = current->next;
current->data+=1;
return 1; // no need to return
}
|
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 parallel.
| 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();
// non-blocking code to be executed once every 3 sec
}
}
As Arduino is written in C++, feel free to create a timer class doing this for you (and avoid static or global variables) But that's probably beyond your question.
|
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 build 64 bit executable for Project 1.
So i want some CMake commands to ensure that Project 1 can be built on 32 bit only.
Something like
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
##ABORT##
in Project 1. Thanks
| 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 the fact that it usually requires very little effort to compile the binaries of a project for different configurations. If parts of your project only apply to certain configurations, it would be user-friendly to provide a main CMakeLists.txt for the project that makes the appropriate choices without resulting in an error during configuration.
A good way of accompilishing this would be to conditionally add the subdirectory in the parent CMakeLists.txt.
if(CMAKE_SIZEOF_VOID_P EQUAL 4)
add_subdirectory(project1)
else()
message("Not a 32 bit build; not adding Project 1")
endif()
add_subdirectory(project2)
Even with this approach you should keep the snippet with the fatal error in the subproject to prevent issues, if some user uses your project in an unintended way and uses Project 1 as source directory instead of your main project dir.
|
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++ -o $@ $(CPPFLAGS) $(OBJECTS)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(HEADER_DIR)/%.h
g++ $(CPPFLAGS) -c $< -o $@ -I $(HEADER_DIR)
clean:
del $(OBJ_DIR)\*.o $(EXECUTABLE)
CPPFLAGS = -std=c++11
Above is my makefile. It doesn't update after main.cpp gets changed while it works for main.cpp only when I remove the header file from the dependency.
i.e. change this line $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(HEADER_DIR)/%.h
to
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
Why is that happening?
| 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 will continue looking for some other rule to build the object file.
If no other rule is found, make will tell you that there is no rule to build the object file.
If you're getting this error for main.cpp, then it means that there is no corresponding main.h file.
You either need to create a main.h file, or change this pattern rule to not put the header as a prerequisite (you add the headers of other files as prerequisites directly), or create a new pattern rule that doesn't require the header.
|
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 to only accept template arguments of the same type. This means, that the statement inside the main should fail and should only work when all the template arguments are of the same type. Essentially, there are 2 requirements:
The code should not work for less than 1 template argument. That is, at least one template argument must be present. If the user provides 0 template arguments then it should not work.
The code should not work for different type of template arguments.
I don't if this is even possible. I was thinking of maybe using enable_if or some other feature but i don't know what might help here.
| 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()
{
string str = "ABC";
Class1 a(str);
Class2 b(str);
Class3 c(str);
}
I'm trying to find the cost of my constructor.
Class 1: cost 1 copy constructor
Class 2: cost 1 copy constructor and 1 move constructor
Class 3: cost 1 copy constructor + {A. nothing, B. move constructor, C. copy constructor}
Is the compiler smart enough to copy str directly into c.s ? What is the answer for the 3rd case?
Big edit: using a vector-like class, the answer is C. But is there any reason why the compiler can't steal s_ even when the object will be destructed after s(s_) ?
#include <iostream>
#include <string>
using namespace std;
template <typename T = int>
class MyVector {
private:
int n;
T* data;
public:
MyVector() {
n = 0;
data = nullptr;
cout << "MyVector default constructor\n";
}
MyVector(int _n) {
n = _n;
data = new T[n];
cout << "MyVector param constructor\n";
}
MyVector(const MyVector& other) {
n = other.n;
data = new T[n];
for (int i=0; i<n; i++) data[i] = other.data[i];
cout << "MyVector copy constructor\n";
}
MyVector(MyVector&& other) {
n = other.n;
data = other.data;
other.n = 0;
other.data = nullptr;
cout << "MyVector move constructor\n";
}
MyVector& operator = (const MyVector& other) {
if (this != &other) {
n = other.n;
delete[] data;
data = new T[n];
for (int i=0; i<n; i++) data[i] = other.data[i];
}
cout << "MyVector copy assigment\n";
return *this;
}
MyVector& operator = (MyVector&& other) {
if (this != &other) {
n = other.n;
delete[] data;
data = other.data;
other.n = 0;
other.data = nullptr;
}
cout << "MyVector move assigment\n";
return *this;
}
~MyVector() {
delete[] data;
cout << "MyVector destructor: size = " << n << "\n";
}
int size() {
return n;
}
};
class Class1 {
MyVector<> s;
public:
Class1(const MyVector<>& s_) : s(s_) {}
};
class Class2 {
MyVector<> s;
public:
Class2(MyVector<> s_) : s(std::move(s_)) {}
};
class Class3 {
MyVector<> s;
public:
Class3(MyVector<> s_) : s(s_) {}
};
int main()
{
MyVector<> vec(5);
cout << "-----------\n";
cout << "Class1\n";
Class1 a(vec);
cout << "\n------------\n";
cout << "Class3\n";
Class2 b(vec);
cout << "\n------------\n";
cout << "Class3\n";
Class3 c(vec);
cout << "\n------------\n";
return 0;
}
| 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 is unchanged. Since you cannot observe copies of a string being made if you don't take addresses of the string objects, the compiler is free to optimize the copies away in any case.
If you take a constructor argument to be stored in a member by-value, there is no reason not to use std::move.
|
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 Code:
# include <bits/stdc++.h>
using namespace std;
int Factorial (int N)
{
int i = 0;int fact = 1;
while (i < N && N > 0) // Time Complexity O(N)
{
fact *= ++i;
}
return fact;
}
int main()
{
int n;cin >> n;
cout << Factorial(n) << endl;
return 0;
}
|
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.
This should only be an idea this is far away from being a good example but it should do the job.
int main()
{
int n;cin >> n;
std::cout << "Factorial of " << n << "!\n";
for (int i =1; i<=n; i++)
{
if(i != n)
std::cout << i << " * ";
else
std::cout << n << " = ";
}
cout << Factorial(n) << endl;
return 0;
}
Better approach using std::string and std::stringstream
#include <string>
#include <sstream>
using namespace std;
int main()
{
int n;
cin >> n;
stringstream sStr;
sStr << "Factorial of " << n << " = ";
for (int i = 1; i <= n; i++)
{
if (i != n)
sStr << i << " * ";
else
sStr << i << " = ";
}
sStr << Factorial(n) << endl;
cout << sStr.str();
return 0;
}
|
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-command > some-stream
Problem is : my ncurses display is captured by the pipe or the redirect, not only the final string.
Is there a way to allow that ?
Thanks.
| 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>
std::FILE* cursesout{};
WINDOW* myinitscr() {
cursesout = std::fopen("/dev/tty", "w"); // open new stream to your terminal
if(cursesout) newterm(std::getenv("TERM"), cursesout, stdin);
return stdscr;
}
and after endwin():
std::fclose(cursesout);
Alternatively, use a smart pointer to not have to std::fclose the new output stream manually:
#include <cstdio>
#include <cstdlib>
#include <memory>
using FILE_ptr = std::unique_ptr<FILE, decltype(&std::fclose)>;
FILE_ptr cursesout{nullptr, nullptr};
WINDOW* myinitscr() {
cursesout = FILE_ptr(std::fopen("/dev/tty", "w"), &std::fclose);
if(cursesout) newterm(std::getenv("TERM"), cursesout.get(), stdin);
return stdscr;
}
A version not taking the address of a standard library function (which is strictly prohibited) could look like this:
#include <cstdio>
#include <cstdlib>
#include <memory>
using FILE_ptr = std::unique_ptr<FILE, void (*)(FILE*)>;
FILE_ptr cursesout{nullptr, nullptr};
WINDOW* myinitscr() {
cursesout = FILE_ptr(std::fopen("/dev/tty", "w"), [](FILE* fp) {
std::fclose(fp);
});
if(cursesout) newterm(std::getenv("TERM"), cursesout.get(), stdin);
return stdscr;
}
|
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 (example 1):
int[] arr = new int[64 * 1024 * 1024];
// Loop 1
for (int i = 0; i < arr.Length; i++) arr[i] *= 3;
// Loop 2
for (int i = 0; i < arr.Length; i += 16) arr[i] *= 3;
Note the factor 16 in the second loop, as ints are 4 bytes long in my machine ( Intel i5), every element in the second loop will be in a different cache line, so theoretically and according to the author, these two loops will take almost the same time to execute, because the speed here is governed by the memory access, not by the integer multiplication instruction.
So I've tried to reproduce this behavior, with two different compilers, MSVC 19.31.31105.0 and GNU g++ 9.4.0 and the result is the the same on both cases, the second loop takes about 4% of the time with respect to the first loop. Here is the implementation I've used to reproduce it
#include <cstdlib>
#include <chrono>
#include <vector>
#include <string>
#define SIZE 64 * 1024 * 1024
#define K 16
//Comment this to use C array instead of std vector
//#define USE_C_ARRAY
int main() {
#if defined(USE_C_ARRAY)
int* arr = new int[SIZE];
std::cout << "Testing with C style array\n";
#else
std::vector<int> arr(SIZE);
std::cout << "Using std::vector\n";
#endif
std::cout << "Step: " << K << " Elements \n";
std::cout << "Array Elements: " << SIZE << "\n";
std::cout << "Array Size: " << SIZE/(1024*1024) << " MBs \n";
std::cout << "Int Size: " << sizeof(int) << "\n";
auto show_duration = [&](auto title, auto duration){
std::cout << "[" << title << "] Duration: " <<
std::chrono::duration_cast<std::chrono::milliseconds>(duration).count() <<
" (milisecs) \n";
};
auto start = std::chrono::steady_clock::now();
// Loop 1
for (int i = 0; i < SIZE; i++) arr[i]++;
show_duration("FullArray",
(std::chrono::steady_clock::now() - start));
start = std::chrono::steady_clock::now();
// Loop 1
for (int i = 0; i < SIZE; i += K) arr[i]++;
show_duration(std::string("Array Step ") + std::to_string(K),
(std::chrono::steady_clock::now() - start));
#if defined(USE_C_ARRAY)
delete[] arr;
#endif
return EXIT_SUCCESS;
}
To compile it with g++:
g++ -o for_cache_demo for_cache_demo.cpp -std=c++17 -g3
Note 1: I'm using -g3 to explicitly show that I'm avoiding any compiler optimization just to see the raw behavior.
Note 2: The difference in the assembly code generated for the two loops is the second argument of the loop counter add function, which adds 1 or K to i
add DWORD PTR [rbp-4], 16 # When using a 16 Step
Link to test in in Compiler Explorer: https://godbolt.org/z/eqWdce35z
It will be great if you have any suggestions or ideas about what I might be missing, thank you very much in advance!
| 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
[FullArray] Duration: 105 (milisecs)
[Array Step 16] Duration: 23 (milisecs)
If I use an optimization, even the most conservative optimization flag, -O1, suddenly the result changes:
$ g++ -O1 cache.cpp -o cache
$ ./cache
Using std::vector
Step: 16 Elements
Array Elements: 67108864
Array Size: 64 MBs
Int Size: 4
[FullArray] Duration: 26 (milisecs)
[Array Step 16] Duration: 22 (milisecs)
(you can see that run time of step 16 has not changes much, because it was already bottlenecked by memory access, while run time of step 1 access improved dramatically, since it was limited by executing instructions, not memory bandwidth)
Further raising optimization levels did not change results for me.
You can compare the inner loops for different optimization levels. With -O0:
vector_step_1(std::vector<int, std::allocator<int> >&):
push rbp
mov rbp, rsp
sub rsp, 32
mov QWORD PTR [rbp-24], rdi
mov DWORD PTR [rbp-4], 0
.L7:
cmp DWORD PTR [rbp-4], 67108863
jg .L8
mov eax, DWORD PTR [rbp-4]
movsx rdx, eax
mov rax, QWORD PTR [rbp-24]
mov rsi, rdx
mov rdi, rax
call std::vector<int, std::allocator<int> >::operator[](unsigned long)
mov rdx, rax
mov ecx, DWORD PTR [rdx]
mov eax, ecx
add eax, eax
add eax, ecx
mov DWORD PTR [rdx], eax
add DWORD PTR [rbp-4], 1
jmp .L7
.L8:
nop
leave
ret
You can see it makes a whole function call on every iteration.
With -O1:
vector_step_1(std::vector<int, std::allocator<int> >&):
mov eax, 0
.L5:
mov rdx, rax
add rdx, QWORD PTR [rdi]
mov ecx, DWORD PTR [rdx]
lea ecx, [rcx+rcx*2]
mov DWORD PTR [rdx], ecx
add rax, 4
cmp rax, 268435456
jne .L5
ret
Now, there are just 8 instructions in the loop. At -O2 it becomes 6 instructions per loop.
|
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 pool_type : pool_type_impl<T> {
// ...
};
|
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 parameter list, member initializer list, attribute list, etc. The following is the list of all allowed contexts:
Base specifiers and member initializer lists:
A pack expansion may designate the list of base classes in a class declaration.
Example
struct Person
{
Person() = default;
Person(const Person&)
{
std::cout<<"copy constrcutor person called"<<std::endl;
}
};
struct Name
{
Name() = default;
Name(const Name&)
{
std::cout<<"copy constructor Name called"<<std::endl;
}
};
template<class... Mixins>
//---------------vvvvvvvvv---------->used as list of base classes from which X inherits publicly
class X : public Mixins...
{
public:
//-------------------------------vvvvvvvvvvvvvvvvv---->used as member initializer list
X(const Mixins&... mixins) : Mixins(mixins)... {}
};
int main()
{
Person p;
Name n;
X<Person, Name> x(p, n); //or even just X x(p, n); works with C++17 due to CTAD
return 0;
}
The output of the above program can be seen here:
copy constrcutor person called
copy constructor Name called
constructor called
Explanation
In the above code, the X class template uses a pack expansion to take each of the supplied mixins and expand it into a public base class. In other words, we get a list of base classes from which X inherits publicly. Moreover, we also have a X constructor that copy-initializes each of the mixins from supplied constructor arguments.
|
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()
{
this->key = 0;
this->value = 0;
}
Pair(TKey key, TValue value)
{
this->key = key;
this->value = value;
}
};
template <typename TKey, typename TValue>
class Dictionary
{
private:
vector<Pair<TKey, TValue>> pairs;
//...
public:
Pair operator[] (unsigned index)
{
return this->pairs[index];
}
//...
};
The error I'm getting:
deduced class type 'Pair' in function return type
What can I do with that?
| 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<EntryType> pairs;
//...
public:
EntryType operator[] (unsigned index)
{
return this->pairs[index];
}
};
|
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 + 1];
}
return pos;
}
int main()
{
const int N = 4;
int mas[N] = {2, 6, 6, 8};
int pos = sizeof(mas)/sizeof(mas[0]);
int x = 6;
pos = deleteElement(mas, pos, x);
cout << "Modified array is \n";
for (int i = 0; i < pos; i++)
cout << mas[i] << " ";
return 0;
}
The task is to remove all specified elements from array.
In my case x = 6 but it only removes one element that is equal to x:
Array: 2 6 6 8
Output: 2 6 8
What I need to do to make this code remove all elements from array that are equal to x?
Expected output: 2 8
| 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 the function loop when pos changes (though, I don't really recommend this solution, it would work). Like so:
int deleteElement(int mas[], int pos, int x)
{
int prevPos;
do {
prevPos = pos;
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 + 1];
}
} while ( prevPos != pos ); // if the size has changed, loop back to beginning
return pos;
}
Alternatively, you can just keep track of how many items were removed, and shift elements up by that amount, like so:
int deleteElement(int mas[], int pos, int x)
{
int idx;
int offset = 0; // number of elements to shift by
for ( int idx = 0; idx < pos; ++idx ) {
if ( mas[idx] == x ) // found the element
++offset; // so increase the offset
else if ( offset != 0 ) { // doesn't really need the "if" part, but would be more efficient if dealing with objects
mas[idx-offset] = mas[idx]; // move the item up the list
}
}
return pos - offset; // new size is the old size minus number of elements removed
}
|
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 :
while (t--) {
long long hc, dc, hm, dm, w, a;
long k;
scanf("%lld%lld%lld%lld%d%lld%lld", &hc, &dc, &hm, &dm, &k, &w, &a); // ok
// cin >> hc >> dc >> hm >> dm >> k >> w >> a; // cannot work
for (int i = 0; i < k + 1; i++) {
int opt = k - i;
long long hc1 = opt * a + hc;
long long dc1 = i * w + dc;
long long cnt1 = hm / dc1 + (hm % dc1 > 0);
long long cnt2 = hc1 / dm + (hc1 % dm > 0);
if (cnt1 <= cnt2) {
printf("YES\n");
goto nt;
}
}
printf("NO\n");
}
}
I just try a lot of practices , found the key of question is input of question.
| 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 ticket of 10 has been used"
However, I have no idea where to even begin. I'm sorry if this is too vague but any help would be greatly appreciated
I tried to put my numbers into an array but that didn't work unfortunately. I also tried dividing them seperatly but that didn't work either
| 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; // reduce amount
long c10s = ui / 10; // divide
ui -= c10s * 10; // reduce amount
std::cout
<< c50s << " tickets of 50 have been used\n"
<< c20s << " tickets of 20 have been used\n"
<< c10s << " tickets of 10 have been used\n"
<< "you have " << ui << " left\n"
;
} else {
std::cerr << "invalid input\n";
}
}
Example if giving 180 as input:
3 tickets of 50 have been used
1 tickets of 20 have been used
1 tickets of 10 have been used
you have 0 left
If you do this a lot, you could create a helper function:
long div_and_reduce(long& input, long div) {
long result = input / div; // divide
input -= result * div; // reduce
return result;
}
int main() {
std::cout << "enter amount: ";
if(long ui; std::cin >> ui) {
long c50s = div_and_reduce(ui, 50);
long c20s = div_and_reduce(ui, 20);
long c10s = div_and_reduce(ui, 10);
// ...
|
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] == 0)
return 2;
return -1;
//return strlen(sz);
}
constinit int c = test("Hi");
int main() {
printf("C %d\n", c);
}
| 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 char* sz) {
return std::char_traits<char>::length(sz);
}
|
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 typename Args is (that can be treacherous when using e.g. int as it compiles unless you crank up warning levels).
The trick to single out the first argument in the list works for checking all elements are equal:
template <typename Arg, typename... Args>
bool are_all_equal(Arg const& arg0, Args const&... args) {
return ((arg0 == args) && ... );
}
but it won't work here for operator< since it would only test whether all arguments are greater than the first one.
| 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 type, one initialized with the first argument a0
CT c0, c1 = a0;
your fold expression can be
return ((c0 = c1, c0 < (c1 = static_cast<CT>(args))) && ...);
Without isolating the first argument, there is the problem of the inizialization of c1. You can try with std::numeric_limits<CT>::min(), but the code fail if the first value of args... is equal to this value (that isn't improbable when you check unsigned values).
The following is a full compiling example
#include <iostream>
template <typename A0, typename... Args>
constexpr bool are_strictly_increasing(A0 const & a0, Args const&... args)
{
using CT = std::common_type_t<A0, Args...>;
CT c0, c1 = a0;
return ((c0 = c1, c0 < (c1 = static_cast<CT>(args))) && ...);
}
int main()
{
std::cout << are_strictly_increasing(0, 1, 2, 3, 4) << std::endl;
std::cout << are_strictly_increasing(0, short{1}, 2l, 3u, 4ull) << std::endl;
std::cout << are_strictly_increasing(0, 1, 2, 3, 4, 4) << std::endl;
std::cout << are_strictly_increasing(0, 1, 21, 3, 4, 4) << std::endl;
}
|
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) << std::endl; //4
std::cout << *bitand(d, e) << std::endl; //37
int* bit_and = bitand(d, e);
std::cout << *bit_and << std::endl; //37 (should it be 4?)
| 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 discards the first argument, then evaluates and returns the second argument. So (d, e) is the same as e, and your code boils down to &e.
So despite the code saying bitand, there's no bitwise and happening here. It's acting as the unary address-of operator and returning a pointer that points to e. That's why you have to dereference it with unary *, and why the value after dereferencing is 37 not 4.
As an aside, if you're using clang or gcc, if you enable -Wunused (which is included in -Wall), the compiler will issue a warning that you're discarding a value with no effect, like so:
<source>:8:26: warning: left operand of comma operator has no effect [-Wunused-value]
8 | std::cout << *bitand(d, e) << std::endl; //37
|
Which would have given you a heads-up that this wasn't acting like a function invocation but instead something else.
|
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 executed? In other words, is it possible either the write or read task will simply not get done? Will one or both be blocked? Or are they guaranteed to be sequentialized? I am NOT asking here about order of operations. I am asking simply if the operation will be done at some unspecified time in the future.
| 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 same integer variable. This operation typically involves reading the integer, adding 1 and writing the result (notice that this is only an example, the C++ standard does not say anything about how operations are broken into atomic steps and thus we cannot make any assumptions about it based on the standard).
In this case we would have the steps "read", "add one" and "write". For each thread, these steps are guaranteed to the executed in that order, but there is no guarantee how the steps are interleaved. It may be:
B: read
B: add1
B: write
A: read
A: add1
A: write
which results in the integer being incremented twice.
It could also be
A: read
A: add1
B: read
B: add1
B: write
A: write
which would result in the integer being incremented only once.
Thus this implementation would have a race condition.
To get rid of that we can use a std::atomic<int> instead of a plain int for the integer. std::atomic<int> implements the ++ operator and the guarantee which std::atomic<> provides is that incrementing in this case will happen atomically.
In the example, this means that the sequence of steps - read, add one, write - will not be interrupted by another thread. There is still no guarantee about the order of execution between the threads. Hence, we could have
A: read
A: add1
A: write
B: read
B: add1
B: write
or
B: read
B: add1
B: write
A: read
A: add1
A: write
but other combinations will not be possible and in both cases the integer will be incremented twice. Thus there is no race condition.
|
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, i2;
i1 * i2;
}
It's compiled successfully by gcc, but failed by MSVC and clang, with error overloaded operator '*' is ambiguous. The problem comes from the explicit deleted operator bool.
https://godbolt.org/z/nh6M11d98
Which side (gcc or clang/MSVC) is right? And why?
| 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 candidate built-in overloads for the * operator for all pairs of promoted arithmetic types.
So, instead of using * we could also consider
auto mul(int a, int b) { return a*b; } // (1)
auto mul(long a, long b) { return a*b; } // (2)
// further overloads, also with non-matching parameter types
mul(i1, i2);
Notably there are no overloads including bool, since bool is promoted to int.
For (1) the chosen conversion function for both arguments is operator int() const instantiated from operator Integral() const since conversion from int to int is better than bool to int. (Or at least that seems to be the intent, see e.g. https://github.com/cplusplus/draft/issues/2288 and In overload resolution, does selection of a function that uses the ambiguous conversion sequence necessarily result in the call being ill-formed?).
For (2) however, neither conversion from int or bool to long is better than the other. As a result the implicit conversion sequences will for the purpose of overload resolution be the ambiguous conversion sequence. This conversion sequence is considered distinct from all other user-defined conversion sequences.
When then comparing which of the overloads is the better one, neither can be considered better than the other, because both use user-defined conversion sequences for both parameters, but the used conversion sequences are not comparable.
As a result overload resolution should fail. If I completed the list of built-in operator overloads I started above, nothing would change. The same logic applies to all of them.
So MSVC and Clang are correct to reject and GCC is wrong to accept. Interestingly with the explicit example of functions I gave above GCC does reject as expected.
To disallow implicit conversions to bool you could use a constrained conversion function template, which will not allow for another standard conversion sequence after the user-defined conversion:
template<std::same_as<int> T>
operator T() const { return _value; }
This will allow only conversions to int. If you can't use C++20, you will need to replace the concept with SFINAE via std::enable_if.
|
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 why does only the 2nd case update the outer map correctly? Do cases 1 and 3 get the value of the inner map instead of a reference to it?
#include <iostream>
#include<map>
using namespace std;
int main()
{
map<int, map<string, int>> m1;
map<int, map<string, int>> m2;
map<int, map<string, int>> m3;
auto inner = m1[500];
inner["text"] = 10;
map<string, int> *ptr = &m2[500];
(*ptr)["text"] = 20;
map<string, int> inner3 = m3[500];
inner3["text"] = 30;
cout << "inner " << inner["text"] << " map " << m1[500]["text"] << endl;
cout << "ptr " << (*ptr)["text"] << " map " << m2[500]["text"] << endl;
cout << "inner3 " << inner3["text"] << " map " << m3[500]["text"] << endl;
return 0;
}
This prints out the following:
inner 10 map 0
ptr 20 map 20
inner3 30 map 0
I would expect all 3 to print non-0 values, but only the 2nd case does.
| 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<string, int>& inner3 = m3[500];
|
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 clearly achievable for the header files (as described below by adding the directory to the settings, is this not the same for source files?
-- Original Question --
I'm working on replicating a project from CPython into C++ as a challenge to learn more C++ but I can't seem to get the environment established so that I can compile a test run. When I build the solution, it throws a LNK2019 which I know has something to do with the Linker unable to locate the symbols. I have read through numerous solutions on SO that say to updated the properties with the directories of the files, but they do not resolve the issue.
The issues currently stand at:
Some of the headers from other directories show in the explorer, but some do not, why?
The source files are not found and therefore LNK2019 is thrown, cannot resolve, how to?
Here is the layout of my project:
/root
/proj-cmd
/src/main/cpp
/proj/cmd
-> main.cpp
/proj-core
/src/main/cpp/
/proj/cmd
-> command.h
-> base_command.h
-> base_command.cpp
/proj/utils
-> settings.h
-> settings.cpp
The content of main.cpp for testing of environment:
// astro
#include <astro/core/util/settings.h>
// stdlib
#include <exception>
#include <string>
#include <iostream>
using namespace std;
// astro entry point
int
main(int argc, char *argv[])
{
if (conf().hasKey("APP_CWD"))
{
cout << "APP_CWD is: " << conf().getKey("APP_CWD") << endl;
}
else
{
cout << "APP_CWD was not found" << endl;
}
}
In order for #include <astro/core/util/settings.h> to work, I updated the include directories in the properties:
However, in the explorer only command.h and settings.h are shown, not base_command.h:
Additionally, the base_command.cpp and settings.cpp do not display in the source files either, so I updated (similar to the include directories) the source directories:
That takes care of the first issue I am noticing, but now onto LNK2019. I believe this is a related result of the former problem, in that the source files are unknown:
So following many other SO posts, I tried to update the Linker settings without success:
I'm not very familiar with the Visual Studio 2017 environment, so if somebody could provide input as to how to configure these settings so that I can compile I'd appreciate this.
| 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 is why you are getting linker errors: the code in settings.cpp and base_command.cpp are never getting built.
See Microsoft Docs
|
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 of the main() function below (or see on https://godbolt.org/z/Y8G47h4GK).
#include <tuple>
#include <iostream>
template<typename... Ts> struct pack { };
template <class> struct pack_helper;
template <class R, class... Args>
struct pack_helper<R(Args...)> {
using args = pack<Args...>;
};
template <class R, class... Args>
struct pack_helper<R(*)(Args...)> {
using args = pack<Args...>;
};
template <class F, class = typename pack_helper<F>::args>
class memoize;
template <class F, class... Args>
class memoize<F, pack<Args...>>
{
public:
using result_type = std::invoke_result_t<F, Args...>;
memoize(F &&f) : _f(std::forward<F>(f)) {}
result_type operator()(Args... args) { return _f(args...); }
private:
F _f;
};
int test(int x) { return x + 1; }
int main() {
auto test_mem = memoize<decltype(&test)>(&test);
std::cout << test_mem(2) << '\n';
auto l = [](int x) -> int { return x + 1; };
// auto l_mem = memoize<?>(?);
}
| 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(Type::*) (Args...));
template<class Result, class Type, class ...Args>
pack<Args...> lambda_pack_helper(Result(Type::*) (Args...) const);
// helper functions: if called with an instance of the first parameter type of memorize, the return type is the one used as the second one
// overload for function
template<class Result, class ...Args>
pack<Args...> pack_helper(Result(Args...));
// overload for function pointer
template<class Result, class ...Args>
pack<Args...> pack_helper(Result (*)(Args...));
// sfinae will prevent this overload from being considered for anything not providing an operator()
// for those types we use the return type of helper function lambda_pack_helper
template<class T>
decltype(lambda_pack_helper(&T::operator())) pack_helper(T);
template <class F, class = decltype(pack_helper(std::declval<F>()))>
class memoize;
template <class F, class... Args>
class memoize<F, pack<Args...>>
{
public:
using result_type = std::invoke_result_t<F, Args...>;
memoize(F&& f) : _f(std::move(f)) {}
memoize(F const& f) : _f(f) {}
result_type operator()(Args... args) { return _f(args...); }
private:
F _f;
};
int test(int x) { return x + 1; }
int main() {
auto test_mem = memoize<decltype(&test)>(&test);
std::cout << test_mem(2) << '\n';
auto l = [](int x) -> int { return x + 1; };
auto l_mem = memoize<decltype(l)>(l);
std::cout << l_mem(3) << '\n';
}
|
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 <iostream>
#include <vector>
#include <memory>
using namespace std;
class Entity {
public:
int index;
Entity() {};
virtual ~Entity() {};
virtual void hit() = 0;
};
class Mesh : public Entity {
public:
int index;
Mesh(int x) {this->index=x;};
virtual void hit() {}
};
int main() {
vector<unique_ptr<Entity>> objects;
objects.push_back(unique_ptr<Entity>(new Mesh(35)));
objects.push_back(unique_ptr<Entity>(new Mesh(10)));
for ( int i = 0 ; i < objects.size() ; i++ )
cout << objects[i]->index << endl;
return 0;
}
Where I expect
35
10
to be printed, meanwhile I get instead.
0
0
How can I access the correct member variable values in this scenario?
| 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 {} // extraa safety: use override instead of virtual to be sure to override
};
Online demo
Not related to the problem, but some more thoughts:
You can of course only use the interface of the base class (here Entity).
It is not very prudent to expose the index member publicly. A safer option would be to have it private, and access it via a public getter. If the index should be set only at construction, the Entity constructor should take care of it, otherwise you could consider a public setter.
|
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 pseudo;
int healthValue = 100;
int attackValue = 5;
Player(std::string aPseudo) {
pseudo = aPseudo;
healthValue = healthValue;
attackValue = attackValue;
}
std::string getPseudo() {
return pseudo;
}
int getHealthValue() {
return healthValue;
}
int getAttackValue() {
return attackValue;
}
void attack(Player aTargetPlayer) {
aTargetPlayer.healthValue -= this->attackValue;
}
};
MAIN.CPP
#include "Player.cpp"
int main() {
Player player1("player1");
Player player2("player2");
std::cout << player2.getHealthValue() << std::endl;
player1.attack(player2);
std::cout << player2.getHealthValue() << std::endl;
return 0;
}
| 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 -= this->attackValue;
}
|
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 reachable through the resulting pointer to x2[0]
// but is not reachable from the source
| 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 object Y if those bytes are within the storage of an object Z that is pointer-interconvertible with Y, or within the immediately enclosing array of which Z is an element)
x2 is an array of 2 arrays of 10 arrays of int. Let's suppose we call the two arrays a and b.
&x2[0][0] is an int* pointing to the first element of a.
&x2[0][0] + 10 is an int* pointer one-past the last element a. The address of this pointer value is also the address at which b begins. However one cannot obtain a pointer to b or one of its elements via reinterpret_cast since &x2[0][0] + 10 doesn't point to any object that is pointer-interconvertible with b or one of its elements.
In terms of the technical definition, the only object pointer-interconvertible with the first element of a is the object itself. Therefore the reachable bytes from a pointer to the first element of a are only the bytes of a, which is the array immediately enclosing this object.
Therefore the reachable bytes through &x2[0][0] are only those of the array a, not including b. E.g. *(&x2[0][0] + 10) = 123; has undefined behavior.
However if std::launder were to return a pointer to a (of type int(*)[10]), then (p2+1)[i] would be a way to access all elements of b. Or in terms of the technical definition, the array immediately enclosing the object p2 points to would be x2, so that all bytes of x2 are reachable.
This means after the std::launder bytes that weren't reachable before would become reachable. Therefore the call has undefined behavior.
|
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;
float Zpos;
cVector(float x, float y, float z);
void Print();
float Length();
cVector Negation();
cVector Normalisation();
};
#endif
and in the source file (.cpp) i have tried to define
#include<iostream>
#include<math.h>
#include "cVector.h"
#include <float.h>
int main()
{
cVector(float x, float y, float z) { // Constructor with parameters
Xpos = x;
Ypos = y;
Zpos = z;
};
}
Yet i get the error that float x is not a valid type name, what is the error?
i wanted the implementation to define the cVector input to the variables Xpos ,Ypos , Zpos
| 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<UStaticMeshComponent>(TEXT("StaticMesh"));
if (StaticMeshCompt)
{
// further work with the component
}
| 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 point,
you've got other problems).
|
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 ) {
write( f, p.first );
write( f, p.second );
}
template< ranges::range T >
void write( fstream & f, const T & data ) {
const uint64_t size = ranges::size( data );
write( f, size );
for ( const auto & i : data )
write( f, i );
}
int main() {
auto f = fstream( "spagetti", ios::out | ios::binary );
const bool pls_compile = true;
if constexpr (pls_compile) {
write( f, pair< int, int >( 123, 777 ) );
write( f, map< int, int >{ { 1, 99 }, { 2, 98 } } );
}
else
write( f, pair< map< int, int >, int >( { { 1, 99 }, { 2, 98 } }, 777 ) );
}
which made me a happy developer of serialization library which provides functions to serialize to file anything that is integral || pair || range. But it turned out that if you set pls_compile = false, then compilation fails with spagetti.cpp:12:10: error: no matching function for call to 'write(std::fstream&, const std::map<int, int>&)'. It can't be fixed by moving declaration of write( pair ) past write( range ) because pls_compile = true will stop compiling then.
What is the best way to fix it and why compiler forgets about existence of write( range ) while generating implementation of write( pair< map, int > ) based on write( pair ) template? It clearly should be already familiar with write( range ) since it already proceeded down to write( pair< map, int > ).
| 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 instatiation of a template defined before the declation but triggered by a use of a template afterwards, as you have here.)
The easiest fix is to just forward declare your templates/functions. You can't go wrong forward declaring everything at the top of the file:
void write( fstream & f, const integral auto & data );
void write( fstream & f, const pair<auto,auto> & p );
template< ranges::range T >
void write( fstream & f, const T & data );
|
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 implicitly-deleted copy constructor of 'std::unique_ptr<int>'
::new ((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
[...]
note: in instantiation of member function 'std::vector<std::unique_ptr<int>>::vector' requested here
const std::vector<std::unique_ptr<int>> bar(foo);
^
../include/c++/v1/__memory/unique_ptr.h:215:3: note: copy constructor is implicitly deleted because 'unique_ptr<int>' has a user-declared move constructor
unique_ptr(unique_ptr&& __u) _NOEXCEPT
I assume that this situation is because the std::vector<T> implementation doesn't use SFINAE to disable the copy constructor when T isn't copy-constructible. But why not? Is there something in the standard that says it must work this way? It's unfortunate because it means my own SFINAE around copy-constructibility doesn't do the right thing around vectors.
| 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_constructible_v on the container will always be true. There is no way to test whether an instantiation of a definition would be well-formed with a type trait.
It would be possible to specify that the copy constructor is not declared or excluded from overload resolution if the element type is not copyable. However, that would come with a trade-off which is explained in detail in this blog post: https://quuxplusone.github.io/blog/2020/02/05/vector-is-copyable-except-when-its-not/.
In short, if we want to be able to use the container with an incomplete type, e.g. recursively like
struct X {
std::vector<X> x;
};
then we cannot determine whether X is copyable when the container class is instantiated. Therefore the declaration of the copy constructor cannot be made dependent on this property.
Since C++17 the standard requires std::vector, std::list and std::forward_list, but not the other containers, to work like this with incomplete types.
|
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 --form "fileupload=@file1.txt" -X POST http://127.0.0.1:8000/
I noticed that the variable body__, which gets populated with the text of the file also gets populated with header data. I do not want this. How do I populate the variable body__ without any header data?
This is what it looks like:
| 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 with --data-binary, --data, --form.
Unfortunately curl does not send a file name. If a file name is required on a server side, specify the header Content-Disposition:
curl --data-binary "@file1.txt" -H "Content-Type: application/octet-stream" -H "Content-Disposition: attachment; filename=file1.txt" http://127.0.0.1:8000/
KB
--data-binary
-F, --form
|
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 appended as an empty string, but the debugger shows the instance of that student class (the "Alumno" class) has actually a name.
i'll leave you the code below,
class libroDeClases {
public:
vector<string> nombres;
vector<float> notasDef;
};
class Alumno {
private:
string nombre;
float n1, n2, n3;
float notaDef;
public:
Alumno(string nombre, float x, float y, float z) {
nombre = nombre;
n1 = x;
n2 = y;
n3 = z; }
void calcularNota(libroDeClases L) {
float nd = (n1 + n2 + n3) / 3;
notaDef = nd;
L.notasDef.push_back(nd);
L.nombres.push_back(nombre);
}
int main() {
libroDeClases Libro;
Alumno a1("Oscar", 4.0, 4.7, 5.5);
a1.calcularNota(Libro);
thank you for your help!
Edit: i added the "Libro" class in order to make the code compile, i forgot to provide it sorry about that.
| 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::endl;
}
else
{
std::cout<<"equal"<<std::endl;
}
Demo
Other alternative is to do the opposite. That is, convert the std::string to int(if possible) and then perform the comparison.
|
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
private:
string diskname; //file name of software-disk
int numberofblocks; //number of blocks on disk
int blocksize; //block size in bytes
};
class Filesys: public Sdisk
{
public:
Filesys(string disk_name, int number_of_blocks, int block_size);
Filesys(); //default constructor
};
My constructor for Fileys is calling getblock from the Sdisk class and returns the correct value, but my string buffer does not change
Filesys::Filesys(string disk_name, int number_of_blocks, int block_size) {
string buffer;
int code = getblock(0, buffer);
if (code == 0) { //passes this so it is calling the function and returning a value
cout << "Failed";
}
cout << buffer; //empty, buffer is not being changed by getblock
}
//returns the blocknumber called for and passes it by ref in buffer
int Sdisk::getblock(int blocknumber, string &buffer){
ifstream file(diskname);
int i = (blocknumber -1) * blocksize;
int j = (blocknumber * blocksize) -1;
int k = 0;
char b;
if (j > (blocksize * numberofblocks)) {
file.close();
return 0;
}
while (file >> noskipws >> b) {
if ((k > i-1) && (k < j+1)) {
buffer.push_back(b);
}
k++;
}
file.close();
return 1;
}
This function works when it is called normally like
Sdisk disk1("test1",16,32);
string block3;
disk1.getblock(4, block3);
cout << block3; //correctly outputs what is being asked
Why might this be happening?
| 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, and they are needed for Sdisk::getblock to run 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 << "I am Base\n"; }
};
class Derived_A : public Base {
public:
void who() { cout << "I am Derived_A\n"; }
};
class Derived_B : public Base {
public:
virtual void who() override { cout << "I am Derived_B\n"; }
};
int main()
{
Base b;
b.Print(); //-> return "I am Base"
Base* ptr = new Derived_A();
ptr->Print(); // was expecting "I am Base" instead returns "I am Derived_A"
Base* ptr1 = new Derived_B();
ptr1->Print(); // expecting "I am Derived_B" and surely returns "I am Derived_B"
return 0;
}
| 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.
Example:
class Base {
public:
virtual void foo(int) {}
};
class Derived : public Base {
public:
void foo(double) override {} // compilation error
};
|
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 execution context and back again onto a coroutine thread of execution. Think asynchronous i/o wrappers if you must. Consider the non-trivial state machine required to do thread-safe asynchronous time-outs, completion callbacks, teardown, and dispatching back to the original coroutine thread of execution without leaking.)
template <typename T>
concept IoCoServiceImplementation = requires(
T t,
typename T::return_type x,
CoServiceCallback<typename T::return_type> *callback)
{
{t.Execute(callback)} -> std::same_as<void>;
{t.Cancel(callback)} -> std::same_as<bool>;
};
template <IoCoServiceImplementation SERVICE_IMPLEMENTATION>
class CoServiceAwaitable {
...
};
What I want concisely: IoCoServiceImplementation must provide two methods:
class AnImplementation {
public:
using return_type = RETURN_TYPE;
void Execute(CoServiceCallback<return_type>*);
bool Cancel(CoServiceCallback<return_type>*);
}
Note the significant difference in readability of the concept and the example. Also worth noting is that the generated error message doesn't supply the actual types required. You would have to browse the source of the concept declaration to figure out what callback means when you get error blahblah requires {t.Execute(callback)}.
While I can think of a dozen ways to hack a concept that requires the methods I want, none of them seem sufficiently readable and self-documenting. And the more I hack, the less readable the declarations, and error messages get.
I'm thinking about exploring whether std::function<> can be hacked to produce a readable and self-documenting declarations. Something like:
{ std::function< void T::Execute(CoServiceCallback<return_type>*) > };
{ std::function< bool T::Cancel(CoServiceCallback<return_type>*) > };
(which doesn't actually work, obvsly).
Is there a better way to do this? Has anyone delivered style guidelines for concepts yet?
--
Proactively, because I'm sure this will come up...
You could quibble about whether it should be std::same_as<bool> or std::convertable_to<bool>. Here's my thinking on that. I expect a bool. If that method returns anything other than bool, I can't imagine what it would it be. So it's reasonable to insist that it not be something I don't expect.
A frequent argument defending the deficiencies of the current C++ concept implementation: that concepts are supposed to enforce what you can do, not the precise implementation. In this case, I don't really care what you can do; I'm concerned with letting you know what you do do.
| 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_type>* callback) {
{ t.Execute(callback) } -> std::same_as<void>;
{ t.Cancel(callback) } -> std::same_as<bool>;
};
I'm thinking about exploring whether std::function<> can be hacked to
produce a readable and self-documenting declarations.
This is not a good idea, first of all, you need to include extra (and unnecessary) headers, and it's not as intuitive as compound requirements with return-type-requirement.
|
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'); // ok
auto c2 = f2('A'); // error
return c1 + c2;
}
Compiled with: clang++-14 -std=c++20 -stdlib=libc++, and the error message is:
undefined reference to `operator"" _UC(unsigned long long)'
See online demo
Why does f1() is ok while f2() is not?
Why does consteval not behave as expected?
| 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);
int n = 0;
do {
n = a.find('a',1);
cout << n;
a.erase(n, 0);
cout << a;
} while (n != -1);
cout << a;
}
I tried to change int to double, but the program does not work correctly. However, the error disappears
| 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 then n is equal to std::string::npos and you are using this value in the call of erase. You need to check that n is not equal to std::string::npos before calling the member function erase.
And the call of erase in any case is incorrect.
Instead of the do-while loop it is better to use the for loop. For example
for ( std::string::size_type n; ( n = a.find( 'a' ) ) != std::string::npos; )
{
std::cout << n;
a.erase(n, 1 );
std::cout << a << '\n';
}
Also you should declare the variable n as having the type std::string::size_type.
And as @Ted Lyngmo wrote in a comment if your compiler supports C++ 20 then you can use standard C++ function erase defined for standard containers like
std::erase( a, 'a' );
to remove all occurrences of the letter 'a' in the string.
|
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 specific problem. Thank you, leon4aka
void chip8c::loadSoftware(char* filepath)
{
FILE* fptr = NULL;
u32 fsize;
fptr = fopen(filepath, "rb"); // reading in binary mode
if(fptr == NULL)
printf("Error: invalid filepath");
fseek(fptr, 0, SEEK_END);
fsize = ftell(fptr); // getting file size
fseek(fptr, 0, SEEK_SET);
for(int i = 0; i < fsize; i++)
memory[i] = fptr[i]; // ! Does not work !
fclose(fptr);
}
I tried copying the content of the file with a for-loop like shown above but it didn't work.
| 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 std::decay<U>::type, Foo>::value>::type>
Foo(U&&) {
}
};
int main() {
Foo<int> ff;
Foo<char> dd(ff); //here I want a compiler error
Foo<int> e(15); //it should work
return 0;
}
I'm trying to add constraints about template constructor, however this code compiles so I think I'm missing something, what's the proper way to add the enable_if?
| 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 (templated) constructors from pre-decay types. If your argument too one of the copy or move constructors (from const Foo& and Foo&& respectively) decays into a Foo, then those ctors should be enough. And if they somehow aren't, this implicit conversion that you're allowing for is probably more trouble than it's worth. It will certainly make your class more difficult to read and to adapt. You have, in fact, already seen it has led you to a minor bug :-P
|
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 operator()(const any &data) const = 0;
};
class Func1 : public FunctionBase {
private:
int a,b;
public:
Func1(const MapAny ¶m_map) {
a = any_cast<int>(param_map.at("a"));
b = any_cast<int>(param_map.at("b"));
}
virtual any operator()(const any &data) const override {
// calculate some F1(data, a, b)
return a + b;
}
};
class Func2 : public FunctionBase {
private:
float c,d;
public:
Func2(const MapAny ¶m_map) {
c = any_cast<float>(param_map.at("c"));
d = any_cast<float>(param_map.at("d"));
}
virtual any operator()(const any &data) const override {
// calculate some F2(data, a, b)
return c * d;
}
};
FunctionBase* functionFactory(string name, const MapAny ¶m_map)
{
if (name=="func1") return new Func1(param_map);
if (name=="func2") return new Func2(param_map);
return nullptr;
}
int main()
{
// map<string, ???> functionMapping;
// functionMapping["func1"] = ...
// functionMapping["func2"] = ...
vector<float> data;
MapAny param_map1;
param_map1["a"] = 3;
param_map1["b"] = 5;
FunctionBase* func1 = functionFactory("func1", param_map1); //functionMapping["func1"](param_map1);
assert(any_cast<int>(func1->operator()(data))==8);
MapAny param_map2;
param_map2["c"] = 2.0f;
param_map2["d"] = 4.0f;
FunctionBase* func2 = functionFactory("func2", param_map2); //functionMapping["func2"](param_map2);
assert(any_cast<float>(func2->operator()(data))==8.0);
cout << "Correct\n";
}
I'm trying to make a Python-like C++ library, where user will give a map of string and parameters. The code will parse the map to functions, then execute the functions. Most importantly, I need to be able to write:
std::any param_map; // = something, doesn't matter here
FunctionBase *myfunc = new functionMapping["myfunc"](param_map);
Given the code in the example, what should be the value type of
map<string, ???> functionMapping;
Edit: added an equivalent solution using ugly if-statement
| 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 ----------------------------------------------------------------------------------
struct Base {
Base(int d) : data(d) {};
virtual ~Base() { std::cout << "Destructor Base\n"; }
virtual void print() { std::cout << "Print Base\n"; }
int data{};
};
struct Child1 : public Base {
Child1(int d, std::string s) : Base(d) { std::cout << "Constructor Child1 " << d << " " << s << "\n"; }
virtual ~Child1() { std::cout << "Destructor Child1\n"; }
virtual void print() { std::cout << "Print Child1: " << data << "\n"; }
};
struct Child2 : public Base {
Child2(int d, char c, long l) : Base(d) { std::cout << "Constructor Child2 " << d << " " << c << " " << l << "\n"; }
virtual ~Child2() { std::cout << "Destructor Child2\n"; }
virtual void print() { std::cout << "Print Child2: " << data << "\n"; }
};
struct Child3 : public Base {
Child3(int d, long l, char c, std::string s) : Base(d) { std::cout << "Constructor Child3 " << d << " " << l << " " << c << " " << s << "\n"; }
virtual ~Child3() { std::cout << "Destructor Child3\n"; }
virtual void print() { std::cout << "Print Child3: " << data << "\n"; }
};
using UPTRB = std::unique_ptr<Base>;
template <class Child, typename ...Args>
UPTRB createClass(Args...args) { return std::make_unique<Child>(args...); }
// The Factory ----------------------------------------------------------------------------------------
template <class Key, class Object>
class Factory
{
std::map<Key, std::any> selector;
public:
Factory() : selector() {}
Factory(std::initializer_list<std::pair<const Key, std::any>> il) : selector(il) {}
template<typename Function>
void add(Key key, Function&& someFunction) { selector[key] = std::any(someFunction); };
template <typename ... Args>
Object create(Key key, Args ... args) {
if (selector.find(key) != selector.end()) {
return std::any_cast<std::add_pointer_t<Object(Args ...)>>(selector[key])(args...);
}
else return nullptr;
}
};
int main()
{
// Define the factory with an initializer list
Factory<int, UPTRB> factory{
{1, createClass<Child1, int, std::string>},
{2, createClass<Child2, int, char, long>}
};
// Add a new entry for the factory
factory.add(3, createClass<Child3, int, long, char, std::string>);
// Some test values
std::string s1(" Hello1 "); std::string s3(" Hello3 ");
int i = 1; const int ci = 1; int& ri = i; const int& cri = i; int&& rri = 1;
UPTRB b1 = factory.create(1, 1, s1);
UPTRB b2 = factory.create(2, 2, '2', 2L);
UPTRB b3 = factory.create(3, 3, 3L, '3', s3);
b1->print();
b2->print();
b3->print();
b1 = factory.create(2, 4, '4', 4L);
b1->print();
return 0;
}
|
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 a w!" << endl;
}
}
}
It returns this error:
so.cpp:10:25: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
10 | if(s[i] == "w")
| "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 (x1 == (b)) {
xx1=5;
}
N.B. When it asks you which position would you like it add your X, I am typing "a".
I expected xx1's value to change to 5 but instead of 5 it was 0.
Edit: I was using the "=" operator instead of the "==" operator. I ran the code and it worked, though now, a couple minutes later, it isn't working. I don't know what I did to make this happen, because the only thing that I did was setting it up for other letters.
| 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 to apply Fit-in feature. ( so that, in Undo-Redo I can use that stored position)
But I do not know how to store current position of view in a variable. I tried this way :
void myClass::FitIn()
{
QTransform t = _view->transform();
QScrollBar* hrSBar = _view->horizontalScrollBar();
QScrollBar* verSBar = _view->verticalScrollBar();
myCommand* c = new myCommand(t,hrSBar,verSBar);
undoStack->push(c);
_view->resetTransform();
}
How to store, current view in another variable ?
***** EDIT ******
myCommand.cpp
myCommand::myCommand(QTransform t, QScrollBar *hr, QScrollBar *vr)
{
this->trans = t;
this->horizontalSBar = hr;
this->verticalSBar = vr;
}
void myCommand::undo()
{
_mView->setTransform(trans);
_mView->horizontalScrollBar()->setValue(horizontalSBar->maximum());
_mView->verticalScrollBar()->setValue(verticalSBar->maximum());
}
void myCommand::redo()
{
_mView->setTransform(trans); // Segmentation Fault occurs
_mView->horizontalScrollBar()->setValue(horizontalSBar->maximum());
_mView->verticalScrollBar()->setValue(verticalSBar->maximum());
}
myCommand.h
class myCommand: public QUndoCommand
{
public:
myCommand(QTransform t, QScrollBar* hr, QScrollBar* vr);
private:
QGraphicsScene* _mScene;
QGraphicsView* _mView;
}
| 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 be stored before every operation an restored upon undo.
|
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 I'm calling that from another GUI app built from gtkmm (c++). It does create black console along with GUI window.
This symptom doesn't occur when I tried calling the same mentioned Avalonia app with another cross-platform Avalonia app. It doesn't create any console, only the GUI window as intended. (Using System.Diagnostics.Process from .NET C#).
So maybe there is some detail behind that make these api behave differently? (boost::process / System.Diagnostics.Process)
Basically I'm looking for the api to do the same thing with System.Diagnostics.Process (C#) on c++
| 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 don't do it asynchonously
(If that second GUI window is initialized with black background, like the one created with AvaloniaUI, you may confuse it as another console :p)
|
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 research we found that since spdlog is a header-only library it may cause issues when using it this way, so we changed to using it as a static library inside the native library.
This seems to solve the issue but now we get the SIGSEGV on the first call to spdlog from the application's native code.
Are there any limitations or issues with using spdlog this way, specifically in an Android project?
Any suggestions on debugging the issue?
If any code can be helpful, let me know what is needed and I'll update the question
Edit
Also, it's worth noting that it only happens when the native library is built in Release mode. In Debug everything works as expected
| 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_t position, Node *current_node){
while (current_node->previous){
current_node = current_node->previous;
}
for (int i = 1; i < position; i++){
current_node = current_node->next;
}
return *current_node;
}
void delete_node(Node &node, Node *current_node){
while (current_node->previous){
current_node = current_node->previous;
}
while (current_node->next){
if (current_node == &node){
node.previous->next = node.next;
node.next->previous = node.previous;
node.next = nullptr;
node.previous = nullptr;
}
current_node = current_node->suivant;
}
}
int main(){
Node node1 = {11, nullptr, nullptr}; // works fine
Node node2 = {22, nullptr, nullptr}; // works fine
add_end(node2, &node1); // works fine
delete_node(get_node(2, &node1), &node1); // bug is here
}
| 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 mentioned error.
One way to solve this is to change the return type of get_node to Node& as shown below:
//--vvvvv------------------------------------------------>return type changed to Node&
Node& get_node(size_t position, Node *current_node){
//other code as before
return *current_node;
}
|
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 i = 0; i < colori.size(); i++)
if (colori[i] == "bianco")
return true;
return false;
}
bool rossoPresente()
{
for (short i = 0; i < colori.size(); i++)
if (colori[i] == "rosso")
return true;
return false;
}
bool colorePresente(string nomeColore)
{
for (short i = 0; i < colori.size(); i++)
if (colori[i] == nomeColore)
return true;
return false;
}
};
And this is my main:
int main()
{
map<string, Bandiera> mappaColoriBandiere;
ifstream f("bandiere.txt");
string buffer, nomeNazione, colore;
vector<string> bufferColori;
while (getline(f, buffer))
{
stringstream ss(buffer);
ss >> nomeNazione;
while (!ss.eof())
{
ss >> colore;
bufferColori.push_back(colore);
}
Bandiera b(bufferColori);
mappaColoriBandiere[nomeNazione] = b;
bufferColori.clear();
}
map<string, Bandiera>::iterator it;
for (it = mappaColoriBandiere.begin(); it != mappaColoriBandiere.end(); it++)
if (it->second.biancoPresente() && it->second.rossoPresente())
cout << it->first << endl;
return 0;
}
Take for correct the part of the code where I read data from the ifstream. The error the is given bakc to me is this one:
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\tuple:1586:70: error: no matching function for call to 'Bandiera::Bandiera()'
second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
^
bandiere.cpp:14:5: note: candidate: Bandiera::Bandiera(std::vector<std::__cxx11::basic_string<char> >)
Bandiera(vector<string> c)
^~~~~~~~
bandiere.cpp:14:5: note: candidate expects 1 argument, 0 provided
bandiere.cpp:8:7: note: candidate: Bandiera::Bandiera(const Bandiera&)
class Bandiera
^~~~~~~~
bandiere.cpp:8:7: note: candidate expects 1 argument, 0 provided
bandiere.cpp:8:7: note: candidate: Bandiera::Bandiera(Bandiera&&)
bandiere.cpp:8:7: note: candidate expects 1 argument, 0 provided
Edit 1
Thanks for all the answers, they were almost perfect. My code works perfectly fine just adding the Defualt constructor to my class. The thing is that my code should be good also adding a copy constructor like this one
Bandiera(const Bandiera &b)
{
colori = b.colori;
}
but it gives me the same error as the initial one. Hope someone can explain this to me. Thanks
| 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 std::map<Key,T,Compare,Allocator>::insert or std::map<Key,T,Compare,Allocator>::emplace.
|
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 which columns they are return completely wrong. The interesting thing is that the results don't always come back wrong. What am I doing wrong?
#include <iostream>
#include <time.h>
#include <cmath>
using namespace std;
int main(void) {
// random number for rand()
srand(time(0));
int m = 5; // row count
int n = 5; // column count
// declaration of a dynamic array of pointers
double **arr = (double**) malloc(n * sizeof(double));
// filling the array with pointers
for (int i = 0; i < n; i++)
arr[i] = (double*) malloc(m * sizeof(double));
// array initialization with random numbers
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = (double) (rand() % 400 - 199) / 2.0; // (-100.0; 100.0)
// matrix output
cout << "\n\033[92mOriginal array:\033[94m" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("%5.1f ", arr[i][j]);
cout << endl;
}
// array for the sums of modules of the row elements
float *sumOfAbsolutes = (float*) malloc(m * sizeof(float));
// Initializing the array with zeros
for (int i = 0; i < m; i++) sumOfAbsolutes[i] = 0;
// filling the array with the sums of element modules
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
sumOfAbsolutes[i] += abs(arr[i][j]);
// output
cout << "\n\033[92mSums of modules of array row elements:" << endl;
for (int i = 0; i < m; i++)
cout << "\033[92m" << i << ": \033[94m"<< sumOfAbsolutes[i] << " ";
cout << "\n\n";
// sorting
for (int i = 0; i < (m - 1); i++)
for (int j = i; j < m; j++)
if (sumOfAbsolutes[i] > sumOfAbsolutes[j]) {
double tmp = sumOfAbsolutes[i];
sumOfAbsolutes[i] = sumOfAbsolutes[j];
sumOfAbsolutes[j] = tmp;
double *tmp2 = arr[i];
arr[i] = arr[j];
arr[j] = tmp2;
}
// matrix output
cout << "\033[92mSorted array:\033[94m" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("%5.1f ", arr[i][j]);
cout << endl;
}
int columnWithMaxNegNum = 0; // the column with the maximal negative element
int minNumber = 0; // the column with the minimum element
// 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] > arr[i][columnWithMaxNegNum])
columnWithMaxNegNum = j;
// minimum element search
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < arr[i][minNumber]) minNumber = j;
cout << "\n\033[92mThe column with the maximum negative element: \033[94m" << columnWithMaxNegNum << endl;
cout << "\033[92mThe column with the minimum element: \033[94m" << minNumber << endl;
// rearrangement of columns
for (int i = 0; i < m; i++) {
double temp = arr[i][columnWithMaxNegNum];
arr[i][columnWithMaxNegNum] = arr[i][minNumber];
arr[i][minNumber] = temp;
}
cout << "\n\033[92mRearrangement of columns:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
printf("\033[94m%5.1f ", arr[i][j]);
cout << "\n\033[0m";
}
// memory cleanup
free(sumOfAbsolutes);
for (int i = 0; i < n; i++)
free(arr[i]);
free(arr);
}
| 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] > arr[i][columnWithMaxNegNum])
columnWithMaxNegNum = j;
Because the the search is dependent of the line. You'd need to go for:
double maxNegNum = -100.0; // tbd
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < 0 && arr[i][j] > maxNegNum) {
columnWithMaxNegNum = j;
maxNegNum = arr[i][j];
}
The same applies for the minimum :
double minN=100.0;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
if (arr[i][j] < minN) {
minNumber = j;
minN = arr[i][j];
}
Not related: if you go for C++ forget malloc and free, and use new/delete and new[]/delete[] instead. Here a first attempt: Online demo
Caution/Limitations:
If by no negative number are found, the maximum negative value would be inaccurate.
If several equal maximum negative values and minimum values are found, only the first one( from left to right and to bottom) will be considered.
|
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 border. Here's the result:
Seems like the data loaded from file is OK - pixels in a row after excess once are the same as in file, checked with another varicolored BMP. Here's the function I use to create texture from BMP:
GLuint CreateTextureFromBMP (const char path [])
{
unsigned char header [54];
unsigned int data_position, width, height, image_size;
unsigned char * data;
FILE * file = fopen (path, "rb");
fread (header, sizeof (char), 54, file);
data_position = *(int *)&(header [0x0A]);
image_size = *(int *)&(header [0x22]);
width = *(int *)&(header [0x12]);
height = *(int *)&(header [0x16]);
if (image_size == 0)
image_size = width * height * 3;
if (data_position == 0)
data_position = 54;
data = (unsigned char *) malloc (sizeof (unsigned char) * image_size);
fread (data, sizeof (char), image_size, file);
free (data);
fclose (file);
GLuint texture_id;
glGenTextures (1, &texture_id);
glBindTexture (GL_TEXTURE_2D, texture_id);
glTexImage2D (GL_TEXTURE_2D, 0, 3, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
return texture_id;
}
I tried using different parameters in glTexImage2D and glTexParameteri functions, but still it change nothing. Here's the render scene function:
void RenderScene (int arg)
{
static GLuint texture_id = CreateTextureFromBMP ("cube_blue.bmp");
glEnable (GL_TEXTURE_2D);
glEnableClientState (GL_TEXTURE_COORD_ARRAY);
glEnableClientState (GL_VERTEX_ARRAY);
glActiveTexture (GL_TEXTURE0);
GLfloat vertices [] = { ... };
GLfloat texcoords [] = { ... };
GLubyte indices [] = { ... };
glVertexPointer (3, GL_FLOAT, 0, vertices);
glTexCoordPointer (2, GL_FLOAT, 0, texcoords);
glPushMatrix ();
glBindTexture (GL_TEXTURE_2D, texture_id);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glColor3f (1.0f, 1.0f, 1.0f);
glDrawElements (GL_QUADS, 24, GL_UNSIGNED_BYTE, indices);
glPopMatrix ();
glDisable (GL_TEXTURE_2D);
glDisableClientState (GL_TEXTURE_COORD_ARRAY);
glDisableClientState (GL_VERTEX_ARRAY);
}
Any ideas where to look for the mistake?
| 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 free() and glTexImage2D() is free to overwrite this buffer in the heap.
Try moving the call to free() until after the call to glTexImage2D() and see what happens.
|
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 messsage";
std::vector<uint8_t> msg(msg_str.begin(), msg_str.end());
// generate a key pair
EVP_PKEY* key = EVP_PKEY_Q_keygen(nullptr, nullptr, "RSA", 2048);
// signature
std::vector<uint8_t> sig_out(1024); // reserve some memory
// signing process
EVP_MD_CTX* md_ctx(EVP_MD_CTX_new());
size_t out_len = 0; // final signature length (calculated by openssl)
if (EVP_DigestSignInit(md_ctx, nullptr, EVP_sha1(), nullptr, key) == 0)
{
std::cout << "EVP_DigestSignInit error: " << ERR_error_string(ERR_get_error(), NULL) << std::endl;
}
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::endl;
}
else
{
sig_out.resize(out_len);
std::cout << "signature length: " << sig_out .size() << " data: " << std::endl;
for (size_t i = 0; i < out_len; i++)
{
printf("%.2X ", sig_out[i]);
}
}
EVP_PKEY_free(key);
EVP_MD_CTX_free(md_ctx);
return;
}
On my desktop PC all signatures work but not on the Raspberry Pi. Here is the screen output:
Windows 10, AMD CPU, x64 system, OpenSSL 3.0.0:
signature length: 256 data:
59 A9 45 F5 2B 97 51 F5 53 A8 AE 17 16 7A 26 28
F5 68 3F 1F 3D B2 05 4F 0E 28 AF F2 F5 0E DA FF
37 71 50 DD DA E1 DE F0 91 05 0A 07 79 30 00 03
A4 1E F5 60 F5 7E 47 97 EF 88 9C 27 70 CE 64 63
0B 6C 2E 50 7B D7 89 48 B6 73 44 AD 7A 02 EA 49
BC D3 95 67 B8 E6 D9 E4 A1 4F 2B E8 F4 5C F8 73
B5 53 B0 A5 FB BB 7A 81 1C 25 23 6F 30 D8 8F D8
EC 9E 02 00 C2 0D 7C 9C 23 66 D7 44 62 FF 51 1A
94 3F 6F FB D7 B2 C5 2B A4 03 09 E5 10 44 D4 AE
A2 69 F3 EB 31 1B CB 2A 14 1D 76 CD 11 09 B9 76
99 59 42 5A 74 3D 14 98 B7 87 FD 98 16 17 AC 9E
DA 55 82 0B 93 3D 24 28 4F 09 EB EA AE 82 77 47
B2 E2 C8 1E 62 FF E4 90 E6 18 E8 88 94 B4 F0 AF
DF A2 2B D7 79 32 BD C5 0F B1 03 36 B6 D8 44 9A
FA DB 02 EB 7D FE D5 D7 15 34 77 72 4D 4E 44 A8
E7 DA D9 2B 49 80 43 58 1F AA F4 1D 27 80 1C EE
Raspberry Pi, ARM CPU, Debian (bullseye), x64 system, OpenSSL 3.1.0:
EVP_DigestSign error: error:1C8000B3:Provider routines::invalid signature size
does anyone have any idea what the problem may be? I am now a bit desperate.
best regards,
SBond
| 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::endl;
}
to
EVP_DigestSign(md_ctx, nullptr, &out_len, msg.data(), msg.size()); // calculates the final length (does not perform signature; therfore a fast process)
sig_out.resize(out_len);
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::endl;
}
now I'm happy :)
|
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 code with GDB. All values from table[0][0] to table[0][3] are garbage but all values from table[0][4] to table[0][9] are all 0. This problem is Valid for all pointers from table[0] to table[9].
Then I thought there was a problem with GDB and I printed table[0][0] and table[0][5] to the screen. Indeed the value of table[0][0] is garbage, the value of table[0][5] is 0.
My question is does c++ actually freeing this data?
| 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 0 1 1
Country6 0 1 1
Country7 1 1 0
Let's imagine that all medal types represent specific number of points, for example Gold is 4 points, Silver is 2 points and Bronze is 1 point.
The thing I'm trying to achieve is that program is looking at all rows and columns and prints the number of points each country has.
Expected Output:
Points
Country1 5
Country2 6
Country3 1
Country4 4
Country5 3
Country6 3
Country7 5
Here is my code
#include <iostream>
#include <iomanip>
using namespace std;
const int COUNTRIES = 7;
const int MEDALS = 3;
void print_2D_array(int mas[][MEDALS], int r, int k);
void print_task(int mas[][MEDALS], int r, int k);
int medal_counts[COUNTRIES][MEDALS] = {
{1, 0, 1},
{1, 1, 0},
{0, 0, 1},
{1, 0, 0},
{0, 1, 1},
{0, 1, 1},
{1, 1, 0}};
int main(){
int i;
print_2D_array(medal_counts, COUNTRIES, MEDALS);
print_task(medal_counts, COUNTRIES, MEDALS);
return 0;
}
void print_2D_array(int mas[][MEDALS], int r, int k){
for(int n = 0; n < r; n++){
for(int m =0; m < k; m++){
cout << setw(4) << mas[n][m];
}
cout << endl;
}
}
void print_task(int mas[][MEDALS], int r, int k){
cout << setw(20) << "Gold" << setw(10) << "Silver" << setw(10) << "Bronze" << endl;
for (int i = 0 ; i < COUNTRIES; i++){
cout << "Country" << i + 1 << " ";
for (int j = 0 ; j < MEDALS; j++){
cout << setw(5) << mas[i][j] << " ";
if(j == 2)
cout << endl;
}
}
}
I was trying to solve this problem for a long time and I tried using
for(int i = 0; i < MEDALS; i++){
for(int j = 0; j < COUNTRIES; j++){
cout << "arr[" << j << "][" << i << "] ";
cout << medal_counts[j][i] << endl;
}
}
cout << endl;
With the output of:
arr[0][0] 1
arr[1][0] 1
arr[2][0] 0
arr[3][0] 1
arr[4][0] 0
arr[5][0] 0
arr[6][0] 1
arr[0][1] 0
arr[1][1] 1
arr[2][1] 0
arr[3][1] 0
arr[4][1] 1
arr[5][1] 1
arr[6][1] 1
arr[0][2] 1
arr[1][2] 0
arr[2][2] 1
arr[3][2] 0
arr[4][2] 1
arr[5][2] 1
arr[6][2] 0
But I still didn't figure out how to solve this problem.
Are there any ideas?
| 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 way we can access it although we can't change the value because its type is const.
Question: Is there a way we can access this anonymous variable/object apart from using the reference ref? In general, does C++ allow access to these anonymous objects?
| 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 that reference (with some exceptions not applying here).
So yes, you can use ref here exactly in the same way as if you had written
const int ref = 3 * x + 1;
instead. (With some minor exceptions like decltype(ref) being different.)
There is no other way to access such objects other than binding a reference to them. But that isn't really a restriction. You can do (almost) everything you can do with the name of a variable also with a reference to a variable/object.
|
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 = QWebEngineProfile::defaultProfile();
defaultProfile->setHttpCacheType(QWebEngineProfile::DiskHttpCache);
defaultProfile->setPersistentCookiesPolicy(QWebEngineProfile::ForcePersistentCookies);
QHttpPart* header = new QHttpPart;
header->setRawHeader("X-Frame-Options", "ALLOWALL");
defaultProfile->setCachePath(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
defaultProfile->setPersistentStoragePath(QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation));
I need to save Cookies.
| 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();
view->setPage(page);
view->setUrl(AccueilUrl);
view->setZoomFactor(1.2);
setCentralWidget(view);
|
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 "RtMidi.h"
And only this in the constructor:
RtMidiIn *midiin = new RtMidiIn();
Just to see if that much compiles. But I'm getting the following:
Undefined symbols for architecture x86_64:
"RtMidiIn::RtMidiIn(RtMidi::Api, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, unsigned int)", referenced from:
spotify::playback::AudioDecompressorProcess::AudioDecompressorProcess(spotify::playback::AudioSinkChain const&, std::__1::function<std::__1::unique_ptr<spotify::playback::AudioDecompressor, std::__1::default_delete<spotify::playback::AudioDecompressor> > (spotify::tl::span<unsigned char const>)> const&, bool, spotify::playback::PlaybackInstrumentation&, std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000l> >, std::__1::chrono::duration<long long, std::__1::ratio<1l, 1000l> >) in libplayback.a(audio_decompressor_process.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
** BUILD FAILED **
The following build commands failed:
Ld /Users/acheong/src/spotify/client-web/desktop/shell/build/desktop/Debug/Spotify.app/Contents/MacOS/Spotify normal (in target 'Spotify' from project 'spotify')
I found this thread which suggested defining __MACOSX_CORE__. I tried this in 2 ways. First, using a #define right before the include:
#define __MACOSX_CORE__
#include "RtMidi.h"
Same error. Second, by adding this to the xcodebuild command line:
GCC_PREPROCESSOR_DEFINITIONS='$GCC_PREPROCESSOR_DEFINITIONS __MACOSX_CORE__'
Same error still. (These are definitely doing something though, because when I accidentally tried both the above simultaneously, I got an error that the macro was already defined.)
I'm not super familiar with C++ build chains, so I'm not sure whether I'm just doing something stupid—like, do I need to update some Makefiles or something for the compiler to "see" RtMidi.cpp/h—or is this some kind of compatibility issue as I've read in some threads.
| @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_format.cpp
...
And also added this:
target_link_libraries(playback PRIVATE "-framework CoreMIDI")
Then I was able to include "RtMidi.h" in my existing program, and add the example code, i.e.
RtMidiIn *midiin = new RtMidiIn();
// Check available ports.
unsigned int nPorts = midiin->getPortCount();
...
and have everything build successfully, not even needing the __MACOSX_CORE__ anywhere.
|
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<std::variant<double, int, std::string>, 6> a{3.2, 2, 4, 6, 2.4, "foo"};
int intTotal = 0;
double doubleTotal = 0.0;
Visitor visitor {[&intTotal](const int i){intTotal += i;},
[&doubleTotal](const double d) { doubleTotal += d;},
[](const std::string& c) { }};
std::for_each(begin(a), end(a), [&visitor](const auto &v) {std::visit(visitor, v);});
std::cout << intTotal << " " << doubleTotal << std::endl;
}
I can get rid of the the perfect forwarding as well as the deduction guide. Is this not considered the best practice in C++. In what situations is it less efficient?
template<typename... B>
struct Visitor: B...{
Visitor(const B&... b): B(b)... { }
using B::operator()...;
};
e
|
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 be copied (because they have non-copyable state, e.g. [x = std::make_unique<int>()](){}).
I can get rid of the ... the deduction guide.
If you pass by const reference, yes. But if you pass by a forwarding reference, no.
The constructor having an independent set of template parameters is one problem. Buf if you used the same template parameters (and inherited from std::decay_t<B>... instead), it still wouldn't work, because built-in deduction guides refuse to do perfect forwarding. The template argument deduction wouldn't work if you passed an lvalue.
A better question is why have a constructor at all. If you remove it, the type becomes an aggregate and everything continues to work as before.
It even lets you remove the deduction guide (except that Clang doesn't support that yet).
|
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, char *argv[])
{
parms p(first{}, second{});
}
I get a compile error on clang but compiles on gcc. Which C++ feature is this that is not supported in clang? Obviously if i change the ( to { it compiles fine.
| 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;
int8_t b;
};
void* offset_bytewise(void* void_ptr, ptrdiff_t count) {
return static_cast<void*>(static_cast<char*>(void_ptr) + count);
}
void test() {
auto void_ptr = std::malloc(10);
new (offset_bytewise(void_ptr, 0)) Foo{ 1, 2 };
new (offset_bytewise(void_ptr, 8)) Bar{ 3, 4 };
auto foo_ptr = static_cast<Foo*>(offset_bytewise(void_ptr, 0));
auto bar_ptr = static_cast<Bar*>(offset_bytewise(void_ptr, 8));
std::cout << (int)foo_ptr->a << ' ' << (int)foo_ptr->b << '\n';
std::cout << (int)bar_ptr->a << ' ' << (int)bar_ptr->b << '\n';
// Re-using a part of the allocation as a different type than before.
new (offset_bytewise(void_ptr, 1)) Bar{ 5, 6 };
bar_ptr = static_cast<Bar*>(offset_bytewise(void_ptr, 1));
// I suppose dereferencing `foo_ptr` would be UB now?
std::cout << (int)bar_ptr->a << ' ' << (int)bar_ptr->b << '\n';
std::free(void_ptr);
}
| 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 other objects (although technically the standard currently says this is only true for unsigned char and std::byte, which is probably a defect).
So you are ok to create new objects in that array as you are doing.
However, when you try to obtain a pointer to the newly created object, you cannot simply cast the pointer since elements of the array are not pointer-interconvertible with the objects for which the array provides storage.
Therefore you need to apply std::launder after casting the pointer, e.g.
auto foo_ptr = std::launder(static_cast<Foo*>(offset_bytewise(void_ptr, 0)));
Alternatively you can use the result of new which is a pointer to the newly created object:
auto foo_ptr = new(offset_bytewise(void_ptr, 0)) Foo{ 1, 2 };
Also, you need to make sure that size and alignment of the types is correct, i.e. here you should add:
static_assert(alignof(Foo) <= 8);
static_assert(sizeof(Foo) <= 8);
static_assert(alignof(Bar) <= 1);
static_assert(sizeof(Bar) <= 2);
Creating the second Bar object at offset 1 will cause the lifetime of the Foo object to end, since it overlaps with the storage of the new object. Therefore foo_ptr may afterwards be used only in the way other pointers to object out-of-lifetime of an object may be used. In particular trying to access the value of a member will be UB.
|
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 since it is for string it did not work.
I also tried to reload the operator<< but it did not help.
| 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;apple2;apple3"};
char buffer[256];
while (infile.getline(buffer, sizeof(buffer), ';'))
std::cout << buffer << "\n";
}
Result:
apple1
apple2
apple3
Note: while this fits the school prohibition against using std::string, there's almost no other situation where it makes sense.
|
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.
handleGetResource is where the client's business logic resides. This is the C++ user code specific to the client.
I would like to compile this user code into a dynamic library so that I can provide the client only with the source code related to their business logic. This way, they can modify and rebuild this business logic without having access to my executable's source code.
Can someone provide me with some advice on how to best handle this? Both the app and the dynamic libraries would be written in C++. Note: the executable is cross compiled to run on Win and Linux.
Thank you
| 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 shared library (.so) - which is nearly the same thing as a DLL.
In your application, you will invoke LoadLibrary and GetProcAddress to load the customer's DLL from file and to get a function pointer to his implementation of handleGetResource:
typedef void (__stdcall *HANDLE_GET_RESOURCE)(Request* request, Response* response);
HMODULE hMod = LoadLibrary("C:\\Path\\To\\Customers\\Dll\\TheirHandler.dll");
HANDLE_GET_REQUEST handler = (HANDLE_GET_RESOURCE)GetProcAdderss(hMod, "handleGetResource");
Then to invoke:
handler(&request, &response);
Then your customer can build a DLL with a definition like the following:
extern "C" __declspec(dllexport) void __stdcall handleGetResource(Request* req, Response* res)
{
// their code goes here
}
You can do the same thing on Linux with dlopen and dlsym in place of LoadLibrary and GetProcAddress.
For Windows, I would also be explicitly in having these typedefs and function defintions be explict with regards to __cdecl or __stdcall.
As to how the customer registers the full path to their compiled binary - that's a mechanism that you can decide for yourself. (e.g. command line, registry, expected file name in current directory, etc...)
|
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 the list is a subset of the above set. For example, setlist[0] and setlist[1] are both subsets, so the output would be true
My idea is to loop through the whole vector and check if any of the indexes are a subset using the std::includes function, but I am looking for a faster way. Is this possible?
| 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. This avoids that you check inclusion of the larger sets in the smaller ones.
If the range of the integers is not too large, you could consider implementing the set with a std::bitset (bit n is true if n is included). The inclusion test is then done with very fast logical operation (e.g. subset & large_set == subset). You could still sort the vector by count, but not sure that this would be needed considering the speed of the logical operation.
|
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't compile because I do provide a very specific member object. I feel I should add that consolePlay is a global/independent function.
bool consolePlay(CommandProcessor* game) {
83 cout << "game state: " << game->currentCommand();
84 game->getCommand();
85
86 if (CommandProcessor::validate(game->currentCommand())) {
87 if (game->currentCommand() == "loadmap") {
88 game->setState("maploaded");
89 return true;
120 int main(int argc, char *argv[]) {
121
122 if (argc == 0) {
123 cout << "You must specify console or file input in command line" << endl;
124 exit(0);
125 }
126
127 if (argc > 1 && (argv[0] != "-console" || argv[0] != "-file")) {
128 cout << "Invalid command line argument(s)" << endl;
129 exit(0);
130 }
131 CommandProcessor *game = new CommandProcessor();
132 if (argv[argc-1] == "console")
133 while (consolePlay(game)) {
134 continue;
135 }
currentCommand accesses a member in an array of pointers to different members of the Command class, that array itself being a member variable of CommandProcessing.
22 string CommandProcessor::currentCommand() {
23 Command temp = *commandList[commandCount];
24 return temp.command;
25 }
I appreciate the help this is driving me crazy.
| 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:
#include <yaml-cpp/yaml.h>
#include <fstream>
#include <map>
using namespace std;
int main()
{
YAML::Node camerafile = YAML::LoadFile("/path/to/camera.yaml");
YAML::Node camera = camerafile["camera"];
auto response_values_yaml = camera["response_values"];
for(YAML::const_iterator it=response_values_yaml.begin();it!=response_values_yaml.end();++it) {
YAML::Node response_values_map = it->as<YAML::Node>(); // e.g. [0.0: 0.0, 1.0: 1.1, 245.0: 250.1]
string whole_map = YAML::Dump(response_values_map);
for(YAML::const_iterator at=response_values_map.begin();at!=response_values_map.end();++at) {
auto the_thing = at->as<YAML::Node>();
string the_string = YAML::Dump(the_thing);
float key = at->first.as<float>();
float val = at->second.as<float>();
}
}
}
Debug results:
whole_map: "[{0.0: 0.0}, {1.0: 1.1}, {245.0: 250.1}]"
the_string: "{0.0: 0.0}"
the_thing->Node->Ref->Data has a map item
However, as soon as the program reaches float key = at->first.as<float>();, it crashes.
terminate called after throwing an instance of 'YAML::InvalidNode'
what(): invalid node; this may result from using a map iterator as a sequence iterator, or vice-versa
GDB jumps into yaml-cpp/node/imlp.h. this is an empty node with m_isValid being false.
Trying as<string> produces the same behaviour. I think I have a map, but I can't interpret it as a map using the .first and .second methods, I think this is what the error messages tells me. What am I missing?
| #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 sequence iterator
for (YAML::const_iterator it = response_values_yaml.begin();
it != response_values_yaml.end(); ++it) {
YAML::Node response_values_map
= it->as<YAML::Node>(); // e.g. [0.0: 0.0, 1.0: 1.1, 245.0: 250.1]
for (YAML::const_iterator at = response_values_map.begin();
at != response_values_map.end(); ++at) {
// `at` is a **map iterater** which has a single key/value pair.
// so it will certainly coredump when you are calling `at->first.as<float>()`
assert(at->size() == 1);
// The iterator points to the single key/value pair.
YAML::Node::const_iterator sub_it = at->begin(); // **The key point.**
// Then access the key and value.
float key = sub_it->first.as<float>();
float value = sub_it->second.as<float>();
std::cout << " key: " << key << ", val: " << value << '\n';
}
}
}
The output will look likes this:
key: 0, val: 0
key: 1, val: 1.1
key: 245, val: 250.1
key: 0, val: 0.1
key: 1, val: 1.3
key: 200, val: 250
key: 0, val: 0
key: 1, val: 1.1
key: 245, val: 250.1
|
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, b);
std::cout << sum;
}
int addition(int a, int b) {
return a + b;
}
|
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>
constexpr int nr=100;
void print(const std::vector<double>& d1, const std::array<std::complex<double>,nr>& b1, const std::vector<int>& b2, const std::array<double,nr>& d2)
{
for(int i=0; i<nr; ++i)
std::cout<<b1[i]<<" "<<d1[i]<<" "<<b2[i]<<" "<<d2[i]<<"\n";
}
Now assuming that all the containers contain the standard numeric types I could write a variadic template function that would look like this:
template<typename... T>
void vprint(T... cs)
{
constexpr int nc=sizeof...(T);
std::vector<std::vector<std::complex<long double>>> v(nr, std::vector<std::complex<long double>>(nc));
//then fill v recursively with all the cs and print it
}
where I used std::complex<long double> since it would contain any possible number.
However this solution is unsatisfactory since I am allocating extra memory, I am converting some integers spoiling the output (and possibly precision), and, finally, the solution does not work if any of the containers contains a printable type that does not convert trivially to a numeric type.
Any idea on how to write a more general solution?
| 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 vprint(const T& front, const Ts&... cs) {
for (int i = 0; i < front.size(); ++i) {
std::cout << front[i];
((std::cout << ' ' << cs[i]), ...);
std::cout << '\n';
}
}
This makes use of C++17 fold expressions to print the ith element of each container, after printing the first one manually. Handling the first one explicitly also ensures we don't print an extra space at the end (or beginning) of each line without branches.
If you don't have access to C++17, it can still be implemented but it'll be a lot uglier than this.
As per Louis' comment, you could also add an assert before the for loop to make sure all the containers have at least front.size() elements in them for safety:
assert(((cs.size() >= front.size()) && ...));
Change the >= to == for strict equality.
Usage:
int main() {
std::array<int, 4> a{1,2,3,4};
std::vector<int> b{5,6,7,8};
vprint(a, b);
}
Prints
1 5
2 6
3 7
4 8
https://godbolt.org/z/z6s34TaT9
|
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.?
Thanks a lot!
Ivan
| 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 = 3 then it must also see version++.
What's the weakest memory order and synchronization we must impose so that the assertion in thread B is always satisfied?
If I understand C++ memory_order correctly, the release-acquire ordering won't do because that guarantees that operations BEFORE version++, in thread A, will be seen by the operations AFTER v = version, in thread B.
Acquire and release fences also work in the same directions, but are more general.
As I said, I need the other direction: B sees data = 3 implies B sees version = 1.
I'm using this "versioning approach" to avoid locks as much as possible in a data structure I'm designing. When I see something has changed, I step back, read the new version and try again.
I'm trying to keep my code as portable as possible, but I'm targeting x86-64 CPUs.
| 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. (version = tmp_counter >> 1 since you need two increments per write of the payload to let readers detect tearing when reading the non-atomic data. And to make sure they see the data that goes with this sequence number. Make sure you don't read the atomic counter a 3rd time; use the local tmp that you read it into to verify match before/after copying data.)
Readers will have to retry if they happen to attempt a read while data is being modified. But it's non-atomic, so there's no way if thread B sees data = 3 can ever be part of what creates synchronization; it can only be something you see as a result of synchronizing with a version number from the writer.
See:
Implementing 64 bit atomic counter with 32 bit atomics - my attempt at a SeqLock in C++, with lots of comments. It's a bit of a hack because ISO C++'s data-race UB rules are overly strict; a SeqLock relies on detecting possible tearing and not using torn data, rather than avoiding concurrent access entirely. That's fine on a machine without hardware race detection so that doesn't fault (like all real CPUs), but C++ still calls that UB, even with volatile (although that puts it more into implementation-defined territory). In practice it's fine.
GCC reordering up across load with `memory_order_seq_cst`. Is this allowed? - A GCC bug fixed in 8.1 that could break a seqlock implementation.
If you have multiple writers, you can use the sequence-counter itself as a spinlock for mutual exclusion between writers. e.g. using an atomic_fetch_or or CAS to attempt to set the low bit to make the counter odd. (tmp = seq.fetch_or(1, std::memory_order_acq_rel);, hopefully compiling to x86 lock bts). If it previously didn't have the low bit set, this writer won the race, but if it did then you have to try again.
But with only a single writer, you don't need to RMW the atomic sequence counter, just store new values (ordered with writes to the payload), so you can either keep a local copy of it, or just do a relaxed load of it, and store tmp+1 and tmp+2.
|
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 <cstring>
#include <algorithm>
#include "vector.h" //You can also use #include <vector>
using namespace std;
Vector<string> split(string str, string token) //The saving grace
{
Vector<string> result;
while(str.size()){
int index = str.find(token);
if(index!=string::npos){
result.push_back(str.substr(0,index));
str = str.substr(index+token.size());
if(str.size()==0)result.push_back(str);
}
else
{
result.push_back(str);
str = "";
}
}
return result;
}
bool isInteger(string str)
{
for(int i = 0; i<str.length(); i++)
{
if(isdigit(str[i]) == true)
{
return true;
}
}
return false;
}
//----------------------------------------------------//
//Lets get the text of the file into vectors
Vector<string> movieTitle(string txtfile)
{
Vector<string> text; //Contains all of the text
Vector<string> films; //All the films
fstream myFile;
string word;
myFile.open(txtfile);
if(!myFile.good())
{
cout << "ERROR: FILE NOT FOUND" << endl;
exit(1);
}
while(getline(myFile, word, '\n'))
{
//cout << word << endl;
text += split(word, "\t");
}
for(int i = 0; text.size(); i++)
{
if(text[i].find("(") != string::npos && isInteger(text[i]))
{
films.push_back(text[i]);
}
}
return films;
}
int main()
{
Vector<string> test;
test = movieTitle("movies_mpaa.txt");
cout << test << endl;
return 0;
}
Out Put:
terminate called after throwing an instance of 'ErrorException'
what():
Aborted (core dumped)
I am just confused on where the error is occurring.
| 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 as std::vector's and throws an exception if i becomes bigger than size()-1. Your loop never stops because size() never would return 0 if it wasn't 0 to begin with, so eventually i becomes greater. Loop should look like
for(int i = 0; i < text.size(); i++)
If you used backtrace command in GDB after program had stopped, you'd saw the chain of called functions leading to catastrophic stop. You can walk up to your code by using command frame <number>, where <number> would be an item in that list. GDB got extensive online documentation and FAQ, there are god guides how to use it.
|
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::endl;
}
int main(int argc, char* argv[]) {
print_message(say_hello);
return 0;
}
How do I template instantiate the print_message function explicitly in the .cpp file, along the lines of how it is described here.
I tried the following code snippet but I get this error: explicit instantiation of 'print_message' does not refer to a function template, variable template, member function, member class, or static data member.
// 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::endl;
}
template void print_message<say_hello>(say_hello func);
int main(int argc, char* argv[]) {
print_message(say_hello);
return 0;
}
| 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.
This compiles whithout error:
#include <iostream>
// func.h
template <class T>
void print_message(T func) {
func();
}
// main.cpp
void say_hello() {
std::cout << "hello" << std::endl;
}
template void print_message<decltype(&say_hello)>(decltype(&say_hello) func);
int main(int argc, char* argv[]) {
print_message(&say_hello);
return 0;
}
|
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 for the discussion: Suppose we have 2 threads running on 2 different cores
This is pseudo-code!
We start with int f = 0; int x = 0; and then run those threads:
# Thread 1
while(f == 0);
print(x)
# Thread 2
x = 42;
f = 1;
Of course, the desired result of this program is that thread 1 will print 42.
NOTE: I leave "compile-time reordering" out of this discussion, I only want to focus on what happens in runtime, so ignore all kinds of optimizations that the compiler might do.
Ok so from what I understand the problem here is what is called "memory reordering": the CPU is free to reorder memory operations as long as the end result is what the program expects it to be. In this case, within thread 2, the f = 1 may be executed before x = 42. In this case, thread 1 will print 0, which is not what the programmer want.
At this point, Wikipedia points at another possible scenario that may occur:
Similarly, thread #1's load operations may be executed out-of-order and it is possible for x to be read before f is checked
Since we're talking right now about "out of order execution" - let's ignore for a moment from the caches of the cores. So let's analyze what happens here. Start with thread 2 - the compiled instructions will look (in pseudo-assembly) something like:
1 put 42 into register1
2 write register1 to memory location of x
3 put 1 into register 2
4 write register2 to memory location of f
Ok so I understand that 3-4 may be executed before 1-2. But I don't understand the equivalent in thread 1:
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 exactly may be out of order here? 3 can be before 1-2?
Let's go on: Up until now we talked about out-of-order execution, which brings me to my primary confusion:
In this great post the author describes the problem as such: Each core has its own cache, and the core does the memory operations against the cache, not against the main memory. The movement of memory from the core-specific caches to the main memory (or a shared cache) occurs in unpredictable time and order. So in our example - even if thread 2 will execute its instructions in-order - the writing of x=42 will occur before f=1, but that will be only to the cache of core2. The movement of these values to a shared memory may be in the opposite order, and hence the problem.
So I don't understand - when we talk about "memory reordering" - do we talk about Out-of-order execution, or are we talking about the movement of data across caches?
| 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 exactly may be out of order here? 3 can be before 1-2?
To answer your question, this is a reverberating "YES!". Since the contents of register1 are not tied in any way to the contents of register2 the CPU may happily (and correctly, for that matter) preload register2, so that when the the 1,2 loop finally breaks, it can immediately go to 4.
For a practical example, register1 might be an I/O peripheral register tied to a polled serial clock, and the CPU is just waiting for the clock to transition to low, so that it can bit-bang the next value onto the data output lines. Doing it that way for one saves precious time on the data fetch and more importantly may avoid contention on the peripheral data bus.
So, yes, this kind of reordering is perfectly fine and allowed, even with optimizations turned off and happening on a single threaded, single core CPU. The only way to make sure that register2 is definitely read, after the loop breaks, is to insert a barrier.
The second question is about cache coherence. And again, the answer to the need of memory barriers is "yes! you need them". Cache coherence is an issue, because modern CPUs don't talk to the system memory directly, but through their caches. As long as you're dealing with only a single CPU core, and a single cache, coherence is not an issue, since all the threads running on the same core do work against the same cache. However the moment you have multiple cores with independent caches, their individual views of the system memory contents may differ, and some form of memory consistency model is required. Either through explicit insertion of memory barriers, or on the hardware level.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.