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 |
|---|---|---|---|---|
70,170,287 | 70,170,465 | Bug in templated conversion operator in GCC: Workaround? | I want to have a class representing a unit with some kind of dimension. This should express something like 1.5m^2. A scalar multiplication with some type shall be allowed and a dimensionless unit should behave exactly like the underlying type. Here is my solution:
#include <type_traits>
template<typename T, int Dim>
class Unit {
public:
explicit Unit(T t): _value(t) {}
template<int D = Dim, typename std::enable_if_t<D==0, int> = 0>
operator T() { static_assert(Dim==0, ""); return _value; } //static_assert not necessary, but gives error if template is removed
T _value;
};
template<typename S, typename T, int Dim>
auto operator*(S s, Unit<T,Dim> unit)
{
return Unit<T, Dim>(s * unit._value);
}
auto main() -> int
{
auto i = double{0};
//Scalar test
auto scalar = int{0};
auto x = Unit<double,1>(i);
auto test = scalar * x;
//Conversion test
auto y = Unit<double,0>(i);
return y + i;
}
This works perfectly fine in clang (https://godbolt.org/z/8Pev7W6Y1). However, due to a GCC bug with templated conversion operators (Conversion operator: gcc vs clang), this does not work in GCC.
It is not possible to remove the SFINAE construction because it (correctly) runs into the static_assert.
Do you have an idea for equivalent code that also works in GCC? The code should work in C++17 with both compilers.
| You can use specialization instead of SFINAE. To avoid too much duplication you can move the common parts (anything that does not depend on Dim) to a base class:
#include <type_traits>
template <typename T>
class base_unit {
public:
explicit base_unit(T t): _value(t) {}
T _value;
};
template<typename T, int Dim>
class Unit : public base_unit<T> {
public:
explicit Unit(T t): base_unit<T>(t) {}
};
template <typename T>
class Unit<T,0> : public base_unit<T> {
public:
explicit Unit(T t) : base_unit<T>(t) {}
operator T() { return base_unit<T>::_value; }
};
template<typename S, typename T, int Dim>
auto operator*(S s, Unit<T,Dim> unit)
{
return Unit<T, Dim>(s * unit._value);
}
auto main() -> int
{
auto i = double{0};
//Scalar test
auto scalar = int{0};
auto x = Unit<double,1>(i);
auto test = scalar * x;
//Conversion test
auto y = Unit<double,0>(i);
return y + i;
}
Live Demo
Note that this is a little old-fashioned and does not consider more modern C++20 approaches (for example the operator T() requires (Dim == 0) mentioned in a comment).
|
70,170,411 | 70,170,468 | c++ klocwork scan std::vector uninitialized | > -Severity (Error)
> -ID(local): 7
> -Code: UNINIT.CTOR.MUST --> IpuCCAInterfaceBase()
> -Message: 'this->_remaining_run_kernels_uuids' is not initialized
> in this constructor.
> -Details:
>
> 'this->_remaining_run_kernels_uuids' is not initialized in this
> constructor.
>
> * IpuCCAInterfaceBase.cpp:47: passing 'this' to 'InitializeSaResults'
> does not initialize 'this->_remaining_run_kernels_uuids'
>
> * IpuCCAInterfaceBase.cpp:47: passing 'this' to 'CreateNVMData'
> does not initialize 'this->_remaining_run_kernels_uuids'
>
> * IpuCCAInterfaceBase.cpp:143: 'this->_remaining_run_kernels_uuids'
> is used, but is uninitialized.
>
> Current status 'Analyze'
This is the error I am getting
class COMMON_CCA_INTERFACE IpuCCAInterfaceBase : public ICCAOperations
{
private:
vector<int> _remaining_run_kernels_uuids;
}
here is the header file
the cpp ctor
IpuCCAInterfaceBase::IpuCCAInterfaceBase()
{
}
we are using klocworks 20.1
what is the recommended way to solve this error?
the vector will be initialized and filled later in a different function. but when loading the class there is no data in it.
| Perhaps Klockwork requires you to explicitly initialize the vector, for example in a constructor initializer list:
IpuCCAInterfaceBase::IpuCCAInterfaceBase()
: _remaining_run_kernels_uuids{ }
{
}
With that said, I would consider the message a false positive, as the vector should be implicitly default-constructed (and thus initialized) even without this.
|
70,170,507 | 70,171,035 | How to iterate through a collection of maps of different kinds using range based 'for' loops? | I can iterate through a map as follows:
std::map<int, std::string> intMap = { {1, "one"}, {2, "two"}, {3, "three"} };
for (const auto &[k, v]: intMap)
{
doSomething(k, v);
}
I have another map (of different type and size) defined as follows:
std::map<float, std::string> floatMap = { {1.0, "one"}, {2.0, "two"}};
I want to do the same thing for this map as well (doSomething(k, v) is templated)
for (const auto &[k, v]: floatMap)
{
doSomething(k, v);
}
Is there a way where I can do this for both the maps by iterating through the collection of maps?
Something like:
for (const auto &map: {intMap, floatMap})
{
for (const auto &[k, v]: map)
{
doSomething(k, v);
}
}
This however gives the error:
cannot deduce type of range in range-based 'for' loop
What's the cleanest way (> C++17) to iterate through a collection of maps (of different kinds) using range-based 'for' loops?
Thanks!
| You can use fold expression to expand immediately invoked lambda to do this:
[](const auto&... maps) {
([&] {
for (const auto& [k, v] : maps)
doSomething(k, v);
}(), ...);
}(intMap, floatMap);
Demo.
|
70,172,168 | 70,172,721 | One less data is deleted when using hash table delete function | I have created a project using a hash table with separate chaining. Now for my delete function, there is a slight problem, sometimes when a try to delete a node it always deletes 1 less node than it's supposed to. To simplify what I mean is, for example, if I am trying to delete all "people" objects that are in Columbia then I expect 56 data to be deleted but only 55 get deleted. And when I try to delete again then it realizes there is 1 left and deletes that. So every time it is deleting one less data than it is supposed to. Please let me know if there is a problem with my implementation.
void HashMap::deleteByString(string toDelete)
{
bool haveDeleted = false;
int totalDeleted = 0;
auto start = chrono::steady_clock::now();
for (int i = 0; i < buckets; i++) {
Node* current = hashTable[i];
Node* previous = NULL;
while (current && current->data.getCountry() != toDelete) {
previous = current;
current = current->next;
}
if (current) {
if (previous) {
previous->next = current->next;
haveDeleted = true;
delete current;
++totalDeleted;
}
else {
hashTable[i] = current->next;
haveDeleted = true;
delete current;
++totalDeleted;
}
}
}
}
| Since deleteByString iterates over all content without using a hash function on its argument, we can assume that countries are not the hash key and thus there can be arbitrarily many items with the same country in a bucket. You can't just drop out of your inner loop when you find one of them in this case.
Something like the following should be what you want:
void deleteByString(std::string toDelete)
{
for (int i = 0; i < buckets; i++) {
Node* current = hashTable[i];
Node* previous = NULL;
while (current) {
if ( current->data.getCountry() != toDelete) {
previous = current;
current = current->next;
} else {
if (previous) {
previous->next = current->next;
auto temp = current;
current = previous->next;
delete temp;
} else {
hashTable[i] = current->next;
auto temp = current;
current = hashTable[i];
delete temp;
}
}
}
}
}
Basically since iteration is continuing after a deletion, you now need to make sure previous and current are correctly maintained across deletions.
|
70,172,239 | 70,176,608 | Menubar does not change colour | I have following simple piece of code:
m_menuBar = new wxMenuBar();
m_menuBar->SetForegroundColour(*wxRED);
m_menuBar->SetBackgroundColour(*wxGREEN);
m_menuBar->SetOwnBackgroundColour(*wxYELLOW);
But no matter where I set these colours, my menu bar does not show any of them. So what am I doing wrong or what has to be done to let the menu bar and menus appear in a custom colour?
Thank you :-)
| Unfortunately a menu bar is not really a window even if wxMenuBar does derive from wxWindow. This is confusing, but the relationship between the classes is preserved for compatibility even if it's impossible to implement -- in particular, because there is no way to change the colours of a menu under macOS (or under Linux WMs using application menus), for example, so these wxWindow-inherited methods can never work in this class.
|
70,172,710 | 70,172,901 | Memory corruption when removing elements from a vector of shared pointers | I was dealing with a bothersome error yesterday involving a function meant to delete elements from a vector of shared pointers. Here's the problematic code:
template <typename T>
void flush(
std::vector<std::shared_ptr<T>>& offers
) {
std::vector<unsigned int> idxs;
for (unsigned int i = 0; i < offers.size(); i++) {
if (!offers[i]->is_available()) {
idxs.push_back(i);
}
}
for (unsigned int i : idxs) {
offers[i] = offers.back();
offers.pop_back();
}
}
Occasionally, elements of the offers vector would become corrupted (i.e. they would point to garbage data). I ended up changing the above code to use a more standard erase-remove idiom:
template <typename T>
void flush(
std::vector<std::shared_ptr<T>>& offers
) {
offers.erase(
std::remove_if(
offers.begin(),
offers.end(),
[](std::shared_ptr<T> offer) { return !offer->is_available(); }
),
offers.end()
);
}
Now I don't see the same problem as before (and this is more elegant in any case). However, I want to understand why this works when the previous code didn't. I suspect it has something to do with the wrong elements being retained in the vector or perhaps with something strange happening with the pointers' reference counting, but I would appreciate some insight into exactly what is going on here.
| Just posting a quick answer so this can be marked as resolved. The issue is the second loop: in order for the algorithm to work, the indices need to be sorted in descending order; otherwise we'll access out-of-bounds data. I believe the following should behave correctly:
template <typename T>
void flush(
std::vector<std::shared_ptr<T>>& offers
) {
std::vector<unsigned int> idxs;
for (int i = offers.size()-1; i >= 0; i--) {
if (!offers[i]->is_available()) {
idxs.push_back(i);
}
}
for (unsigned int i : idxs) {
offers[i] = offers.back();
offers.pop_back();
}
}
|
70,172,806 | 70,173,019 | Iterate over columns in C++ matrix | I want to iterate over single row and column in std::vector<std::vector<int>> matrix and get their sum.
I know that I can do this in nested loop, but here is my question. Can I use
int val_sum = 0;
std::for_each(matrix_[row].begin(),matrix_[row].end(),[&](int x) { val_sum += x;});
for columns and how to do that?
| The analogous way of your proposal is to iterate the matrix rows and accumulate the elements in the given column.
int val_sum = 0;
std::for_each(matrix.begin(),matrix.end(),[&](std::vector<int> &row) { val_sum += row[column];});
But I would still prefer to use the c++11 range-loop version
int val_sum = 0;
for ( const std::vector<int> &row : matrix )
val_sum += row[column];
|
70,172,898 | 70,173,312 | How to use gmock SaveArgPointee with with std::shared_ptr of derived class | I have a BaseMessage class from which I derive several different DerivedMessage subclasses and want to send them like this:
class BaseMessage {
public:
virtual std::vector<uint8_t> data() const noexcept = 0;
virtual ~BaseMessage() = default;
[...]
}
class DerivedMessage : public BaseMessage {
public:
[...]
std::vector<uint8_t> data() const noexcept override { return m_data; }
private:
std::vector<uint8_t> m_data;
}
// simplified
class Tcp {
public
virtual void sendMessage(std::shared_ptr<BaseMessage> msg) { write(msg->data());}
[...]
};
class SomeClass {
public:
SomeClass(Tcp& tcp) : m_tcp(tcp) {}
void writeDataToRemote(std::shared_ptr<DerivedMessage> derived) const {
m_tcp.sendMessage(derived);
private:
Tcp m_tcp;
}
};
Now I want to write tests for SomeClass with gtest.
Therefore I mock the function of the TCP class:
class MockTcp : public Tcp {
MOCK_METHOD(void, sendMessage, (std::shared_ptr<ralco::CommandMsg> msg), (override));
[...]
}
Let's assume that all is simplified up to here but works.
So in the test, I'd like to inspect the argument given to sendMessage in the function writeDataToRemote.
I read about ::testing::SaveArg and ::testing::SaveArgPointee on StackOverflow (but not in the documentation, though).
TEST(SomeClassTest, writesMessageToSocket){
MockTcp mockTcp;
SomeClass sc(mockTcp);
// >>>how to declare msgArg here?<<<
EXPECT_CALL(mockTcp, sendMessage(_)).Times(1).WillOnce(::testing::SaveArgPointee<0>(msgArg));
const auto derivedMsg = std::make_shared<DerivedMessage>();
sc.writeDataToRemote(derivedMsg);
// further inspection of msgArg follows
}
As written in the code comment, I don't know how to declare the msgArg variable so that it can be assigned the actual argument given to sendMessage. When using SaveArg I think I'd get a dangling pointer and doing it as above I get errors because the message cannot be copy-assigned. Any hints apreciated.
| In your case you actually want to just save and inspect the considered shared_ptr, so it is enough to use SaveArg:
MockTcp mockTcp;
SomeClass sc(mockTcp);
std::shared_ptr<BaseMessage> bm;
EXPECT_CALL(mockTcp, sendMessage(_)).Times(1).WillOnce(::testing::SaveArg<0>(&bm)); // it will effectively do bm = arg;
const auto derivedMsg = std::make_shared<DerivedMessage>();
sc.writeDataToRemote(derivedMsg);
// verify that the argument that you captured is indeed pointing to the same message
std::cout << derivedMsg.get() << std::endl;
std::cout << bm.get() << std::endl;
The common misunderstanding of SaveArgPointee is that it assigns value pointed by the arg to your local variable in test, which in your case maybe is not a good idea, because it would invoke a copy constructor of Message.
Alternatively I can recommend using Invoke. It is very generic and easy to use. You can e.g. capture the desired argument like that:
MockTcp mockTcp;
SomeClass sc(mockTcp);
std::shared_ptr<BaseMessage> bm;
EXPECT_CALL(mockTcp, sendMessage(_)).Times(1).WillOnce(::testing::Invoke([&bm](auto arg) { bm = arg; }));
const auto derivedMsg2 = std::make_shared<DerivedMessage>();
sc.writeDataToRemote(derivedMsg2);
std::cout << derivedMsg2.get() << std::endl;
std::cout << bm.get() << std::endl;
Or using a raw pointer to BaseMessage:
BaseMessage* rawBm = nullptr;
EXPECT_CALL(mockTcp, sendMessage(_)).Times(1).WillOnce(Invoke([&rawBm](auto arg) { rawBm = arg.get(); }));
const auto derivedMsg2 = std::make_shared<DerivedMessage>();
sc.writeDataToRemote(derivedMsg2);
std::cout << derivedMsg2.get() << std::endl;
std::cout << rawBm << std::endl;
|
70,172,941 | 70,173,056 | C99 designator member outside of aggregate initializer | struct Foo {
char a[10];
int b;
};
static Foo foo = {.a="bla"};
Compiling the above code gives the following gcc error:
$ gcc -std=gnu++2a test.cpp
C99 designator ‘a’ outside aggregate initializer
I thought that c-string designators in initializer list like these are ok in C++20? What am I missing? I am using gcc version 10.
| This is a known bug with GCC: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55227
Unfortunately, you will have to either not use designated initializers or use a different initializer for the array:
static Foo foo = {"bla"};
static Foo foo = {.a={'b', 'l', 'a', 0}};
|
70,173,395 | 70,173,987 | C++ Win socket sleep bug? | I've got a little problem with sending file with TCP to downloaded server. I spend couple of hours to find what is the problem but still I can't find the reason why it doesn't work.
The main problem is when i'm trying to send a file. Program got number of bytes of my file also read the file and passes through the condition in a loop, but it only sometimes send the file. While i run it by debugger the program always send all the files. Also the problem disappear when i use sleep() for 1 second.
#include <iostream>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <string>
#pragma comment(lib, "ws2_32.lib")
#include <windows.h>
int main()
{
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
SOCKET SendSocket;
SendSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (SendSocket < 0) {
perror("Error at socket: ");
return 1;
}
struct sockaddr_in myAddr;
memset(&myAddr, '\0', sizeof myAddr);
myAddr.sin_family = AF_INET; //IP4
myAddr.sin_port = htons(2000);
inet_pton(AF_INET, "127.0.0.1", &(myAddr.sin_addr));
memset(myAddr.sin_zero, '\0', sizeof myAddr.sin_zero);
if (connect(SendSocket, (struct sockaddr*)&myAddr, sizeof(myAddr)) < 0)
{
perror("Error at connect: ");
return 1;
}
char buffer[512];
const char fileName[] = "test.txt";
FILE* fd;
if (errno_t a = fopen_s(&fd, fileName, "rb") != 0) {
perror("File not opened:");
return 1;
}
size_t bytes_read = 0;
size_t test = 0;
while (!feof(fd)) {
do {
if ((bytes_read = fread(buffer, 1, sizeof(buffer), fd)) < 0)
{
std::cout << "while error";
break;
}
else
{
//Sleep(1000);
if ((test = send(SendSocket, buffer, bytes_read, 0)) < 0) {
perror("Error send");
return 1;
}
//std::cout << "while send" << std::endl;
}
} while (test != bytes_read);
}
fclose(fd);
WSACleanup(); //clinap
system("PAUSE");
}
| Your code is broken. send returns the number of bytes sent, and it can be less than bytes_read. But the loop while (test != bytes_read) throws away the buffer contents and fills it with a new fread.
You could change it to call send in a nested loop until the entire buffer is sent but that will be inefficient with regard to TCP framing - for best performance need to combine fread and send in the same loop.
Also about framing - your buffer is too small (512), the recommended send size is 1500 (the typical max MTU).
Also note: your fread error handling is broken. In Win32 fread return value is unsigned, so it will never be < 0.
It should be something like this (untested):
char buffer[8192];
int bytes_in_buffer = 0;
for (;;) {
if (bytes_in_buffer < sizeof(buffer) / 2) {
int bytes_read = (int)fread(buffer + bytes_in_buffer, 1, sizeof(buffer) - bytes_in_buffer, fd);
if (bytes_read == 0) {
if (ferror(fd)) {
perror("fread");
return 1;
}
// at EOF now but continue
}
bytes_in_buffer += bytes_read;
}
if (bytes_in_buffer == 0) {
break; // all data is sent - done
}
int bytes_sent = send(SendSocket, buffer, bytes_in_buffer, 0);
if (bytes_sent < 0) {
perror("send");
return 1;
}
bytes_in_buffer -= bytes_sent;
if (bytes_in_buffer > 0 && bytes_sent > 0) {
memmove(buffer, buffer + bytes_sent, bytes_in_buffer);
}
}
A possible improvement here is to use a ring buffer so as to reduce copying.
|
70,173,952 | 70,182,830 | <Package>Config.cmake for a library package | We equipped a library package with a *Config.cmake file, following step 11 of the CMake tutorial. Yet our downstream software fails to find the library.
Our package is called "formfactor" [https://jugit.fz-juelich.de/mlz/libformfactor]. It provides a shared library (libformfactor) and some header files.
Our downstream code uses
find_package(formfactor REQUIRED CONFIG)
message(STATUS "formfactor: found=${formfactor_FOUND}, include_dirs=${formfactor_INCLUDE_DIR}, "
"lib=${formfactor_LIBRARY}, version=${formfactor_VERSION}")
to search for the library. Alas, it prints
formfactor: found=1, include_dirs=/usr/local/include, lib=, version=0.1
That is, it does not find the library, yet fails to raise a fatal error though we said "REQUIRED".
Package "formfactor" contains all the following:
CMakeLists.txt:
cmake_minimum_required(VERSION 3.6 FATAL_ERROR)
project(formfactor VERSION 0.1.1 LANGUAGES CXX)
if(NOT DEFINED BUILD_SHARED_LIBS)
option(BUILD_SHARED_LIBS "Build as shared library" ON)
endif()
option(WERROR "Treat warnings as errors" OFF)
add_subdirectory(ff)
install(EXPORT formfactorTargets
FILE formfactorTargets.cmake
DESTINATION cmake
)
include(CMakePackageConfigHelpers)
configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in
"${CMAKE_CURRENT_BINARY_DIR}/formfactorConfig.cmake"
INSTALL_DESTINATION cmake
NO_SET_AND_CHECK_MACRO
NO_CHECK_REQUIRED_COMPONENTS_MACRO
)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/formfactorConfigVersion.cmake"
VERSION "${formfactor_VERSION_MAJOR}.${formfactor_VERSION_MINOR}"
COMPATIBILITY AnyNewerVersion
)
install(FILES
${PROJECT_BINARY_DIR}/formfactorConfig.cmake
${PROJECT_BINARY_DIR}/formfactorConfigVersion.cmake
DESTINATION cmake)
export(EXPORT formfactorTargets
FILE ${CMAKE_CURRENT_BINARY_DIR}/formfactorTargets.cmake
)
Config.cmake.in:
set(formfactor_INCLUDE_DIR @CMAKE_INSTALL_PREFIX@/include)
include(${CMAKE_CURRENT_LIST_DIR}/formfactorTargets.cmake)
ff/CMakeLists.txt:
set(lib formfactor)
set(${lib}_LIBRARY ${lib} PARENT_SCOPE)
file(GLOB src_files *.cpp)
set(api_files Polyhedron.h PolyhedralTopology.h PolyhedralComponents.h)
add_library(${lib} ${src_files})
target_include_directories(${lib}
PUBLIC
$<BUILD_INTERFACE:${CMAKE_SOURCE_DIR}>
$<INSTALL_INTERFACE:include>
)
set_target_properties(
${lib} PROPERTIES
OUTPUT_NAME ${lib}
VERSION ${formfactor_VERSION}
SOVERSION ${formfactor_VERSION_MAJOR})
install(
TARGETS ${lib}
EXPORT formfactorTargets
LIBRARY DESTINATION lib
RUNTIME DESTINATION lib
ARCHIVE DESTINATION lib)
install(
FILES ${api_files}
DESTINATION include/ff)
Anything wrong? Anything missing? Why else doesn't it work?
Disclosure:
Cross-posting from https://discourse.cmake.org/t/find-package-config-mode-wont-find-library/4573.
I have seen the related discussion Create CMake/CPack <Library>Config.cmake for shared library. Here I am interested in a solution that does all the automatic file generation recommended in the CMake tutorial.
| The script formfactorTargets.cmake, generated by CMake via
install(EXPORT formfactorTargets
FILE formfactorTargets.cmake
DESTINATION cmake
)
defines only targets, which has been added to the export set with that name (formfactorTargets).
Since you have added only a single library to it
set(lib formfactor)
...
install(
TARGETS ${lib}
EXPORT formfactorTargets
LIBRARY DESTINATION lib
RUNTIME DESTINATION lib
ARCHIVE DESTINATION lib)
the script defines only a library target formfactor.
Linking with that target is the "modern" usage of find_package results:
# downstream
find_package(formfactor REQUIRED CONFIG)
target_link_libraries(<my executable> PUBLIC formfactor)
It is up to your Config.cmake.in script (which will be installed as formfactorConfig.cmake, that is read by the find_package(formfactor)) to provide additional information for your package and/or its additional usage.
E.g. you could set variables formfactor_INCLUDE_DIRS and formfactor_LIBRARIES
so a downstream could use your library via "old way", assuming variable formfactor_INCLUDE_DIR to contain include directories and variable formfactor_LIBRARIES to contain a library file(s) which are needed to link with:
find_package(formfactor REQUIRED CONFIG)
include_directories(${formfactor_INCLUDE_DIRS})
add_executable(my_exe <sources>)
target_link_libraries(my_exe PUBLIC ${formfactor_LIBRARIES})
It is quite difficult for you (as a package's developer) to provide absolute path to the library. But you could assign variable formfactor_LIBRARIES in a
way which "just works":
# Config.cmake.in
# Value of 'formfactor_INCLUDE_DIRS' is real: it contains the include directory.
set(formfactor_INCLUDE_DIRS @CMAKE_INSTALL_PREFIX@/include)
# Value of 'formfactor_LIBRARIES' is fake: it doesn't contain a library path.
# But linking with ${formfactor_LIBRARIES} will work, as it will link
# to the **target**, and CMake will extract a library path from it.
set(formfactor_LIBRARIES formfactor)
# In any case we need to include the export script generated by CMake:
# exactly this script defines 'formfactor' target.
include(${CMAKE_CURRENT_LIST_DIR}/formfactorTargets.cmake)
|
70,174,078 | 70,243,408 | Klockwork scan c++ Template value | > -Severity (Error)
> -ID(local): 1
> -Code: UNINIT.CTOR.MUST --> IPCAtomic()
> -Message: 'this->value' is not initialized in this constructor.
> -Details:
>
> 'this->value' is not initialized in this constructor.
>
> * CommunicationTypes.h:198: 'this->value' is used, but is
> uninitialized.
>
> * CommunicationTypes.h:198: List of instantiations (may be
> incomplete)
>
> * CommunicationTypes.h:198: <anonymous>::IPCAtomic< ,
> >::#constructor
>
> Current status 'Analyze'
This is the code I have, I also tried other options, but KW still produces the same error
template <typename T, typename SerializeAs = T>
class IPCAtomic : public IPCBundleIfc
{
typedef IPCAtomic<T, SerializeAs> MyType;
public:
T value;
IPCAtomic() : value(T())
{
}
IPCAtomic(T v) : value(v)
{
static_assert(!std::is_base_of<IPCBundleIfc, T>::value, "type parameter of this class can not derive from IPCBundleIfc");
}
virtual ~IPCAtomic() {}
operator T& ()
{
return value;
}
MyType& operator=(const T& v)
{
if (&v != &value)
{
value = v;
}
return *this;
}
bool operator==(const T& v) const
{
return value == v;
}
bool operator==(const MyType& v) const
{
return value == v.value;
}
Can you offer any solutions?
| To initialize templated member values, use list initialization instead of initializing from a default constructed object.
Like this :
IPCAtomic() :
value{}
{
}
// when initializing with a value use const T& this avoids
// unecessary copies. Also make constructors with one parameter
// explicit so they can't accidentaly be used as type conversions.
explicit IPCAtomic(const T& v) :
value{v}
{
}
// allow efficient initialization from temporaries
explicit IPCAtomic(T&& v) :
value{v}
{
}
|
70,174,189 | 70,174,368 | Iterate values of a map using range-based for loop | Recently I started using range-based for loop. I had a problem where I needed to sort a map by value and then check if value is smaller/larger then some other element/number. Can I do that with this loop?
for (auto& it : M){
// assign only a value to vector
}
This question would be the same if I had a vector of pairs, could I just check for second, if it is larger then some other element or number? All this using range-based for loop.
| From C++20, you can use views::values to get at the values of a std::map, or a vector<pair> for that matter:
for (auto v : m | std::views::values) // m is some map
// ...
demo
You can similarly get at the keys with views::keys.
|
70,174,971 | 70,180,806 | Merge Sort Code Not Giving Desired Output | I have just started to learn recursion. The problem is of merge sort, I was trying to solve it without breaking in two arrays so i am passing the start index (si) and end index (end).
#include <iostream>
using namespace std;
void inputArray(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
}
void printArray(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void mergeArray(int a[], int si, int end)
{
int mid = (si + end) / 2;
int size = end - si + 1;
int temp[size];
int index = 0, i = si, j = mid + 1;
while (i <= mid && j <= end)
{
if (a[i] <= a[j])
{
temp[index] = a[i];
index++;
i++;
}
else
{
temp[index] = a[j];
index++;
j++;
}
}
if (i > mid)
{
while (j <= end)
{
temp[index] = a[j];
index++;
j++;
}
}
if (j > end)
{
while (i <= mid)
{
temp[index] = a[i];
index++;
i++;
}
}
//Copying Content Of Temp Array Back To Original Array
int k=0;
for (i = si; i < size; i++)
{
a[i] = temp[k];
k++;
}
}
void mergeSort(int a[], int si, int end)
{
if (si >= end)
{
return;
}
int mid = (si + end) / 2;
mergeSort(a, si, mid);
mergeSort(a, mid + 1, end);
mergeArray(a, si, end);
}
int main()
{
int a[100];
int n;
cin >> n;
inputArray(a, n);
mergeSort(a, 0, n - 1);
printArray(a, n);
return 0;
}
Sorry For The Long Code, It fails for cases like: 6 5 4 3 (Array In Descending Order) but works for other case like 6 5 4 9
I am trying to debug this code since yesterday, can someone please help me
| Fixed It, Thank You Everyone!
#include <iostream>
using namespace std;
void inputArray(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
}
void printArray(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void mergeArray(int a[], int si, int end)
{
int mid = (si + end) / 2;
int size = end - si + 1;
int temp[size];
int index = 0;
int i = si;
int j = mid + 1;
while (i <= mid && j <= end)
{
if (a[i] <= a[j])
{
temp[index] = a[i];
index++;
i++;
}
else
{
temp[index] = a[j];
index++;
j++;
}
}
while (j <= end)
{
temp[index] = a[j];
index++;
j++;
}
while (i <= mid)
{
temp[index] = a[i];
index++;
i++;
}
index = 0;
for (i = si; i <= end; i++)
{
a[i] = temp[index];
index++;
}
}
void mergeSort(int a[], int si, int end)
{
if (si >= end)
{
return;
}
int mid = (si + end) / 2;
mergeSort(a, si, mid);
mergeSort(a, mid + 1, end);
mergeArray(a, si, end);
}
int main()
{
int a[100];
int n;
cin >> n;
inputArray(a, n);
mergeSort(a, 0, n - 1);
printArray(a, n);
return 0;
}
|
70,175,131 | 70,176,157 | Qt: how to implement a hash function for QColor? | I have a need to use std::pair<QColor, char> as a key of unordered_map. As for the pair, I know that there is boost functionality that can be used, but what about the color? Is it enough to just provide the hash template in the std namespace? If so, what would be the best attribute of the color to base the hash on to maximize the performance and minimize collisions? My first thought was about simple name(). If so
namespace std {
struct hash<Key>
{
std::size_t operator()(const Key& k) const {
return std::hash<std::string>()(k.name());
}
}
The code above is taken from C++ unordered_map using a custom class type as the key.
| What you propose will probably work (although you would have to convert the color name from QString to std::string), I would use the RGBA value of the color directly. It is a bit cheaper than having to go through the QString to std::string construction and hash calculation:
template<>
struct std::hash<QColor>
{
std::size_t operator()(const QColor& c) const noexcept
{
return std::hash<unsigned int>{}(c.rgba());
}
};
According to Qt's documentation, QRgb returned by QColor::rgba() is some type equivalent to unsigned int.
|
70,175,136 | 70,175,902 | Changing internal format causes texture to have incorrect parameters | I set up framebuffer texture on which to draw a scene on as follows:
glGenFramebuffers(1, &renderFBO);
glGenTextures(1, &renderTexture);
glBindTexture(GL_TEXTURE_2D, renderTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, W_WIDTH, W_HEIGHT, 0, GL_RGBA, GL_FLOAT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
int width, height;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
cout << "width: " << width << " height: " << height << endl;
glBindFramebuffer(GL_FRAMEBUFFER, renderFBO);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTexture, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
By validating width and height, they do indeed have the correct dimensions, 1024, 768.
Now I am trying to set up a second texture, to be used as a counter, meaning I am trying to count the occurences of every color value, by incrementing the appropriate texel in the texture. Since I am trying to count the colors, I use a 2D texture of size 256 x 3. In each cell I want a single unsigned integer, showing the number of times a specific color value has appeared up until that point. For instance, if the color (255,5,3) was encountered, I would to increment the numbers inside tex[255][0], tex[5][0], tex[3][0]
num_bins = 256;
GLuint* hist_data = new GLuint[num_bins * color_components]();
glGenTextures(1, &tex_output);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_output);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, 256, 3, 0, GL_RED, GL_UNSIGNED_INT, hist_data);
glBindImageTexture(0, tex_output, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI);
int width, height;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
cout << "width: " << width << " height: " << height << endl;
I used the sized and base internal format correspondence shown in the opengl specification. However when this code executes the output values are width=0, height=0. The input data doesn't seem to be the issue, because I tried providing NULL as the last argument and it still didn't work. What am I missing here?
EDIT:
Incrementation of the values in the texture is supposed to happen inside the following compute shader:
#version 450
layout(local_size_x = 1, local_size_y = 1) in;
layout(rgba32f, binding = 0) uniform image2D img_input;
layout(r32ui, binding = 1) uniform uimage2D img_output;
void main() {
// grabbing pixel value from input image
vec4 pixel_color = imageLoad(img_input, ivec2(gl_GlobalInvocationID.xy));
vec3 rgb = round(pixel_color.rgb * 255);
ivec2 r = ivec2(rgb.r, 0);
ivec2 g = ivec2(rgb.g, 1);
ivec2 b = ivec2(rgb.b, 2);
uint inc = 1;
imageAtomicAdd(img_output, r, inc);
imageAtomicAdd(img_output, g, inc);
imageAtomicAdd(img_output, b, inc);
}
| You get a GL_INVALID_OPERATION error, because the texture format argument doesn't correspond with the internal format of the texture. For an unsigned integral format you have to use GL_RED_INTEGER instead of GL_RED (see glTexImage2D):
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, 256, 3, 0, GL_RED, GL_UNSIGNED_INT, hist_data);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32UI, 256, 3, 0, GL_RED_INTEGER, GL_UNSIGNED_INT, hist_data);
I recommend using Debug Output, it saves a lot of time and lets you find such errors quickly.
|
70,175,614 | 70,175,875 | Does always int i{0} be faster then int i = 0? | int i{0}; //(1)
int i = 0; //(2)
Do I have correct understanding that in first case (1) the variable i will be created already with 0 as it's value, and in (2) it will be created without a value and then assigned a value 0, so (1) will always faster then (2)?
But seems like most(all?) modern compilers will still optimize (2) to be same as (1) under the hood?
| initializing variables with Brace Initialization performs additional checks at compile time (no effect on runtime). . Such as if you enter a float literal inside the curly braces it will throw an error. Initialization with the equal sign will be optimized by the compiler. Prefer brace initialization whenever possible. I hope that answers your question
|
70,175,635 | 70,175,879 | C++: Member function call forwarding using variadic data structure | I am trying to create a class (similar to std::tuple) which can hold a variable number of references to objects of different type and which can forward a call to a specific member function to all of its constituents. Here is an example:
// g++ Test7.C -std=c++17 -o Test7
#include <iostream>
struct P1 { void operator()(void) const { std::cout<<"P1 "; } };
struct P2 { void operator()(void) const { std::cout<<"P2 "; } };
struct P3 { void operator()(void) const { std::cout<<"P3 "; } };
template <class... EmitterList> struct Emitters
{
inline void operator()(void) const { std::cout<<std::endl; }
};
template <class Emitter, class... EmitterList>
class Emitters<Emitter, EmitterList...> : public Emitters<EmitterList...>
{
public:
using Base = Emitters<EmitterList...>;
Emitters(const Emitter & e, const EmitterList & ... eList)
: emitter(e), Base(eList...) {}
inline void operator()(void) const { emitter(); this->Base::operator()(); }
private:
const Emitter & emitter;
};
int main(void)
{
P1 p1;
P2 p2;
P3 p3;
Emitters e0; e0(); // works
//Emitters e1{p1}; e1(); // does not work
//Emitters e2{p1,p2}; e2(); // does not work
//Emitters e3{p1,p2,p3}; e3(); // does not work
return 0;
}
The expectation is that e1() would output "P1 \n" (calls p1()), e2() would output "P1 P2 \n" (calls p1(); p2()), and e3() would output "P1 P2 P3 \n" (calls p1(); p2(); p3();). But something is not right in the code: it compiles for e0 but not for the other cases. Could you please help me to understand what I am doing not right here and how to fix it?
Thank you very much for your help!
| It looks like you're trying to do partial specialization, and you're close. Rather than this
template <class... EmitterList> struct Emitters
{
inline void operator()(void) const { std::cout<<std::endl; }
};
Consider
template <class... Ts>
struct Emitters;
template <>
struct Emitters<> {
void operator()(void) const { std::cout<<std::endl; }
};
template <class Emitter, class... EmitterList>
class Emitters<Emitter, EmitterList...> : public Emitters<EmitterList...>
{
// Unmodified from your example ...
}
The first declaration here says "there's a thing called Emitters, but I'm not telling you what it is yet". It's an incomplete type definition. Then we define two cases: one with Emitters<> (the empty, base case), and one (the recursive case) for when we have at least one argument.
These classes will compile now, but they're inconvenient to use. Due to complexities in the language, constructor calls aren't as good as inferring template arguments as regular functions. So a line like this
Emitters e1{p1};
isn't good enough. We could be explicit
Emitters<P1> e1{p1};
but that's just a pointless level of verbosity. Instead, we can look to std::tuple, which has the same problem. The standard library defines a function std::make_tuple, which does nothing but call the tuple constructor. But since it's an ordinary function, we get template argument deduction.
template <typename... Ts>
Emitters<Ts...> make_emitters(const Ts&... args) {
return Emitters<Ts...>(args...);
}
Now we can make instances without specifying template arguments
Emitters e0 = make_emitters(); e0();
Emitters e1 = make_emitters(p1); e1();
Emitters e2 = make_emitters(p1,p2); e2();
Emitters e3 = make_emitters(p1,p2,p3); e3();
Now your example should work as intended.
One final note about your constructor. You should always list the base class constructor first, before any fields. Compiling with -Wall will warn you about this. The compiler is internally reordering them for you, so it's best practice to put them in the right order to begin with. Rather than
Emitters(const Emitter & e, const EmitterList & ... eList)
: emitter(e), Base(eList...) {}
consider
Emitters(const Emitter & e, const EmitterList & ... eList)
: Base(eList...), emitter(e) {} // Note: Base and emitter are switched
Complete example:
#include <iostream>
struct P1 {
void operator()(void) const {
std::cout << "P1 ";
}
};
struct P2 {
void operator()(void) const {
std::cout << "P2 ";
}
};
struct P3 {
void operator()(void) const {
std::cout << "P3 ";
}
};
template <class... Ts>
struct Emitters;
template <>
struct Emitters<> {
void operator()(void) const {
std::cout << std::endl;
}
};
template <class T, class... Ts>
struct Emitters<T, Ts...> : public Emitters<Ts...> {
public:
using Base = Emitters<Ts...>;
Emitters(const T& e, const Ts&... eList)
: Base(eList...), emitter(e) {}
void operator()(void) const {
emitter();
this->Base::operator()();
}
private:
const T& emitter;
};
template <typename... Ts>
Emitters<Ts...> make_emitters(const Ts&... args) {
return Emitters<Ts...>(args...);
}
int main(void) {
P1 p1;
P2 p2;
P3 p3;
Emitters e0 = make_emitters(); e0();
Emitters e1 = make_emitters(p1); e1();
Emitters e2 = make_emitters(p1,p2); e2();
Emitters e3 = make_emitters(p1,p2,p3); e3();
return 0;
}
|
70,175,652 | 70,175,769 | How to write else if as logical statement? | I want to write an if-else statement as a logical statement. I know that:
if (statement1){
b=c
}
else{
b=d
}
can be written as:
b=(statement1 && c)||(!statement1 && d)
But how do I write the following if-else statements as logical?:
if (statement1){
b=c
}
else if (statement2){
b=d
}
else{
b=e
}
I have thought of something like:
b=(statement1 && c)||(statement2 && d)||((!statement1&&!statement2) && e)
I'm sorry if there is already a post about this. I have tried, but couldn't find anything similar to my problem.
| As with all logical statement building, it'll be easiest to create a truth table here. You'll end up with:
+--+--+--------+
|s2|s1| result |
+--+--+--------+
| 0| 0| e |
+--+--+--------+
| 0| 1| c |
+--+--+--------+
| 1| 0| d |
+--+--+--------+
| 1| 1| c |
+--+--+--------+
So un-simplified, that'll be
(!s1 & !s2 & e) || (!s2 & s1 & c) || (s2 & !s1 & d) || (s1 & s2 & c)
This can be simplified by combining the two c results and removing the s2:
(!s1 & !s2 & e) || (s2 & !s1 & d) || (s1 & c)
(note that this will be faster in C++ and match the if statements closer with s1 & c as the first term. This will especially make a difference if evaluating any of these values will cause outside effects)
Note that what you built,
(statement1 && c)||(statement2 && d)||((!statement1&&!statement2) && e)
will function incorrectly if statement1 is true, c is false, and both statement2 and d are true (you'll get a result of true when you should have false).
|
70,175,970 | 70,176,116 | What is the type of a lambda expression for the compiler? | So, if we run the gdb on the following source code :
//...
auto myLambda1 = [&](int x){ printf("Hi, I got x=%d here\n",x);};
auto myLambda2 = [&](double y){ printf("Hi, I got y=%f here\n",y);};
//...
I will get :
(gdb) ptype myLambda1
type = struct <lambda(int)> {
}
(gdb) ptype myLambda2
type = struct <lambda(double)> {
}
So what is a lambda expression for a compiler? Why it's a struct
| The type of a lambda expression is a class type, but it has no name. The most important feature of the class is that it has a public operator() so that it can be used in a function-call expression syntax.
Tons of technical details are in the Standard section [expr.prim.lambda.closure], which begins with
The type of a lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type, called the closure type, whose properties are described below.
|
70,176,159 | 70,176,518 | Overload function/method with template argument | I want to overload a method, based only on template argument (which is a type), without passing any method arguments. For that, I use code like this (simplified, of course) in C++17:
template<typename T>
class C {
public:
auto f() const {
return f((T*) nullptr);
}
private:
int f(int *) const {
return 42;
}
std::string f(std::string *) const {
return "hello";
}
std::vector<char> f(std::vector<char> *) const {
return {'h', 'i'};
}
};
dump(C<int>().f());
dump(C<std::string>().f());
dump(C<std::vector<char>>().f());
, which outputs:
42
"hello"
std::vector{'h', 'i'}
I am not a professional C++ developer, and this way looks hack-ish to me. Is there a better way to overload method f without using pointers as helper arguments? Or is this a "normal" solution?
P.S.: I'm not bonded to any particular C++ version.
| (The comments on the question raise some valid questions about why you would have this. But just focusing on the question as asked.)
It is a bit hacky, but sometimes having an API function call an implementation function for technical reasons is a reasonable approach. One gotcha you might get into with that pattern is that pointers can automatically convert to other pointers: particularly T* to const T* and Derived* to Base*.
A rewrite using if constexpr (C++17 or later):
template <typename T>
T C<T>::f() const {
if constexpr (std::is_same_v<T, int>) {
return 42;
} else if constexpr (std::is_same_v<T, std::string>) {
// Note I changed the return type to T. If it's auto,
// this would need return std::string{"hello"} so you don't
// just return a const char*.
return "hello";
} else if constexpr (std::is_same_v<T, std::vector<char>>) {
return {'h', 'i'};
} else {
// Always false (but don't let the compiler "know" that):
static_assert(!std::is_same_v<T,T>,
"Invalid type T for C<T>::f");
}
}
No more worries about pointer conversions, and this gives you a nicer error message if T is an unhandled type.
A rewrite using constraints (C++20 or later):
template<typename T>
class C {
public:
int f() const requires std::is_same_v<T,int> {
return 42;
}
std::string f() const requires std::is_same_v<T,std::string> {
return "hello";
}
std::vector<char> f() const
requires std::is_same_v<T, std::vector<char>>
{
return {'h', 'i'};
}
};
Now if a bad type T is used, the class doesn't contain any member named f at all! That could be better for other templates which might try checking if x.f() is a valid expression. And if a bad type is used, the compiler error might list the overloads which were declared but discarded from the class.
|
70,176,567 | 70,177,536 | Why connect `QThread::finished` signal to `QObject::deleteLater`? | I read this in the Qt 5.15 documentation for QThread::finished:
When this signal is emitted, the event loop has already stopped running. No more events will be processed in the thread, except for deferred deletion events. This signal can be connected to QObject::deleteLater(), to free objects in that thread.
However, in another section of the documentation, it says that
Calling delete on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment [emphasis mine].
If I'm understanding this correctly, after QThread::finished is emitted, the event loop has already stopped running, and if no deferred deletion events exist (i.e. QObject::deleteLater hasn't been called), all objects in the thread should have finished processing events as well. So why bother using QObject::deleteLater for these objects instead of just manually deleting them? I have no problem with using QObject::deleteLater; I'm just making sure my understanding of Qt is correct.
| QObject::deleteLater in this case is essentially just erring on the side of caution. There's no reason you couldn't simply delete the objects if you're absolutely certain there's no chance the object will be accessed.
In practice though you'll save way more time simply using QObject::deleteLater and letting Qt take care of it for you, compared to the hassle of debugging some random-seeming crash during runtime or on exit because there happens to be an access to an object you manually deleted.
|
70,176,591 | 70,176,650 | Determine the longest word in a text input | How do I create a program where it reads in text from the user and then outputs the shortest and longest words and how many characters these words contain?
So far, I can only create a program that counts the number of words in the text.
int count_words {};
string word;
cout << "Type a text:" << endl;
while (cin >> word)
{
count_words++;
}
cout << "The text contains " << count_words << " words." << endl;
Can the loop be manipulated so that it determines the shortest and longest words?
| Simply declare a couple of string variables, and then inside the while loop you can assign word to those variables when word.size() is larger/smaller than the size() of those variable, eg:
size_t count_words = 0;
string word, longest_word, shortest_word;
cout << "Type a text:" << endl;
while (cin >> word)
{
++count_words;
if (word.size() > longest_word.size())
longest_word = word;
if (shortest_word.empty() || word.size() < shortest_word.size())
shortest_word = word;
}
cout << "The text contains " << count_words << " word(s)." << endl;
if (count_words > 0) {
cout << "The shortest word is " << shortest_word << "." << endl;
cout << "It has " << shortest_word.size() << " character(s)." << endl;
cout << "The longest word is " << longest_word << "." << endl;
cout << "It has " << longest_word.size() << " character(s)." << endl;
}
Online Demo
Alternatively:
string word;
cout << "Type a text:" << endl;
if (cin >> word) {
size_t count_words = 1;
string longest_word = word, shortest_word = word;
while (cin >> word) {
++count_words;
if (word.size() > longest_word.size())
longest_word = word;
if (word.size() < shortest_word.size())
shortest_word = word;
}
cout << "The text contains " << count_words << " word(s)." << endl;
cout << "The shortest word is " << shortest_word << "." << endl;
cout << "It has " << shortest_word.size() << " character(s)." << endl;
cout << "The longest word is " << longest_word << "." << endl;
cout << "It has " << longest_word.size() << " character(s)." << endl;
}
else {
cout << "No text was entered." << endl;
}
Online Demo
|
70,176,780 | 70,177,121 | C++ Template specialization of member function with a generic type eg. std::vector<T> do not compile | I have a problem with specialization of a member function of a generic struct.
My goal is to specialize the member function Run of Bar with all kinds of std::vector.
#include <iostream>
#include <vector>
// (1) compile
template <typename T>
struct Foo {
T Run() {
std::cout << "Foo not specialized" << std::endl;
return T();
};
};
// (2) compile
template <typename T>
struct Foo<std::vector<T>> {
std::vector<T> Run() {
std::cout << "Foo specialized" << std::endl;
return std::vector<T>();
};
};
template <typename T> struct Bar
{
T Run();
};
// (3) compiles
template<typename T>
T Bar<T>::Run() {
std::cout << "Bar not specialized" << std::endl;
return T();
};
// (3) compiles
template<>
std::vector<bool> Bar<std::vector<bool>>::Run() {
std::cout << "Bar specialized" << std::endl;
return std::vector<bool>();
};
// (4) wont compile: error: invalid use of incomplete type 'struct Bar<std::vector<T> >
template<typename T>
std::vector<T> Bar<std::vector<T>>::Run() {
std::cout << "Bar specialized" << std::endl;
return std::vector<T>();
};
int main(int argc, char const *argv[]) {
Foo<bool> f1;
bool rf1 = f1.Run();
Foo<std::vector<int>> f2;
std::vector<int> rf2 = f2.Run();
Bar<bool> b1;
bool rb1 = b1.Run();
Bar<std::vector<bool>> b2;
std::vector<bool> rb2 = b2.Run();
Bar<std::vector<int>> b3;
std::vector<int> rb3 = b3.Run();
return 0;
};
it would not compile see (4) if i comment it out it work probably.
Is there a way to get this working. Thank you in advance.
Demo not compiling
Demo compiling
| Template functions cannot be a partially specialized.
You can do it with a trampoline and overloading. Like Run(){ DoRun(*this) then write DoRun overloads.
|
70,176,846 | 70,177,008 | How do I specify the size of a class in C++? | My task is to create a class that implements Floating point number.
The size of the class must be exactly 3 bytes:
1 bit for the sign
6 bits for exponent
17 bits for mantissa
I tried to implement the class using bit fields, but the size
is 4 bytes :
class FloatingPointNumber
{
private:
unsigned int sign : 1;
unsigned int exponent : 6;
unsigned int mantissa : 17;
};
| C++ (and C for that matter) compilers are permitted to insert and append any amount of padding into a struct as they see fit. So if your task specifies that it must be exactly 3 bytes, then this task can not be done with struct (or class) using just standard language elements.
Using compiler specific attributes or pragmas, you can force the compiler to not insert padding; however for bitfields the compiler still might see the need to fill up any gaps left to type alignment requirements.
For this specific task your best bet probably is to use a class like this
class CustomFloat {
protected: // or private: as per @paddy's comment
unsigned char v[3];
}
…and hoping for the compiler not to append some padding bytes.
The surefire way would be to simply to
typedef char CustomFloat[3];
and accept, that you'll not enjoy static type checking benefits whatsoever.
And then for each operation use a form of type punning to transfer the contents of v into a (at least 32 bit wide) variable, unpack the bits from there, perform the desired operation, pack the bits and transfer back into v. E.g. something like this:
uint32_t u = 0;
static_assert( sizeof(u) >= sizeof(v) );
memcpy((void*)&u, sizeof(v), (void const*)v);
unsigned sign = (u & SIGN_MASK) >> SIGN_SHIFT;
unsigned mant = (u & MANT_MASK) >> MANT_SHIFT;
unsigned expt = (u & EXPT_MASK) >> EXPT_SHIFT;
// perform operation
u = 0;
u |= (sign << SIGN_SHIFT) & SIGN_MASK;
u |= (mant << MANT_SHIFT) & MANT_MASK;
u |= (expt << EXPT_SHIFT) & EXPT_MASK;
memcpy((void*)v, sizeof(v), (void const*)&u);
Yes, this looks ugly. Yes, it is quite verbose. But that's what going to happen under the hood anyway, so you might just as well write it down.
|
70,177,177 | 70,177,380 | Catch c++ Access Violation exception | A c++ access violation error gets thrown at some part of my code. I would like to "catch" it and log the faulting line so I can investigate further.
I tried the first answer in this thread:
Catching access violation exceptions?
Unfortunately no luck so far. I am using debug mode in Visual Studio 2019. Anyone knows a way how to log the faulting line?
| On Windows, you can do it with __try ... __except, as in the following simplified example:
__try
{
* (int *) 0 = 0;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
std::cout << "Exception caught\n";
}
Microsoft call this mechanism 'structured exception handling' and it is much more powerful (and, indeed, usable) than signals on Unix and I encourage you to learn more about it if you want to do this kind of thing:
https://learn.microsoft.com/en-us/cpp/cpp/try-except-statement?view=msvc-170
I use it to catch exceptions in poorly behaved ASIO drivers which would otherwise crash my app.
|
70,177,472 | 70,177,502 | Why is #undef not working for my function? | I defined something at the beginning:
#define noprint
Then I returned in my functions if it's defined:
void print()
{
#ifdef noprint
return;
#else
//do stuff
#endif
}
Then in the main function:
main()
{
#undef noprint
print();
}
And it still doesn't work. How come?
| Macros are not variables. They are a simple text replacement tool. If you define, or undefine a macro, then that (un)definition has no effect on the source that precedes the macro. The function definition doesn't change after it has been defined.
Example:
#define noprint
// noprint is defined after the line above
void print()
{
#ifdef noprint // this is true because noprint is defined
return;
#else
//do stuff
#endif
}
main()
{
#undef noprint
// noprint is no longer after the line above
print();
}
After pre-processing has finished, the resulting source looks like this:
void print()
{
return;
}
main()
{
print();
}
P.S. You must give all functions a return type. The return type of main must be int.
|
70,177,526 | 70,177,553 | C++ UNIX Help - simple TCP server socket connection | I am a student writing a C++ code using UNIX system calls to perform simple server <-> client requests from the Terminal. The user (me) input in the port for both programs (Server and Client) in the Terminal to establish a connection, the goal is for the Server to send back to the Client the contents of what the Client program input in.
I.e:
Terminal 1:
./server 9000
Terminal 2:
./client localhost 9000 ~
Will show a list of all directories and files in Home.
Or
Terminal 2: ./client localhost 9000 test.txt
Will read contents from the test.txt file and write it onto the Client's terminal.
As of now, only folders work. Whenever I try a file instead, it prints a blank line. This is my code for the process function:
void processClientRequest(int connSock)
{
int received;
char path[1024], buffer[1024];
// Read from the client
if((received = read(connSock, path, sizeof(path))) < 0)
{ perror("receive"); exit(EXIT_FAILURE); }
// Check if it is a directory or a file
struct stat s;
if(stat(path,&s) == 0 )
{
// It is a directory
if(s.st_mode & S_IFDIR)
{
DIR *dirp = opendir(path);
if (dirp == 0)
{
// Tell client they gave the inappropriate input
// Duplicate socket descriptor into error output
// Then print it to client's end with perror to
// Give more in-depth details of the error to user
close(2);
dup(connSock);
perror(path);
exit(EXIT_SUCCESS);
}
struct dirent *dirEntry;
while((dirEntry = readdir(dirp)) != NULL)
{
// If statement to hides all files/folders that start with a dot
// Which are hidden files/folders
if(dirEntry->d_name[0] != '.')
{
strcpy(buffer, dirEntry->d_name);
strcat(buffer, "\n");
if(write(connSock, buffer, strlen(buffer)) < 0)
{ perror("write"); exit(EXIT_FAILURE); }
}
}
closedir(dirp);
close(connSock);
exit(EXIT_SUCCESS);
}
// It is a file
else if(s.st_mode & S_IFREG)
{
int fd = open(path, O_RDONLY);
if(fd < 0) { perror("open"); exit(EXIT_FAILURE); }
read(fd, buffer, strlen(buffer));
strcat(buffer, "\n");
if(write(connSock, buffer, strlen(buffer)) < 0)
{ perror("write"); exit(EXIT_FAILURE); }
close(fd);
}
// Not a file or directory
else
{
cout << "It is neither a file nor directory!" << endl;
exit(EXIT_FAILURE);
}
}
else
{
// Same explanation as line 95 - 98
close(2);
dup(connSock);
perror("stat");
exit(EXIT_SUCCESS);
}
close(connSock);
exit(EXIT_SUCCESS);
}
As a side question, how do I get it to accept/recognize a codeword before executing the process as well as the double quotes? As of now I can only use ./client ... pathname/"name with spaces" ; if I use ./client ... "pathname/name with spaces" it displays a stat: no such file or directory error.
For example:
./client localhost 4000 "GET pathname/filename"
| You problem is here:
else if(s.st_mode & S_IFREG)
{
int fd = open(path, O_RDONLY);
if(fd < 0) { perror("open"); exit(EXIT_FAILURE); }
read(fd, buffer, strlen(buffer)); << Change strlen(buffer)
strcat(buffer, "\n");
if(write(connSock, buffer, strlen(buffer)) < 0)
{ perror("write"); exit(EXIT_FAILURE); }
close(fd);
}
strlen(buffer) can be any value, because you are initializing buffer to 1024 bytes. The memory area is possibly being filled full of zeroes. strlen(buffer) would then be returning 0, because the first character is a null byte. Nothing is being written into the buffer because read will end up writing zero bytes.
|
70,177,686 | 70,181,913 | How to set text origin to be the center of sf::text in SFML? | I need to center a text object in SFML to the middle of the string rather than the top left corner. Thus far, I have tried this:
topTextObj.setOrigin( (float)topTextObj.getCharacterSize() / 2, (float)topTextObj.getCharacterSize() / 2);
However, this does not fix my issue, as the text is still top-left aligned.
| origin should be set to the center of text bounding rect:
sf::FloatRect rc = text.getLocalBounds();
text.setOrigin(rc.width/2, rc.height/2);
|
70,177,691 | 70,177,782 | Storing timepoints or durations | I want to make a simple editor to shift subtitle times around. A Subtitle of WebVTT is made of chunks like this:
1
00:02:15.000 --> 00:02:20.000
- Hello World!
So as you can see there is a time that the subtitle will apear and a time that it dissapears. This time is also can be clicked to jump to that specific point of the video file.
Now I want to create a simple application that can shift these times by a given amount to left or right in time domain. What would be the best way to store these timepoints for making easy calculation and changes?
For example:
struct SubtitleElement {
std::chrono< ?????? > begin; // What is a good candidate here?
std::chrono< ?????? > end; // What is a good candidate here?
std::string text;
}
Later I want to have functions that operate on these elements. E.g.:
void shiftTime(SubtitleElement element, int millisecs) {
// reduce begin and end of the element by millisecs
}
DURATION getDuration(SubtitleElement& element) {
//return end - begin
}
DURATION totalDuration(vector<SubtitleElement> elements) {
// sum all the durations of the elements in vector
}
So what would the most clean and modern way of doing this? Also important is that it will be easy to convert the string "hh:mm:ss:ZZZ" to that member. Please note that I think the hh can be much more than 24, because its amount of time, not time of the day! E.g. a vido file can be 120 hours long!!
| Since these are time points relative to the beginning of the video, not to some clock, I suggest keeping it simple and using std::chrono::milliseconds. They support all operations you require, except im not sure there is an existing implementation for parsing them from a string. But that should be very easy to build.
|
70,177,987 | 70,178,656 | Point Cloud Library Octree lib generating error | I get this error just by including the header file to my code.
I'm using visual studio 2019 and c++17, I've included the linker files and all but it doesn't want to work.
What could it be?
Error C4996 'std::iterator<std::forward_iterator_tag,const pcl::octree::OctreeNode,void,const pcl::octree::OctreeNode *,const pcl::octree::OctreeNode &>': warning STL4015: The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. (The header is NOT deprecated.) The C++ Standard has never required user-defined iterators to derive from std::iterator. To fix this warning, stop deriving from std::iterator and start providing publicly accessible typedefs named iterator_category, value_type, difference_type, pointer, and reference. Note that value_type is required to be non-const, even for constant iterators. You can define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING or _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have received this warning. TCC2 D:\dev\CMake\vcpkg\installed\x64-windows\include\pcl\octree\octree_iterator.h 71
| It is a warning for using deprecated code and Visual Studio treat it as error by default.
Go to project properties -> Configuration Properties -> C/C++ -> General -> SDL checks -> set to No. And it should be good.
|
70,178,194 | 70,178,221 | Error: initializer must be brace-enclosed | What does this error mean and why can't I initialise this struct with a braced initialiser list? Unfortunately the structs are auto-generated.
// Contains no functionality, purely documentative.
struct NativeTable {};
...
struct TableKeyT : public flatbuffers::NativeTable {
typedef TableKey TableType;
std::string exp{};
std::string type{};
std::string ext{};
};
...
TableKeyT key { std::string(sym), std::string(ex), std::string("") };
[build] ../../../src/io/socket.cpp:102:39: error: initializer for ‘flatbuffers::NativeTable’ must be brace-enclosed
[build] 102 | TableKeyT key { std::string(sym), std::string(ex), std::string("") };
[build] | ^~~
| Since TableKeyT inherits NativeTable, you also need to initialize the base class, but since it is an empty class, using {} should be fine.
TableKeyT key { {}, std::string(sym), std::string(ex), std::string("") };
//^^^
|
70,178,398 | 70,178,432 | Obtaining start position of istringstream token | Is there a way to find the start position of tokens extracted by istringstream::operator >>?
For example, my current failed attempt at checking tellg() (run online):
string test = " first \" in \\\"quotes \" last";
istringstream strm(test);
while (!strm.eof()) {
string token;
auto startpos = strm.tellg();
strm >> quoted(token);
auto endpos = strm.tellg();
if (endpos == -1) endpos = test.length();
cout << token << ": " << startpos << " " << endpos << endl;
}
So the output of the above program is:
first: 0 8
in "quotes : 8 29
last: 29 35
The end positions are fine, but the start positions are the start of the whitespace leading up to the token. The output I want would be something like:
first: 3 8
in "quotes : 13 29
last: 31 35
Here's the test string with positions for reference:
1111111111222222222233333
01234567890123456789012345678901234 the end is -1
first " in \"quotes " last
^--------------------^-----^ the end positions i get and want
^-------^--------------------^------ the start positions i get
^---------^-----------------^---- the start positions i *want*
Is there any straightforward way to retrieve this information when using an istringstream?
| First, see Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?
Second, you can use the std::ws stream manipulator to swallow whitespace before reading the next token value, then tellg() will report the start positions you are looking for, eg:
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
...
string test = " first \" in \\\"quotes \" last";
istringstream strm(test);
while (strm >> ws) {
string token;
auto startpos = strm.tellg();
if (!(strm >> quoted(token)) break;
auto endpos = strm.tellg();
if (endpos == -1) endpos = test.length();
cout << token << ": " << startpos << " " << endpos << endl;
}
Online Demo
|
70,178,437 | 70,178,467 | Segmentation Fault while getting input from 2D vector | I get a segmentation fault when I run the code below.
int main()
{
int R, C, val;
cin>>R>>C;
vector<vector<int>> a;
for(int i = 0; i < R; i++)
{
for(int j = 0; j < C; j++)
{
cin>>val;
a[i].push_back(val);
}
}
But when I change it to this, it seems to work. What is the reason?
int main()
{
int R, C, val;
cin>>R>>C;
vector<vector<int>> a;
for(int i = 0; i < R; i++)
{
vector<int>temp;
for(int j = 0; j < C; j++)
{
cin>>val;
temp.push_back(val);
}
a.push_back(temp);
}
I get the same fault no matter what the value of R and C is kept.
| You have never told what is the size of vector<vector<int>>, and you try to access a[i].
You have to resize the vector.
int main()
{
int R, C;
std::cin >> R >> C;
std::vector<std::vector<int>> a(R, std::vector<int>(C));
for(int i = 0; i < R; i++)
{
for(int j = 0; j < C; j++)
{
std::cin >> a[i][j]; //because we resize the vector, we can do this
}
}
}
|
70,178,477 | 70,178,506 | Cannot initialize a lambda member variable with a default argument | I would like to compile the code below with c++17, so that I can pass any function (lambda) that has a specific signature, int(int), while also allowing the default argument:
template <class F = int(int)> // for deduction
struct A{
A(F f = [] (int x){return x;}) : f_{f} {}
F f_;
};
int main() {
A work([](int x){return x + 1;});
A not_work; // compile error.
}
However, clang emits an error:
a.cpp:6:4: error: data member instantiated with function type 'int (int)'
F f_;
^
a.cpp:11:4: note: in instantiation of template class 'A<int (int)>' requested here
A not_work;
^
I don't understand why the member f_ can be initialized when I pass the lambda and the default lambda argument cannot be?
Meanwhile, is there any better way to do this?
| As the error message said, you can't declare a data member with a function type like int(int).
When passing a lambda to the constructor, the template parameter F would be deduced as the lambda closure type by CTAD (since C++17); when passing nothing F will use the default argument int(int) and the data member f_'s type would be int(int) too, which causes the error.
You might use a function pointer type (lambdas without capture could convert to function pointer implicitly) or std::function<int(int)>. E.g.
template <class F = int(*)(int)> // for deduction
struct A{
A(F f = [] (int x){return x;}) : f_{f} {}
F f_;
};
Or
template <class F = std::function<int(int)>> // for deduction
struct A{
A(F f = [] (int x){return x;}) : f_{f} {}
F f_;
};
|
70,178,554 | 70,178,649 | Qt: how can one close a window upon another window closed by the user | The following code snippet opens two windows, w1 and w2. How can one force w2 to close when w1 is closed by the user? As in the comment, the connect function is not working that way.
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w1;
w1.setWindowTitle("w1");
w1.show();
QWidget w2;
w2.setWindowTitle("w2");
w2.show();
// when w1 is closed by the user, I would like w2 to close, too.
// However, it won't happen, even though the code compiles fine.
QObject::connect(&w1, &QObject::destroyed, &w2, &QWidget::close);
return a.exec();
}
Edit In my case, those two widgets are designed in two separate libraries, so they cannot communicate with each other. Thus, the close event is not applicable.
Edit Eventually my solution to my problem is based on the answer by @JeremyFriesner: emit a closed signal in closeEvent of w1, and connect this (instead of QObject::destroyed) to w2.
| This modified version of your program shows how you could do it by overriding the closeEvent(QCloseEvent *) method on your w1 widget:
#include <QApplication>
#include <QtGui>
#include <QtCore>
#include <QtWidgets>
class MyWidget : public QWidget
{
public:
MyWidget(QWidget * closeHim) : _closeHim(closeHim)
{
// empty
}
virtual void closeEvent(QCloseEvent * e)
{
QWidget::closeEvent(e);
if (_closeHim) _closeHim->close();
}
private:
QWidget * _closeHim;
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w2;
w2.setWindowTitle("w2");
w2.show();
MyWidget w1(&w2);
w1.setWindowTitle("w1");
w1.show();
return a.exec();
}
If you wanted to do it more elegantly, you could have your closeEvent() method-override emit a signal instead of calling a method on a pointer; that way you wouldn't have a direct dependency between the two classes, which would give you more flexibility in the future.
|
70,178,758 | 70,180,682 | Dynamically create a SphereComponent in UnrealEngine | I'm trying to create a SphereComponent dynamically 2 seconds after the level is started. For that I have this following code:
void ACollidingPawnSpawnPawns::DelayedFunction() {
// The first parameter 'SphereComponent' is the main component in the level and it has been created using the CreateDefaultSubobject method in the constructor of this class. But that method can't be used outside the constructor.
USphereComponent *dynamicallyCreatedSphere = NewObject<USphereComponent>(SphereComponent, USphereComponent::StaticClass());
dynamicallyCreatedSphere ->InitSphereRadius(30.0f);
dynamicallyCreatedSphere ->SetCollisionProfileName(TEXT("Pawn"));
dynamicallyCreatedSphere ->SetRelativeLocation(FVector(155.0f, 165.0f, 45.0f));
dynamicallyCreatedSphere ->SetVisibility(true);
}
After I run the level I don't see this dynamic sphere pop up.
For the main 'SphereComponent' that does show up this code is in the constructor:
// Our root component will be a sphere that reacts to physics
SphereComponent = CreateDefaultSubobject<USphereComponent>(TEXT("RootComponent"));
RootComponent = SphereComponent;
SphereComponent->InitSphereRadius(40.0f);
SphereComponent->SetCollisionProfileName(TEXT("Pawn"));
// Create and position a mesh component so we can see where our sphere is
UStaticMeshComponent* SphereVisual = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualRepresentation"));
SphereVisual->SetupAttachment(RootComponent);
static ConstructorHelpers::FObjectFinder<UStaticMesh> SphereVisualAsset(TEXT("/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere"));
if (SphereVisualAsset.Succeeded())
{
SphereVisual->SetStaticMesh(SphereVisualAsset.Object);
SphereVisual->SetRelativeLocation(FVector(0.0f, 0.0f, -40.0f));
SphereVisual->SetWorldScale3D(FVector(0.8f));
}
But again I can't use the CreateDefaultSubobject to create the UStaticMeshComponent outside the constructor.
So I imagine for me to see my dynamicallyCreatedSphere in my level I would have to create a UStaticMeshComponentand I would need some variation of the FObjectFinder method to invoke (this FObjectFinder also doesn't work outside the constructor).
I've been stuck on this for a while now. Anyone know how to do this?
Update 2021-12-2
Thanks to advice from https://stackoverflow.com/a/70180682/4722577 below, here's the final code I have to create the sphere dynamically:
In the cpp file:
void ACollidingPawnSpawnPawns::spawnPawns()
{
if (dynamicallyCreatedSphere == nullptr) {
//dynamicallyCreatedSphere = NewObject<USphereComponent>(USphereComponent::StaticClass()); // compiles
dynamicallyCreatedSphere = NewObject<USphereComponent>(SphereComponent, USphereComponent::StaticClass());
//dynamicallyCreatedSphere->SetupAttachment(SphereComponent);
dynamicallyCreatedSphere->InitSphereRadius(30.0f);
dynamicallyCreatedSphere->SetCollisionProfileName(TEXT("Pawn"));
dynamicallyCreatedSphere->SetRelativeLocation(FVector(155.0f, 165.0f, 45.0f));
dynamicallyCreatedSphere->SetVisibility(true);
dynamicMesh = NewObject<UStaticMeshComponent>(this);
dynamicMesh->AttachToComponent(dynamicallyCreatedSphere, FAttachmentTransformRules::KeepWorldTransform);
dynamicMesh->RegisterComponent();
dynamicMesh->SetStaticMesh(StaticMesh);
}
}
in the .h file I have these 3 lines:
UPROPERTY(EditAnywhere)
UStaticMesh* StaticMesh;
USphereComponent* dynamicallyCreatedSphere = nullptr;
UStaticMeshComponent* dynamicMesh = nullptr;
Declaring the StaticMesh as a UProperty allows me to select the mesh manually in the UE interface. Then when I run the level that StaticMesh is inserted into the dynamicMesh variable.
| First, only NewObject can be used to create components outside of constructor:
void ACollidingPawnSpawnPawns::DelayedFunction()
{
// you should specify outer as current actor (because this component is part of it)
USphereComponent* DynamicallyCreatedSphere = NewObject<USphereComponent>(this, USphereComponent::StaticClass());
DynamicallyCreatedSphere->RegisterComponent();
// when component is dynamically created, you can use AttachToComponent, not SetupAttachment
DynamicallyCreatedSphere->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform);
DynamicallyCreatedSphere->InitSphereRadius(30.0f);
DynamicallyCreatedSphere->SetCollisionProfileName(TEXT("Pawn"));
DynamicallyCreatedSphere->SetRelativeLocation(FVector(155.0f, 165.0f, 45.0f));
DynamicallyCreatedSphere->SetVisibility(true);
}
Instead of FObjectFinder you can use LoadObject to load something using specified path. But I think this is incovinent way, because ref is hardcoded.
Use following code in UCLASS instead:
UPROPERTY(EditAnywhere)
UStaticMesh* StaticMesh;
And specify static mesh directly: SphereVisual->SetStaticMesh(StaticMesh);
After that you can inherit C++ class to blueprint and pick StaticMesh from Content Browser.
|
70,179,190 | 70,179,392 | enum class with scoping but without having to cast to underlying type | I have this:
enum class Categories : uint32_t {
C6 = 0x00000020,
C7 = 0x00000040,
C8 = 0x00000080,
...
};
I chose an enum class because it is great for scoping. But the downside is that when I need to use the categories as mask bits for bitwise operations I need to cast them to uint32_t first.
Example:
uint32_t masterCat = ((uint32_t)MyClass::Categories::C6) | ((uint32_t)MyClass::Categories::C7);
Is there a way I can get the same scoping benefit, without having to cast before using each time ? If I use a regular enum, then I lose the scoping benefit :(
Example:
uint32_t masterCat = (MyClass::Categories::C6) | (MyClass::Categories::C7);
| Split the enum class into an enum and a class (or struct for convenience).
struct Categories {
enum : uint32_t {
C6 = 0x00000020,
C7 = 0x00000040,
C8 = 0x00000080,
};
};
Since the enum is an embedded type, you need to specify Categories to access it, as in Categories::C6.
If this is inside another class, such as
class MyClass {
public:
struct Categories {
enum : uint32_t {
C6 = 0x00000020,
C7 = 0x00000040,
C8 = 0x00000080,
};
};
};
then you can use MyClass::Categories::C6 to refer to one of the enumerates, but neither MyClass::C6 nor C6 will work.
|
70,179,351 | 70,181,124 | How to write this floating point code in a portable way? | I am working on a cryptocurrency and there is a calculation that nodes must make:
average /= total;
double ratio = average/DESIRED_BLOCK_TIME_SEC;
int delta = -round(log2(ratio));
It is required that every node has the exact same result no matter what architecture or stdlib being used by the system. My understanding is that log2 might have different implementations that yield very slightly different results or flags like --ffast-math could impact the outputted results.
Is there a simple way to convert the above calculation to something that is verifiably portable across different architectures (fixed point?) or am I overthinking the precision that is needed (given that I round the answer at the end).
EDIT: Average is a long and total is an int... so average ends up rounded to the closest second.
DESIRED_BLOCK_TIME_SEC = 30.0 (it's a float) that is #defined
| For this kind of calculation to be exact, one must either calculate all the divisions and logarithms exactly -- or one can work backwards.
-round(log2(x)) == round(log2(1/x)), meaning that one of the divisions can be turned around to get (1/x) >= 1.
round(log2(x)) == floor(log2(x * sqrt(2))) == binary_log((int)(x*sqrt(2))).
One minor detail here is, if (double)sqrt(2) rounds down, or up. If it rounds up, then there might exist one or more value x * sqrt2 == 2^n + epsilon (after rounding), where as if it would round down, we would get 2^n - epsilon. One would give the integer value of n the other would give n-1. Which is correct?
Naturally that one is correct, whose ratio to the theoretical mid point x * sqrt(2) is smaller.
x * sqrt(2) / 2^(n-1) < 2^n / (x * sqrt(2)) -- multiply by x*sqrt(2)
x^2 * 2 / 2^(n-1) < 2^n -- multiply by 2^(n-1)
x^2 * 2 < 2^(2*n-1)
In order of this comparison to be exact, x^2 or pow(x,2) must be exact as well on the boundary - and it matters, what range the original values are. Similar analysis can and should be done while expanding x = a/b, so that the inexactness of the division can be mitigated at the cost of possible overflow in the multiplication...
Then again, I wonder how all the other similar applications handle the corner cases, which may not even exist -- and those could be brute force searched assuming that average and total are small enough integers.
EDIT
Because average is an integer, it makes sense to tabulate those exact integer values, which are on the boundaries of -round(log2(average)).
From octave: d=-round(log2((1:1000000)/30.0)); find(d(2:end) ~= find(d(1:end-1))
1 2 3 6 11 22 43 85 170 340 679 1358 2716
5431 10862 21723 43445 86890 173779 347558 695115
All the averages between [1 2( -> 5
All the averages between [2 3( -> 4
All the averages between [3 6( -> 3
..
All the averages between [43445 86890( -> -11
int a = find_lower_bound(average, table); // linear or binary search
return 5 - a;
No floating point arithmetic needed
|
70,179,422 | 70,179,671 | OpenGL texture function always return 0 on integer data | I'm working on a deferred shading pipeline, and i stored some information into a texture, and this is the texture attached to my gbuffer
// objectID, drawID, primitiveID
glGenTextures(1, &_gPixelIDsTex);
glBindTexture(GL_TEXTURE_2D, _gPixelIDsTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32UI, _width, _height, 0, GL_RGB_INTEGER, GL_UNSIGNED_INT, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
And this is how i write IDs into it:
// some other gbuffer textures...
layout (location = 4) out uvec3 gPixelIDs;
gPixelIDs = uvec3(objectID, drawID, gl_PrimitiveID + 1);
After the geometry pass, i can read from it using the following code:
struct PixelIDs {
GLuint ObjectID, DrawID, PrimitiveID;
}pixel;
glBindFramebuffer(GL_READ_FRAMEBUFFER, _gBufferFBO);
glReadBuffer(GL_COLOR_ATTACHMENT4);
glReadPixels(x, y, 1, 1, GL_RGB_INTEGER, GL_UNSIGNED_INT, &pixel);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
So far, so good. The output is what i need.
But when i try to use this shader to display the object id on the screen(just for debug purpose)
uniform sampler2D gPixelIDsTex;
uint objID = uint(texture(gPixelIDsTex, fragData.TexCoords).r);
FragColor = vec4(objID, objID, objID, 1);
the result is 0 (I used the Snipaste to read the pixel color), which means i cant use the data in my following process.
Other gbuffer textures with data format in floating point (eg. vec4) all be fine, so i dont know why texture always return 0 on it
|
uniform sampler2D gPixelIDsTex;
Your texture is not a floating-point texture. It's an unsigned integer texture. So your sampler declaration needs to express that. Just as you write to a uvec3, so too must you read from a usampler2D.
|
70,179,604 | 70,187,736 | Extracting the edges of odd degree vertices in a graph | I have a graph as follows, represented by an adjacency matrix MyCustomVector<MyCustomVector<int>> graph:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 0 1 1 INF INF INF INF INF INF INF INF INF INF INF INF
2 1 0 1 1 1 INF INF INF INF INF INF INF INF INF INF
3 1 1 0 INF INF 1 INF INF INF INF INF INF INF INF INF
4 INF 1 INF 0 1 INF INF INF 1 INF INF INF INF INF INF
5 INF 1 INF 1 0 1 INF INF INF 1 1 INF INF INF INF
6 INF INF 1 INF 1 0 1 INF 1 1 INF 1 INF INF INF
7 INF INF INF INF INF 1 0 1 INF INF INF INF 1 1 1
8 INF INF INF INF INF INF 1 0 INF INF INF INF INF INF 1
9 INF INF INF 1 INF 1 INF INF 0 INF INF INF INF INF INF
10 INF INF INF INF 1 1 INF INF INF 0 INF INF INF INF INF
11 INF INF INF INF 1 INF INF INF INF INF 0 1 INF INF INF
12 INF INF INF INF INF 1 INF INF INF INF 1 0 INF INF INF
13 INF INF INF INF INF INF 1 INF INF INF INF INF 0 1 INF
14 INF INF INF INF INF INF 1 INF INF INF INF INF 1 0 1
15 INF INF INF INF INF INF 1 1 INF INF INF INF INF 1 0
The leftmost and topmost column and row just represent the # node. I thought it was easier to see. All edges are undirected and have a weight of one. INF indicates that there node A and node B do not share a singular edge.
I can calculate all of the odd degree vertices, which are { 3 4 5 7 14 15 } and they are contained in a vector that I have MyCustomVector<int> oddVertices. What I want to do is build a subgraph of this graph with only these vertices and their edges, so something like this.
0 3 4 5 7 14 15
3 0 INF INF INF INF INF
4 INF 0 1 INF INF INF
5 INF 1 0 INF INF INF
7 INF INF INF 0 1 1
14 INF INF INF 1 0 1
15 INF INF INF 1 1 0
So that I can run the Floyd Warshall Algorithm on this graph and get
0 3 4 5 7 14 15
3 0 2 2 2 3 3
4 2 0 1 3 4 4
5 2 1 0 2 1 1
7 2 3 2 0 1 1
14 3 4 3 1 0 1
15 3 4 3 1 1 0
I am having trouble managing the adjacency matrix and grabbing the columns that I need. Essentially what I want to do is
Iterate through the graph
Notice that the node we are currently on is contained in oddVertices
Add the other nodes that are contained in oddVertices.
I cannot use any other data structure than MyCustomVector, and it only has basic functionality like [], size(), pop_back() and push_back().
| Simply extract the rows and columns corresponding to the subset of indices:
using std::vector;
/*
** input:
** adjacency list adj
** subset of node indices v
** output:
** adj list of induced subgraph subadj
*/
vector<vector<int>> get_subgraph(vector<vector<int>> const &adj, vector<int> const &v)
{
vector<vector<int>> subadj(v.length(), vector<int>(v.length()));
for (unsigned int i = 0; i < v.size(); ++i)
for (unsigned int j = 0; j < v.size(); ++j)
{
subadj[i][j] = adj[v[i]][v[j]];
}
return subadj;
}
|
70,179,854 | 70,182,042 | longest increasing subsequence wrong answer | I wrote a recursive solution for the longest increasing subsequence and it worked perfectly fine. But when I applied dp on the same code it gives different answers.
Problem Link: https://practice.geeksforgeeks.org/problems/longest-increasing-subsequence-1587115620/1
Recursive code:
int LISrecursive(int arr[], int n, int currIndex, int maxVal) {
if (currIndex == n) {
return 0;
}
int included = 0, notIncluded = 0;
if (arr[currIndex] > maxVal) {
included = 1 + LISrecursive(arr, n, currIndex + 1, arr[currIndex]);
}
notIncluded = LISrecursive(arr, n, currIndex + 1, maxVal);
return max(notIncluded, included);
}
DP Code:
int LISdp(int arr[], int n, int currIndex, int maxVal, vector<int> &dp) {
if (currIndex == n) {
return 0;
}
if (dp[currIndex] != -1) return dp[currIndex];
int included = 0, notIncluded = 0;
if (arr[currIndex] > maxVal) {
included = 1 + LISdp(arr, n, currIndex + 1, arr[currIndex], dp);
}
notIncluded = LISdp(arr, n, currIndex + 1, maxVal, dp);
return dp[currIndex] = max(notIncluded, included);
}
int32_t main() {
int n;
cin >> n;
int arr[n];
vector<int> dp(n, -1);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << LISrecursive(arr,n,0,-1);
cout << LISdp(arr, n, 0 , -1, dp);
return 0;
}
I cannot figure out what I did wrong?
For this test case
6 (n)
6 3 7 4 6 9 (arr[])
Recursive code gives 4 answer(correct)
But DP code gives 3 answer(incorrect)
| When I think of dynamic programming, I usually break it down into two steps:
Solve the recursion with "including the current element before recursing
again" compared to "not including the current element before recursing again". This is exactly what you did with your recursive solution.
Take the recursive solution from step 1 and add a cache of previous computed results to avoid repetitive recursion. The cache, can be conceptualized as a multidimension matrix that maps all the non-const variable parameters passed to the recursive function to the final result.
In your case, each recursive step has two variables, currIndex, and maxVal. a and n are actually constants throughout the entire recursion. The number of non-const parameters of the recursive step is the number of dimensions in your cache. So you need a two dimensional table. We could use a big 2-d int array, but that would take a lot of memory. We can achieve the same efficiency with a nested pair of hash tables.
Your primary mistake is that your cache is only 1 dimension - caching the result compared to currIndex irrespective of the value of maxVal. The other mistake is using a vector instead of a hash table. The vector technique you have works, but doesn't scale. And when we add a second dimension, the scale in terms of memory use are even worse.
So let's defined a cache type as an unordered_map (hash table) that maps currIndex to another hash table that maps maxVal to the result of the recursion. You could also use tuples, but the geeksforgeeks coding site doesn't seem to like that. No bother, we can just define this:
typedef std::unordered_map<int, std::unordered_map<int, int>> CACHE;
Then your DP solution is effectively just inserting a lookup into the CACHE at the top of the recursive function and an insertion into the CACHE at the bottom of the function.
int LISdp(int arr[], int n, int currIndex, int maxVal, CACHE& cache) {
if (currIndex == n) {
return 0;
}
// check our cache if we've already solved for currIndex and maxVal together
auto itor1 = cache.find(currIndex);
if (itor1 != cache.end())
{
// itor1->second is a reference to cache[currIndex]
auto itor2 = itor1->second.find(maxVal);
if (itor2 != itor1->second.end())
{
// itor2->second is a reference to cache[n][maxVal];
return itor2->second;
}
}
int included = 0, notIncluded = 0;
if (arr[currIndex] > maxVal) {
included = 1 + LISdp(arr, n, currIndex + 1, arr[currIndex], cache);
}
notIncluded = LISdp(arr, n, currIndex + 1, maxVal, cache);
// cache the final result into the 2-d map before returning
int finalresult = std::max(notIncluded, included);
cache[currIndex][maxVal] = finalresult; // cache the result
return finalresult;
}
Then the initial invocation with the input set to solve for is effectively passing INT_MIN as the intial maxVal and an empty cache:
int N = 16
int A[N]={0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15};
CACHE cache;
int result = LISdp(A, N, 0, INT_MIN, cache);
A minor optimization is to make a, n, and cache a member variable of the C++ class encapsulating your solution so that they don't have to be pushed onto the stack for each step of the recursion. The cache is getting passed by reference, so it's not that big of a deal.
|
70,179,958 | 70,180,096 | No matches converting function in C++ error | When I run the code snippet I get the following error.
error: no matches converting function ‘exp’ to type ‘struct std::complex (*)(struct std::complex)’. However when I call exp() inside main() passing a complex argument to it,it runs fine. Can somebody please help?
using namespace std;
complex<long double> testExp(complex<double>(*test_func)(complex<double>), complex<double> x) {
complex<double> result = test_func(x);
return result;
}
int main(int argc, char** argv)
{
constexpr complex<double> x = (5.0, 15.0);
complex<double> result = testExp(exp<complex<double>>, x);
complex<double> result1 = exp(x); /*This compiles fine */
cout<< result << " " << endl;
return 0;
}
| In the documentation, the prototype is complex<T> exp( const complex<T>& z ).
You should declare your function pointer as complex<double>(*test_func)(const complex<double>&).
Then, at the call site, use exp<double>.
The result of the function is complex<long double> but result is complex<double>, you should change its type to complex<long double> (or change the result of the function).
|
70,180,414 | 70,180,623 | My binary search function in c++ in Array is not working and I am not getting why | My code isn't working. The problem may be in the loop.I was trying to write c++ code for Binary Search and it just doesn't execute.In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.
#include <iostream>
#include <stdio.h>
using namespace std;
struct Array{
int A[20];
int length;
int size;
};
int BinarySearch(struct Array arr,int key) {
int low=0;
int high=arr.length-1;
int mid=(low+high)/2;
while(low<=high) {
if(key==arr.A[mid])
return mid;
else if(key<arr.A[mid])
high=mid-1;
else
low=mid+1;
}
return -1;
}
int main()
{
struct Array arr={{2,3,7,12,23,34,45,56,67,78,79,90,91,111,112,334,556,778,990,999},20,20};
cout<< BinarySearch(arr,7);
return 0;
}
| You do not adjust mid in the loop so it stays at the same index that you initialized it with.
Suggested change:
int BinarySearch(const Array& arr, int key) { // const&, no copy
int low = 0;
int high = arr.length - 1;
int mid;
while (low <= high) {
mid = (low + high) / 2; // assign mid inside the loop
if (key < arr.A[mid]) // Put the less than and greater than ...
high = mid - 1;
else if(arr.A[mid] < key) // ... comparisons first ...
low = mid + 1;
else
return mid; // ... and let equal be the last
}
return -1;
}
Putting the less than and greater than comparisons before the equal check is preferable for two reasons:
Equal is usually going to be false so making the other comparisons first is often more effective.
Equal comparisons don't work well with some types, like floating point types.
|
70,180,470 | 70,180,523 | Using static results in an undefined reference in this piece of code | This is a MSVP of a problem I am facing.
What is wrong with m_eventQueue being static in the code below ?
When it is not static, it compiles fine. I want it to be static because I am planning to use it in another class as well and it is a common queue between them.
This is the error I get
badri@badri-All-Series:~/progs$ g++ --std=c++11 inher3.cpp
/tmp/ccGTVi2d.o: In function `RecordingConfigJobStateSignal::RecordingConfigJobStateSignal(std::shared_ptr<EventQueue> const&)':
inher3.cpp:(.text+0x13c): undefined reference to `commonQueue::m_eventQueue'
collect2: error: ld returned 1 exit status
This is inher3.hpp
#include<iostream>
#include<memory>
#include<queue>
using namespace std;
class EventBase
{
public:
private:
int a;
};
using EventBasePtr = std::shared_ptr<EventBase>;
class SubscriptionManager
{
public:
int x;
};
class EventQueue
{
public:
explicit EventQueue( SubscriptionManager& ){};
~EventQueue();
private:
std::queue< EventBasePtr > m_queue;
};
using EventQueuePtr = std::shared_ptr<EventQueue>;
class commonQueue
{
public:
int *a;
static std::queue< EventBasePtr > m_queue;
static EventQueuePtr m_eventQueue;
};
class RecordingConfigJobStateSignal: public commonQueue
{
public:
int c;
RecordingConfigJobStateSignal( const EventQueuePtr &);
private:
int b;
};
This is inher3.cpp
#include<iostream>
#include"inher3.hpp"
RecordingConfigJobStateSignal::RecordingConfigJobStateSignal( const EventQueuePtr& eventQueue )//:m_eventQueue( eventQueue )
{
/* m_eventQueue is actually from class commonQueue */
m_eventQueue = eventQueue;
}
int main()
{
return 0;
}
| When you declare a static member in a class, C++ requires you to define the member outside of the class explicitly. Put this outside of your class in the .cpp file:
/*static*/
EventQueuePtr commonQueue::m_eventQueue;
|
70,180,495 | 70,181,240 | How can I fix c6385? | // Take last element from deck and add to dealer's hand
// Update current elements after
//Ensure the deck still has cards
if (deck.currentElements == 0) {
getNewDeck(deck);
shuffleDeck(deck);
}
deck.currentElements -= 1;
dealerCards.currentElements += 1;
dealerCards.Cards[dealerCards.currentElements] = deck.Cards[deck.currentElements];
// Update the deck array by decreasing size
// hence used cards are removed
Card* temp = deck.Cards;
deck.Cards = new Card[deck.currentElements];
for (int i = 0; i < deck.currentElements; i++) {
deck.Cards[i] = temp[i];
}
// Delete memory associated with temp
delete[] temp;
Hi, i am getting the following error on "deck.Cards[i] = temp[i];": C6385 Reading invalid data from 'deck.cards': the readable size is '(unsigned int)*64+4 bytes', but '128 bytes' may be used.
What am I doing wrong, and how can I fix this? The problem came up when I added the if statement seen at the top. Is there a chance that this could simply be a false warning? I am using visual studios
| dealerCards.Cards[dealerCards.currentElements] will not be assigned for dealerCards.Cards[0]; there will be a hole.
--deck.currentElements;
dealerCards.Cards[dealerCards.currentElements] = deck.Cards[deck.currentElements];
++dealerCards.currentElements;
This assumes that a valid index is in 0 .. (currentElements-1).
The error however is on the deck, but is probably of very similar code elsewhere.
As C level code is very basic (arrays) and error prone, better switch to higher types like vector.
|
70,180,548 | 70,180,635 | How to detect C-style multidimensional arrays in templates specialization? | I have the following code:
enum type_kind{unkown=-1,carray, multi_carray};
template<class T>
struct detect_carray{
constexpr static int kind=unkown;
};
template<class T, std::size_t N>
struct detect_carray<T[N]>{
constexpr static int kind=carray;
};
Now, I want to add another specialization for detecting multidimensional arrays in C-style, that is, T[a][b]....
What is the syntax to achieve this? Can I use Variadic templates?
I expect the following behavior:
int main()
{
std::cout<<detect_carray<std::vector<int>>::kind;//-1
std::cout<<detect_carray<int[3]>::kind;//0
std::cout<<detect_carray<double[3][5]>::kind;//1
std::cout<<detect_carray<std::complex<double>[3][5][8][16]>::kind;//1
//Correct out: -1011
}
| Just add a specialization for multidimensional arrays:
template<class T, std::size_t N1, std::size_t N2>
struct detect_carray<T[N1][N2]>{
constexpr static int kind=multi_carray;
};
then
std::cout<<detect_carray<std::vector<int>>::kind;//-1
std::cout<<detect_carray<int[3]>::kind;//0
std::cout<<detect_carray<double[3][5]>::kind;//1
std::cout<<detect_carray<std::complex<double>[3][5][8][16]>::kind;//1
LIVE
BTW: For double[3][5], T will be double (and N1 will be 3 and N2 will be 5). For std::complex<double>[3][5][8][16], T will be std::complex<double> [8][16] (and N1 will be 3 and N2 will be 5).
|
70,180,555 | 70,181,077 | Yet another how to create a C wrapper of a C++ class? | I'd like to create a C wrapper for a C++ library I wrote.
All the examples and SO's answers I found:
Using void, typedef void myhdl_t
How can I call a C++ function from C?
Trojan horse structure: struct mather{ void *obj; };
https://nachtimwald.com/2017/08/18/wrapping-c-objects-in-c/
# .h
struct mather;
typedef struct mather mather_t;
# .cpp
struct mather{
void *obj;
};
mather_t *mather_create(int start){
mather_t *m;
CPPMather *obj;
m = (typeof(m))malloc(sizeof(*m));
obj = new CPPMather(start);
m->obj = obj;
return m;
}
Deriving a struct from a C++ base class
https://github.com/jpakkane/cppapi
# .h
struct Foo;
#.cpp
struct Foo : public FooInternal {
using FooInternal::FooInternal;
};
struct Foo* foo_new() {
try {
return new Foo;
} catch(...) {
return nullptr;
}
}
My case:
I'd like to have an allocation C function like that:
int alloc_function(struct Foo** foo){
if (foo==nullptr)
return -EFAULT; // The user gives nullptr
if (*foo!=nullptr)
return -EFAULT; // already allocated
// error: Incompatible pointer types assigning to 'struct Foo *' from 'Foo *'
*foo = new Foo;
// No error but Clang-Tidy: Do not use static_cast to downcast from a base to a derived class
*foo = static_cast<struct Foo*>(new Foo);
return 0;
}
I understand Clang-Tidy isn't a compiler error but I still would like to do it the right way.
What's the best practice for writing a C-wrapper? Any real example?
|
My case:
I'd like to have an allocation C function like that:
int alloc_function(struct Foo** foo){
Foo is already a C++ type. Use a different one. Use a void * pointer.
struct CFoo {
void *pnt;
};
extern "C"
int alloc_function(struct CFoo* foo) {
if (!foo)
return -EINVAL; // That is no EFAULT, it's EINVAL.
try {
foo->pnt = reinterpret_cast<void*>(new Foo);
} ...
return 0;
}
|
70,181,531 | 70,181,578 | How to instantiated this ListNode struct in C++? | I am confused about the struct in Leetcode (Algorithm #2).
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
The first problem is I dont know how to instantiated an object by this struct,for example, I tried this to create a list 2 -> 4 -> 3:
int main(){
ListNode p1_1 = ListNode(2);
ListNode p1_2 = ListNode(4, &p1_1);
ListNode p1_3 = ListNode(3, &p1_2);
//ListNode_output(&p1_1);
return 0;
}
However, when I put it to my output function:
void ListNode_output(ListNode * list_input)
{
while(list_input){
cout << list_input->val << ' ';
list_input->next;
}
cout << endl;
}
it only output firstNode '2' endless, what is the main problem in my code. Besides, where can I check the manuscript of this struct, I mean why check node's value use 'ListNode->val', rather 'ListNode.val'?
Now, I follow some code that shows,
ListNode *l1_1 = new ListNode;
l1_1 -> val = 2;
l1_1 -> next = nullptr;
ListNode *l1_2 = new ListNode;
l1_2 -> val = 4;
l1_2 -> next = nullptr;
ListNode *l1_3 = new ListNode;
l1_3 -> val = 3;
l1_3 -> next = nullptr;
l1_1 -> next = l1_2;
l1_2 -> next = l1_3;
ListNode_output(l1_1);
and now, it can correctly show by ListNode_output function, but I am not sure if there is some more simple may can create list...
| The statement
list_input->next;
fetches the value of list_input->next and then does nothing with it.
You probably want:
list_input = list_input->next;
That will make list_input point to the next element in the list.
Also, how you create the list, the call ListNode_output(&p1_1) should be ListNode_output(&p1_3) to print the whole list (&p1_1 will point to the last node in the list).
To help visualize things like lists, use pencil and paper. When you create a node, draw a small box. When you create a pointer or a link from one node to another, draw an arrow. When you modify a pointer or a link then erase and redraw the arrow. If you do that then you will see why ListNode_output(&p1_1) is wrong.
|
70,181,611 | 70,261,388 | C1047 The object or library file '' was created by a different version of the compiler | I am migrating VC++ project from VisualStudio2015 to VisualStudio2019.
One of the project reporting below error,
Error C1047 The object or library file 'Library Path' was created by a different version of the compiler than other objects like 'Object file path'; rebuild all objects and libraries with the same compiler.
I tried to rebuild all the project and use existing compiler object file. But problem not solved.
Can anyone give solution to resolve this issue?
| I followed below step , issue got resolved.
Error C1047 The object or library file 'Library Path' was created by a different version of the compiler than other objects like 'Object file path'; rebuild all objects and libraries with the same compiler.
compile the reported Library Path project in same compiler [VS2019:Toolset 142].
Verify that library created.
clean all binary,lib and object files from issue reported project.
copy the new library to respective folder or If project has any pre-build step , dont copy the library file.
Build the project with same compiler.
|
70,181,668 | 70,181,921 | Overloading operator[] only for members of a specific class | Edit: MyClass has been renamed to ReverseStringAccess for disambiguation.
I have a class which encapsulates a vector<string>. The class has an overloaded operator[] which can be used to read and modify the contents of the vector. This is how it looks (minimally):
class ReverseStringAccess {
public:
ReverseStringAccess() {}
ReverseStringAccess(vector<string> _arr) arr(_arr) {}
string& operator[](int index) {
return arr[index];
}
private:
vector<string> arr;
};
Now I need to be able to modify the contents of each string in the vector without directly accessing the vector (i.e. some sort of operator[][] which only works with vectors that are members of this class). The problem is that using ReverseStringAccess[][] will result in the default behavior of operator[] on strings. For example, this statement:
ReverseStringAccess[i][j]
would give the jth character of the ith string in the vector. But I want it to (for example) instead get the (length - j - 1)th character of the ith string in the vector, where length is the length of the ith string.
Is this possible? If yes, how?
| If you want my_object[i][k] to not invoke std::string::operator[] then don't return a std::string& from MyClass::operator[], but a proxy that implements the desired []:
class MyClass {
public:
MyClass() {}
MyClass(vector<string> _arr) arr(_arr) {}
struct MyProxy {
std::string& str;
char& operator[](size_t index) { /.../ }
const char& operator[](size_t index) const { /.../ }
};
MyProxy operator[](int index) {
return {arr[index]};
}
private:
vector<string> arr;
};
|
70,181,681 | 70,406,854 | Connect 4: Drop function only works for two row | const int N = 200;
const string usr1 = "o", usr2 = "x";
void updateBoard(string a[N][N], int c, int n, string xo) {
int col = c - 1;
int row = n - 1;
for (int i = row; i >= 0; i--) {
if ((a[i][col] == usr1) || (a[i][col] == usr2)) {
a[i - 1][col] = xo;
}
if ((a[i][col] == " ")) {
a[i][col] = xo;
}
i = 0;
}
}
I don't know what's wrong, It stops at the second row, when i try to drop at third, it rewrites the value on the second...
This happens:
| x |
| x |
Want this:
| x |
| o |
| x |
| I found the answer... Here's the fixed function:
bool updateBoard(string board[N][N], int col, int n, string xo) {
for (int i = n - 1; i >= 0; i--) {
if (board[i][col - 1] == "-") {
board[i][col - 1] = xo;
return true;
}
}
return false;
}
|
70,181,738 | 70,181,780 | Should I delete heap objects that will last for the life of the process? | If I created some objects in the heap during the execution of my program; And I know that all these objects will continue to be accessed until the very final lines of codes of main(); Then is it malpractice to not delete the objects in the heap? and is there any actual harm from that behavior?
| It is a good general rule to delete the objects when they are not used anymore. However, when a process exits, all its heap memory is released.
|
70,182,217 | 70,182,333 | How to access a Protected Variable Correctly? | I am trying to access one of the protected variable from items.h class using components.cpp class but I got the error confusing me: :D
Item::Quantity': cannot access forbidden protected member declared in class
'Item'
item.h
protected:
int32 Quantity;
component.h
#include "Items/Item.h"
Item* AddItem(class Item* Item, const int32 Quantity);
component.cpp
ItemAddResult Component::TryAddItem_Internal(class Item* Item)
{
Items.Add(Item);
return ItemAddResult::AddedAll(Item->Quantity);
}
| You can solve this by making the class Component a friend of class Item by adding a friend declaration inside class Item as shown below:
item.h
class Item{
friend class Component;
protected:
int32 Quantity;
//other members here
}
|
70,182,228 | 70,183,725 | Using the keyword 'new' in file scope? | Given this class in the header file:
class ClassA
{
public:
ClassA(){};
}
Then in file.cpp
#include file.h
ClassA* GlobalPointerToClassAType = new ClassA();
a. Is it allowed, and is it good practice to use the keyword 'new' to allocate memory for an object in the heap(?) in lines of file-scope?
b. If it is allowed, then when exactly does the constructor ClassA() is actually called?
c. How does it differ if I wrote instead this line:
ClassA GlobalInstanceOfClassAType = ClassA();
in terms of the time of calling the constructor, in terms of memory efficiency, and in terms of good practice?
|
a. Is it allowed, and is it good practice to use the keyword 'new' to allocate memory for an object in the heap(?) in lines of file-scope?
It is allowed. Whether is it good practice to use new here is opinion based. And i predict that most people will answer no.
b. If it is allowed, then when exactly does the constructor ClassA() is actually called?
Let's start from some concepts.
In C++, all objects in a program have one of the following storage durations:
automatic
static
thread (since C++11)
dynamic
And if you check the cppreference, it claim:
static storage duration. The storage for the object is allocated when the program begins and deallocated when the program ends. Only one instance of the object exists. All objects declared at namespace scope (including global namespace) have this storage duration, plus those declared with static or extern. See Non-local variables and Static local variables for details on initialization of objects with this storage duration.
So, GlobalPointerToClassAType has static storage duration, it fit the statement that "All objects declared at namespace scope (including global namespace) have this storage duration...".
And if you get deeper into the link of the above section, you will find:
All non-local variables with static storage duration are initialized as part of program startup, before the execution of the main function begins (unless deferred, see below). All non-local variables with thread-local storage duration are initialized as part of thread launch, sequenced-before the execution of the thread function begins. For both of these classes of variables, initialization occurs in two distinct stages:
There's more detail in the same site, you can go deeper if you want to get more, but for this question, let's only focus on the initialization time. According to the reference, The constructor ClassA() might be called before the execution of the main function begins (unless deferred).
What is "deferred"? The answer is in the below sections:
It is implementation-defined whether dynamic initialization happens-before the first statement of the main function (for statics) or the initial function of the thread (for thread-locals), or deferred to happen after.
If the initialization of a non-inline variable (since C++17) is deferred to happen after the first statement of main/thread function, it happens before the first odr-use of any variable with static/thread storage duration defined in the same translation unit as the variable to be initialized. If no variable or function is odr-used from a given translation unit, the non-local variables defined in that translation unit may never be initialized (this models the behavior of an on-demand dynamic library). However, as long as anything from a translation unit is odr-used, all non-local variables whose initialization or destruction has side effects will be initialized even if they are not used in the program.
Let's see a tiny example, from godbolt. I use clang, directly copy your code, except that the Class A and main are defined in the same translation unit. You can see clang generate some section like __cxx_global_var_init, where the class ctor is called.
|
70,182,512 | 70,183,276 | Debugging into MFC header code does not work with Visual Studio 2019 | TL;DR: Debuigging into MFC (CString) header code does not work on both my machines and as far as I can tell this is due to the peculiar way these headers are compiled.
Stepping through MFC header code when entered via disassembly works, but setting brealpoints does not work.
I'm looking for a workaround or at least acknowledgement of my analysis.
System:
Visual Studio 2019 Professional 16.9.6
Windows 10 / 1809 Enterprise LTSC
Setup: (I do apologize for this being rather long.)
Create a Visual Studio 2019 Example MFC Application Project (SDI App)
Make sure Enable Just My Codeis off under Options -> Debugging -> General.
Set the build configuration to Debug/x64 (does not make a difference, but let's all stay on the same page)
Navigate to MFCApplication1.cpp -> CMFCApplication1App::InitInstance()
Insert a CString init like this:
...
InitCommonControlsEx(&InitCtrls);
CWinAppEx::InitInstance(); // please put breakpoint 1 here
// Add this line and set breakpoints
CString this_is_text(L"Debugging into CString Header does not work!"); // breakpoint 2 here
Now, you can start the program under the debugger, and you should stop at the first breakpoint:
Now, make sure all symbols are loaded, easiest done via the Call Stack:
Just select all lines in the call stack window and hit Load Symbols in the context menu. Afterwards the call stack should look roughly like this:
> MFCApplication1.exe!CMFCApplication1App::InitInstance() Line 75 C++
mfc140ud.dll!AfxWinMain(HINSTANCE__ * hInstance=0x00007ff7b5070000, ...) Line 37 C++
MFCApplication1.exe!wWinMain(HINSTANCE__ * hInstance=0x00007ff7b5070000, ...) Line 26 C++
MFCApplication1.exe!invoke_main() Line 123 C++
MFCApplication1.exe!__scrt_common_main_seh() Line 288 C++
MFCApplication1.exe!__scrt_common_main() Line 331 C++
MFCApplication1.exe!wWinMainCRTStartup(void * __formal=0x000000c2b7084000) Line 17 C++
kernel32.dll!BaseThreadInitThunk() Unknown
ntdll.dll!RtlUserThreadStart() Unknown
Now, you can try stepping-into (possibly F11) the CWinAppEx::InitInstance() function, which should work without a problem, landing you in mfc140ud.dll!CWinApp::InitInstance() Line 394 - this is OK.
Step out again, and then then try to step-into the CString ctor:
This DOES NOT work on my machine(s)!
What I can do however, is (from the point above) switch to disassembly view, step into the calls there and get into the header code this way:
I can then successfully step through (but never into) the MFC header code. Trying to set a breakpoint will result in the error:
The breakpoint will not currently be hit. No executable code of the debugger's code type is associated with this line.
Possible causes include ...
C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29910\atlmfc\include\cstringt.h
And this is where I'm at.
Analysis:
What we can see from the MFC code is that we can step into "regular" cpp code, but as soon as we try to step into (or set breakpoint) code that is inside this CStringt.h it breaks.
Peculiar here: This is template header code, and still the executed code (as shown by the disassembly) is not in the user module but in the mfc###.dll! I think they do some clever tricks with the preprocessor (see defined(_MFC_DLL_BLD) and somesuch) which enables this multi use of the header file, and maybe, possibly this is also what breaks the debugger.
Question:
Is this a known problem, does this happen with all VS2019 installs, is there something peculiar to my setup?
Maybe fixed in a newer VS version?
Iff this is actually broken, what would be a useable workaround, other than constantly switching to disassembly view when into the MFC headers.
The most interesting answer here would actually be as to WHY this breaks - where does the debugger get confused? Is this a general problem with re-define-ing code when debugging library code?
| Analysis went sideways at some point, but we finally found one part of the problem here:
The Require source files to exactly match the original version option:
was the problem, but in a very peculiar way:
When you do NOT require source files to match (that is, disable this default option), then the erroneous behavior of the OP occurs: The debugger can no longer match the symbols to the cstringt.h file.
Unfortunately, I had this disabled on both machines. Pulling in a third machine showed that we could set breakpoints (though F11 still does not work) and by comparing the xml export of the VS settings we found that this was different.
So, long story short: For us, to be able to set breakpoints in the (unmodified!) MFC header, requires us to enable the Require source files to exactly match .. option.
If the option is disabled, which would imply a more lenient behavior by the debugger, it no longer works.
And, yes, we double checked it's always the same source file at C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29910\atlmfc\include\cstringt.h
The mystery with step-into/F11 persists, but I guess this would better be taken to a separate question.
|
70,182,726 | 70,182,926 | Error: Use of deleted function std::unique_ptr | I am trying to pass a unique_ptr into a custom vector class but I am receiving the error in the subject title.
I understand that you cannot copy a unique_ptr and so I am trying to use std::move() when passing it, however that doesn't seem to solve my problem... Where am I going wrong?
Thanks in advance
template<typename T>
class VectorSelectable {
public:
void Add(const T& v) {
m_Items.push_back(move(v));
}
private:
vector<T> m_Items;
};
class FunctionType {
int m_Data;
};
int main()
{
VectorSelectable<unique_ptr<FunctionType>> vec;
vec.Add(move(make_unique<FunctionType>()));
return 0;
}
Edit: Added 'const' to 'Add(const T& v)'
| If you want to allow both copy-via-const-ref and move-via-rvalue-ref, you can either template your Add method and use the universal forwarding reference technique, or write two overloads explicitly:
void Add(const T& v) {
m_Items.push_back(v);
}
void Add(T&& v) {
m_Items.push_back(std::move(v));
}
or
template <typename U>
void Add(U&& v) {
m_Items.push_back(std::forward<U>(v));
}
|
70,182,761 | 70,184,973 | Boost: how to use `boost::hash` with `std::pair`, when pair contains a custom type? | I'm trying to use the following custom unordered_map
using pair = std::pair<char, QColor>;
using cache = std::unordered_map<pair, QPixmap, boost::hash<pair>>;
cache _cache;
I defined the hash function for QColor as follows
template<>
struct std::hash<QColor>
{
std::size_t operator()(const QColor &color) const noexcept
{
return std::hash<QRgb>{}(color.rgb());
}
};
but no matter where I place it, whether it is a header or source file, I get a verbose compile time error from boost
C:\boost_1_77_0\boost\container_hash\extensions.hpp:305: error: C2665: 'boost::hash_value': none of the 3 overloads could convert all the argument types
C:\boost_1_77_0\boost/container_hash/hash.hpp(550): note: could be 'size_t boost::hash_value(const std::error_condition &)'
C:\boost_1_77_0\boost/container_hash/hash.hpp(543): note: or 'size_t boost::hash_value(const std::error_code &)'
C:\boost_1_77_0\boost/container_hash/hash.hpp(536): note: or 'size_t boost::hash_value(std::type_index)'
C:\boost_1_77_0\boost/container_hash/extensions.hpp(305): note: while trying to match the argument list '(const T)'
It is the last message of all. I think that boost's hashing function for pair doesn't see the hash function I defined. Do I need define it in the boost's namespace? And in general, what's the rule for defining the specific versions of templates? Why the rule that the templates must be defined in header files only doesn't apply here?
UPD: The structure of my project is as follows
// foo.h
#include <QtWidgets>
#include <boost/functional/hash.hpp>
#include <unordered_map>
template<>
struct std::hash<QColor>
{
std::size_t operator()(const QColor &color) const noexcept
{
return std::hash<QRgb>{}(color.rgb());
}
};
class Foo
{
private:
using Pair = std::pair<char, QColor>;
const QPixmap &getPixmapForPair(Pair c);
using CharsCache = std::unordered_map<Pair, QPixmap, boost::hash<Pair>>;
CharsCache _cache;
}
// foo.cpp
const QPixmap &Foo::getPixmapForPair(Pair c)
{
auto it = _cache.find(c);
if (it != _cache.end())
return it->second;
}
Very oversimplified, but delivers the general idea.
| boost::hash<> probably uses boost::hash_combine which uses hash_value overloads and it doesn't have one for QColor which could be a problem so I suggest that you create a specialization for std::hash<Pair> by moving the alias out of the class definition and then use boost::hash_combine directly in your operator():
using Pair = std::pair<char, QColor>;
namespace std {
template<>
struct hash<Pair> {
std::size_t operator()(const Pair &p) const noexcept {
std::size_t seed = 0;
boost::hash_combine(seed, p.first);
boost::hash_combine(seed, p.second.rgb());
return seed;
}
};
} // namespace std
You could probably make it std::size_t seed = p.first; instead of initializing with 0 and calling hash_combine afterwards.
You can then use the default hasher (std::hash<Pair>) when creating your map:
class Foo {
private:
const QPixmap &getPixmapForPair(const Pair &c) const;
using CharsCache = std::unordered_map<Pair, QPixmap>;
CharsCache _cache;
};
Note that the function must return a value. I suggest that you throw an exception if it can't find a match:
const QPixmap& Foo::getPixmapForPair(const Pair &c) const {
auto it = _cache.find(c);
if (it != _cache.end()) return it->second;
throw std::runtime_error("getPixmapForPair"); // must return a value
}
Another option is to provide an overload for hash_value(const QColor&) instead of a specialization for std::hash<Pair>:
std::size_t hash_value(const QColor& c) {
return std::hash<QRgb>{}(c.rgb());
}
class Foo {
private:
using Pair = std::pair<char, QColor>;
const QPixmap& getPixmapForPair(const Pair& p) const;
using CharsCache = std::unordered_map<Pair, QPixmap, boost::hash<Pair>>;
CharsCache _cache;
};
|
70,183,511 | 70,183,588 | Trying to access private class variables in header function | I need several functions in a header file that use std::cout to say the date, but I don't know how to access them from the header file. If I were within the class, I could just say something like:
void DisplayStandard()
{
cout << month << "/" << day << "/" << year << endl;
}
However, since I'm accessing month, day, and year (which are privates in my .cpp file) I'm not sure how to modify those from void functions in the implementation file. Here's all the code:
dateclasses.h
#ifndef DATECLASS_H
#define DATECLASS_H
class dateclass
{
private:
int month;
int day;
int year;
public:
//default constructor
dateclass()
{
month = 1;
day = 1;
year = 1;
}
//value constructor
dateclass(int month, int day, int year)
{
this->month = month;
this->day = day;
this->year = year;
}
void DisplayStandard();
};
#endif
dateclasses.cpp
#include "dateclass.h"
#include <iostream>
using namespace std;
void DisplayStandard()
{
cout << "Date: " << month << "/" << day << "/" << year << endl;
}
I have yet to set up the main function, though I don't think it necessary for this
| You can solve this by changing void DisplayStandard() to void dateclass::DisplayStandard() as shown below
void dateclass::DisplayStandard()//note the dateclass:: added infront of DisplayStandard
{
cout << "Date: " << month << "/" << day << "/" << year << endl;
}
|
70,183,672 | 70,198,448 | Add non-included header file to up-to-date check in Visual Studio project | I am using Microsoft Visual Studio 2017 and I write code in C++.
There always was one problem with the #define settings in header files. The first approach is to place settings in multiple header files corresponding to specific source files. This approach is OK for minimal rebuild but the main disadvantage is that settings are stored in multiple files.
Another approach is to store all defines in one config.h file and to include it to all source files. It is much easier to configure but all files including config.h will be recompiled each time I change a setting.
So I decided to use the third approach. All settings are stored in config.h (one per project) and have a special comment line before them with the relative path of the exact header file, like this:
// in:core/net/http.h
// some http setting
#define CFG_SOME_HTTP_OPTION
// in:core/net/dns.h
// some dns setting
#define CFG_SOME_DNS_OPTION
But config.h itself is not included by any source file. Instead it is parsed by pre-build script, which builds a code with all defines for each header file mentioned in the config.h. Then a check is made if this code differs from the code already presented in the specific header and the replacement is made only if the code differs. This approach keeps the advantages of two previous approaches because all settings are still in one header file but only those files whose settings were changed are to be rebuilded.
I wrote this script and everything works perfectly except one thing. The config.h is a part of the project but is not included in any source file. That's why Visual Studio does not even run my pre-build script because of up-to-date check: if changes are made only in config.h it still thinks that project is up-to-date.
How can I solve this? The easiest approach is to create special source file including config.h for each project, but maybe there is another method to force build process if only config.h is modified?
| Solved.
Just changed Item Type to C/C++ compiler instead of the C/C++ header in the config.h properties.
|
70,183,943 | 70,185,179 | Jsoncpp - How do I read an array? | I'm stuck at trying to read an array from a Json file.
Here is the People.json file:
{
"ID": [
{
"1": {
"name": "Fred",
"favouriteFood": "Cheese",
"gender": "Male"
}
},
{
"2": {
"name": "Bob",
"favouriteFood": "Cake",
"gender": "Male"
}
}
]
}
Here is the function that should read it:
Person choosePerson(int ID)
{
Person Person;
ifstream file("People.json");
Json::Value root;
Json::Reader reader;
Json::FastWriter fastWriter;
reader.parse(file, root);
Person.id = ID;
Person.name = fastWriter.write(root["data"][to_string(ID)]["name"]);
Person.favFood = fastWriter.write(root["data"][to_string(ID)]["favouriteFood"]);
Person.gender = fastWriter.write(root["data"][to_string(ID)]["gender"]);
return Person;
}
After Running it I get a "Json::LogicError" exception.
| Problem is your JSon which is badly designed. It is bad since objects have keys of unexpected values. Those "1" and "2" make things complicated.
I do not see in documentation how to get list of keys of a JSon object.
Ok I've found getMemberNames(), but you try use it yourself. IMO it would be better to fix this JSon.
So after fixing JSon like this:
{
"ID":[
{
"id":"1",
"name":"Fred",
"favouriteFood":"Cheese",
"gender":"Male"
},
{
"id":"2",
"name":"Bob",
"favouriteFood":"Cake",
"gender":"Male"
}
]
}
Reading of it can look like this:
struct Person {
std::string id;
std::string name;
std::string favouriteFood;
std::string gender;
};
Person personFromJSon(const Json::Value& json)
{
return {
json["id"].asString(),
json["name"].asString(),
json["favouriteFood"].asString(),
json["gender"].asString()
};
}
std::vector<Person> personsFromJSon(const Json::Value& json)
{
if (!json.isArray()) return {};
std::vector<Person> result;
result.reserve(json.size());
std::transform(json.begin(), json.end(), std::back_inserter(result), personFromJSon);
return result;
}
std::vector<Person> personsFromJSon(std::istream& in)
{
Json::Value root;
Json::Reader reader;
reader.parse(in, root);
return personsFromJSon(root["ID"]);
}
Here is live demo.
|
70,183,974 | 70,184,638 | How to convert this vector code into a class? | I was trying to put this code into a class but I couldn't manage to do it. The job of the function is pulling team names from a .txt file and putting them in a vector. I think the main problem is I couldn't select the right function return type.
This is the teams.txt: (The names before the "-" symbol are teams. Other names are unrelated with my question but they are coachs of the teams.)
Trabzonspor-Abdullah Avcı+
Fenerbahçe-Vítor Pereira+
Beşiktaş-Sergen Yalçın+
Galatasaray-Fatih Terim+
İstanbul Başakşehir-Emre Belözeoğlu+
Alanyaspor-Bülent Korkmaz+
Fatih Karagümrük-Francesco Farioli+
Gaziantep-Erol Bulut+
Adana Demirspor-Vincenzo Montella+
Ankara Dinc-Nestor El Maestro+
Antalyaspor-Nuri Şahin+
Kayserispor-Hikmet Karaman+
Yeni Malatyaspor-Marius Sumudica+
Konyaspor-İlhan Palut+
Sivasspor-Rıza Çalımbay+
Hatayspor-Ömer Erdoğan+
Giresunspor-Hakan Keleş+
Kasımpaşa-Hakan Kutlu+
And this is the my code who does the putting them in a vector:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std; //I know that's a bad practice but i just need to do this for while
std::string process(std::string const& s) //A function to seperate teams from the coaches
{
string::size_type pos = s.find('-');
if (pos != string::npos)
{
return s.substr(0, pos);
}
else
{
return s;
}
}
int main() {
ifstream readTeam("teams.txt");
if (!readTeam) { //checking that successfully opened the file.
std::cerr << "Error while opening the file.\n";
return 1;
}
vector<std::string> teams;
string team;
while (getline(readTeam, team)) {
teams.push_back(process(team));
}
readTeam.close();
int g = 1;//for printing the teams, just for displaying it. doesn't have to in a class.
for (const auto& i : teams) {
cout << g;
cout << i << endl;
g++;
}
return 0;
}
And that's what i did(tried) to make it a class:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
std::string process(std::string const& s)
{
string::size_type pos = s.find('-');
if (pos != string::npos)
{
return s.substr(0, pos);
}
else
{
return s;
}
}
class readFile {
public:
void setTxtName(string);
vector<unsigned char> const& getTeam() const{
}
vector<string> teams;
private:
string fileName;
};
int main() {
readFile pullTeams;
pullTeams.setTxtName("teams.txt");
return 0;
}
void readFile::setTxtName(string txtName) {
fileName = txtName;
}
vector<string> const& readFile::getTeam { //problem is defining it(I think). So I couldn't add my main code int it..
return teams;
}
Anything helps, thank you!
| I did a little different research based on the Botje's comment. And I manage to create an answer based on here. Thanks.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
std::string process(std::string const& s){
string::size_type pos = s.find('-');
if (pos != string::npos){
return s.substr(0, pos);
}
else{
return s;
}
}
class readFile {
public:
vector<string> getTxt();
bool read(string);
private:
vector<string> teams;
string team;
ifstream txt;
};
int main() {
vector<string> teams;
readFile team;
if (team.read("teaams.txt") == true)
teams = team.getTxt();
int g = 1;//for printing the teams, just for displaying it. doesn't have to in a class.
for (const auto& i : teams) {
cout << g;
cout << i << endl;
g++;
}
return 0;
}
bool readFile::read(string txtName) {
ifstream txt;
string team;
txt.open(txtName.c_str());
if (!txt.is_open())
return false;
while (getline(txt, team))
teams.push_back(process(team));
return true;
}
vector<string> readFile::getTxt() {
return teams;
}
|
70,184,010 | 70,184,161 | Exception thrown: Write access violation C++ | I want to fill (obj * m) with numbers 2 4 6 8 10 12 14 16 18 20. In Microsoft Visual Studio Professional 2019 I am getting this error: "Exception thrown: Write access violation" at the line "n-> val = data;" or line 15. But then I went into the DEV C ++ application and there I realized what the error was, for some reason the repetition started and the array generally deteriorated, roughly speaking, not counting the initial element. By running the program, you will see everything for yourself, I brought it up there and everything is clearly visible.
#include <iostream>
using namespace std;
class obj{
public:
int val, k;
obj* next;
obj* n;
int current = 0;
void func(int data){
for(n = this, k=0; k<current; n = n->next,k++){
cout<<"k= "<<k<<" = "<<n<<" = "<<n->val<<" curr= "<< current<<", ";
}
cout<<endl;
n->val = data;
current++;
}
void print(){
for(n =this, k = 0; k<10;n = n->next,k++)
{
cout<<n->val<<" ";
}
}
};
int main() {
obj *m;
m=new obj [100];
for(int i=2; i<=20;i+=2)
{
m->func(i);
}
m->print();
delete[] m;
cout << endl;
return 0;
}
| In your code, next is not initialized, so n becomes to point wrong address during iteration in func
int main()
{
/* ... snipped ... */
/* Initialize `next` */
for (int i = 1; i < 100; i++)
{
m[i - 1].next = &m[i];
}
m[99].next = nullptr;
/* snipped */
}
|
70,184,436 | 70,184,534 | How to stop fold expression function calls in the middle when a condition is met and return that value? | I have functions foo, bar, baz defined as follows:
template <typename ...T>
int foo(T... t)
{
return (bar(t), ...);
}
template <typename T>
int bar(T t)
{
// do something and return an int
}
bool baz(int i)
{
// do something and return a bool
}
I want my function foo to stop folding when baz(bar(t)) == true and return the value of bar(t) when that happens. How can I modify the above code to be able to do that?
| Use short circuit operator && (or operator ||):
template <typename ...Ts>
int foo(Ts... t)
{
int res = 0;
((res = bar(t), !baz(res)) && ...);
// ((res = bar(t), baz(res)) || ...);
return res;
}
Demo
Note:
(baz(res = bar(t)) || ...); would even be shorter, but less clear IMO.
|
70,184,472 | 70,184,624 | what's the advantage of defining a class instead of a function in some c++ standard library? | Recently I noticed that C++ std::less is a class,although it simply compares the values of two objects.Here is a sample code:
template <class T> struct less {
bool operator() (const T& x, const T& y) const {return x<y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
so what is the advantage of defining a class instead of a funciton?
and I also wonder why using the 'const' keyword despite there is no data member in the class?
| Primarily to use it as a template parameter, like std::set<int, std::less<int>>.
Class template parameter in interfaces like std::set is used instead of pointer to function to be able to pass other function-like objects that do have some data members. In addition, making it a template parameter aids compiler optimizations, although modern compilers can optimize away function pointers in certain cases either.
|
70,185,148 | 70,185,327 | Unpacking first parameter from template parameter pack c++ | I'm new with templates, specially with parameter pack and I wonder if I can get the first value from the pack.
For example the following code:
template <typename T, typename... Args>
bool register(Args... args) {
if (!Foo<T>(args..) {
assert(std::is_same_v<std::string, args...[0]>);
std::cerr << "Failed call Foo with " + args...[0] + "\n";
}
}
How do I really get the first value in args...?
Worth to note that args... can contain different types (string, boolean, etc.)
| You can use lambda to extract the first parameter:
template<typename T, typename... Args>
bool register(Args... args) {
if (!Foo<T>(args...)) {
auto& first = [](auto& first, auto&...) -> auto& { return first; }(args...);
static_assert(std::is_same_v<std::string,
std::remove_reference_t<decltype(first)>>);
std::cerr << "Failed call Foo with " + first + "\n";
}
}
|
70,185,398 | 70,185,561 | What has changed in C++17 in terms of MOVE elision | Is the "move elision" guaranteed in C++17? Let me explain what I mean by that. In almost every article on what C++17 has introduced, one can find the term: "guaranteed copy elision for RVO" which is kinda self-explanatory. But what about move construction?
Let's look at the code below, it's simple there is a non-copyable type, and two functions, one takes NonCopyable parameter by value, and the second one takes it by rvalue reference.
#include <iostream>
struct NonCopyable
{
NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete;
NonCopyable(NonCopyable&& other) noexcept
{
std::cout << "Move ctor\n";
}
};
void func_by_value(NonCopyable cp)
{
auto x = std::move(cp);
}
void func_by_rvalue_ref(NonCopyable&& cp)
{
auto x = std::move(cp);
}
int main()
{
std::cout << "Pass by value:\n";
func_by_value(NonCopyable());
std::cout << "\nPass by rvalue_ref\n";
func_by_rvalue_ref(NonCopyable());
}
I compiled it two times using GCC(trunk) using the following flags, and the results are slightly different.
(1) -O0 -std=c++11 -fno-elide-constructors
Program output:
Pass by value:
Move ctor
Move ctor
Pass by rvalue_ref
Move ctor
(2) -O0 -std=c++17 -fno-elide-constructors
Program output:
Pass by value:
Move ctor
Pass by rvalue_ref
Move ctor
So my question is - what has changed that the move constriction was elided when using C++17?
Compiler explorer
| Since C++17 mandatory elision of copy/move operations was introduced:
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:
...
In the initialization of an object, when the initializer expression is
a prvalue of the same class type (ignoring cv-qualification) as the
variable type:
T x = T(T(f())); // only one call to default constructor of T, to initialize x
In the initialization of the parameter cp from the prvalue NonCopyable(), the move construction is required to be elided. Note that mandatory copy elision works for both copy operation and move operation.
|
70,185,461 | 70,185,576 | How to make a type T that `std::is_empty_v<T> && sizeof(T) > 1` is true? | I came across an interesting quiz question at here:
Write a translation unit containing a class type T, such that
std::is_empty_v<T> is true, and yet sizeof(T) is greater than 1.
I'v thought about it for some time, but no solution.
How to make a type T that std::is_empty_v<T> && sizeof(T) > 1 is true?
| std::is_empty checks if there are no members. You can use alignment to force a size greater than 1:
struct alignas(2) T {};
static_assert(std::is_empty_v<T>);
static_assert(sizeof(T) > 1);
|
70,185,484 | 70,186,252 | Problem with reading a binary file in cpp? | I have a binary file called "input.bin" where every character is of 4 bits. The file contains this kind of data:
0f00 0004 0018 0000 a040 420f 0016 030b
0000 8000 0000 0000 0000 0004 0018 0000
where 0f is the first byte.
I want to read this data and to do that, I am using the following code:
#include <string>
#include <iostream>
#include <fstream>
int main()
{
char buffer[100];
std::ifstream myFile ("input.bin", std::ios::in | std::ios::binary);
myFile.read (buffer, 100);
if (!myFile.read (buffer, 100)) {
std::cout << "Could not open the required file\n";
}
else
{
for (int i = 0; i < 4; i++)
{
std::cout << "buffer[" << i << "] = " << static_cast<unsigned>(buffer[i]) << std::endl;
}
myFile.close();
}
return 0;
}
Currently I am printing just four bytes of data, and when I run it, I get this output:
buffer[0] = 0
buffer[1] = 24
buffer[2] = 0
buffer[3] = 0
Why is it not printing the value of 0f and just printing the value of 18 in index 1 whereas it is actually at index 6?
| The problem is here
myFile.read (buffer, 100);
if (!myFile.read (buffer, 100)) {
where you read twice, and thus ignore the first 100 bytes (if there are more than 100 of them).
Remove the first read, or change the condition to if (!myFile)
|
70,185,610 | 70,185,832 | Transform uppercase letters to lowercase and vice-versa using single parameter function (C++) | I have the trans function which uses a single parameter, has to be void, and returns through c the opposite case of a letter from a word input in main.
Example:
input: dOgdoG
output: DoGDOg
The function does change the case, but i cant figure out a way to build the new word / replace the old one because i keep getting compiling errors regarding "const char" or "invalid conversions".
The following program gives error "invalid conversion from char to const char*
I only changed the type of the function for example purposes.
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
char trans(char c)
{
if(c >= 'a' && c <= 'z')
return c-32;
else
if(c >= 'A' && c <= 'Z')
return c+32;
}
int main()
{
char s[101], s2[101] = "";
cin >> s;
int i;
for(i=0; i<strlen(s); i++)
{
strncat(s2, trans(s[i]), 1);
}
cout<<s2;
return 0;
}
EDIT:
I changed from the char function to a void function and removed the body of the for.
void trans(char c)
{
if(c >= 'a' && c <= 'z')
c-=32;
else
if(c >= 'A' && c <= 'Z')
c+=32;
}
int main()
{
char s[101], s2[101] = "";
cin >> s;
int i;
for(i=0; i<strlen(s); i++)
{
/// i dont know what to put here
}
cout<<s2;
return 0;
}
| Don't reinvent the wheel. The standard library has functions to identify uppercase and lowercase letter, and to change case. Use them.
char trans(char ch) {
unsigned char uch = ch; // unfortunately, character classification function require unsigned char
if (std::isupper(uch))
return std::tolower(uch);
else
return std::toupper(uch);
}
You might be inclined to change that else branch to else if (std::islower(uch) return std::toupper(uch); else return uch;, but that's not necessary; std::toupper only changes lowercase letters to uppercase, so it won't affect characters that aren't lowercase.
Then, when you call it, just copy the result:
int i = 0;
for ( ; i < strlen(s); ++i)
s2[i] = tran(s[i]);
s2[i] = '\0';
EDIT:
Since there seems to be a requirement to do things the hard way, let's change trans to match:
void trans(char& ch) {
unsigned char uch = ch; // unfortunately, character classification function require unsigned char
if (std::isupper(uch))
ch = std::tolower(uch);
else
ch = std::toupper(uch);
}
And now, you can just apply it in place:
for (int i = 0; i < strlen(s); ++i)
trans(s[i]);
I called this "the hard way" because with the original version of trans you can use it directly to modify the original string:
for (int i = 0; i < strlen(s); ++i)
s[i] = trans(s[i]);
and you can use it to copy the string:
for (int i = 0; i < strlen(s); ++i)
s2[i] = trans(s[i]);
// don't forget the terminating nul
With pass by reference, you can only modify in place; copying requires an additional step:
strcpy(s2, s1);
for (int i = 0; i < strlen(s); ++i)
trans(s2[i]);
|
70,185,771 | 70,185,809 | Template value before typename | I have following simplified example code where I attempt to figure out whether given value is the maximum value of enum of it's type.
enum class MyEnum : unsigned char {
VALUE,
OTHER_VALUE,
_LAST
};
template<typename T, T _L>
bool is_not_last(T value) {
return value < _L;
}
int main()
{
is_not_last<MyEnum, MyEnum::_LAST>(MyEnum::OTHER_VALUE);
return 0;
}
How can I format template so I can call is_not_last without specifying type first.
Desired outcome:
is_not_last<MyEnum::_LAST>(MyEnum::OTHER_VALUE);
Following declarations didn't work:
template<T _L>
bool is_not_last(T value); // Doesn't have typename specified
template<typename T _L>
bool is_not_last(T value); // Invalid syntax
I feel like compiler should be able to deduce type from MyEnum::_LAST but I haven't been able to figure that out.
Thank you very much.
| Since C++17, you might do
template <auto L>
bool is_not_last(decltype(L) value) {
return value < L;
}
Demo
|
70,185,931 | 70,188,915 | How to know if shared_ptr was already serialized to boost archive | In my program I have c++ class objects that keep SmartPointers members (SmartPointer is my own custom class derived from boost::shared_ptr). By design, some of my class objects must keep SmartPtr that are unique i.e no shared ownership is allowed.
I want to implement check module for debug reasons that will test whether given c++ class object (the c++ object can contain nested c++ class object members on its own) keeps smart pointers with shared ownership. If yes, I want to throw exception. I was thinking to reuse the serialization lib for this purpose since I already have serialize functions for all my classes. All I have to do is add checking code in my SmartPointer::serialize function to test whether the pointer was already saved in the archive. So anyone is aware of such function in boost serialization that will tell me whether pointer object was already serialized? I think that the boost serialization library must have mechanism to check this, since in the archive output shared_ptrs with shared ownerships are written just once.
| The code smell is using a shared_ptr where unique ownership must be guaranteed. What are you going to do when you find a violation? Assert? std::terminate?
You could make a serialization wrapper that adds the check on de-serialization.
You will depend on library implementation details, because - apparently - while loading there will be a temporary copy of the shared_ptr:
Live On Coliru
#undef NDEBUG
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/wrapper.hpp>
#include <iostream>
template <typename SP> struct Unique {
SP& _ref;
Unique(SP& r):_ref(r){}
template <typename Ar>
void serialize(Ar& ar, unsigned) {
if constexpr (typename Ar::is_saving{}) {
if (_ref && not _ref.unique())
throw std::logic_error("Shared ownership not allowed");
}
ar & _ref;
if constexpr (typename Ar::is_loading{}) {
if (_ref && _ref.use_count() != 2)
throw std::logic_error("Shared ownership not allowed");
}
}
};
template <typename SP>
struct boost::serialization::is_wrapper<Unique<SP>> : boost::mpl::true_ {};
struct Data {
int a,b,c;
void serialize(auto& ar, unsigned) { ar & a & b & c; }
};
static std::string do_write(auto const&... data) {
std::ostringstream oss;
boost::archive::text_oarchive oa(oss);
(oa << ... << data);
return oss.str();
}
static void do_read(std::string const& str, auto&&... data)
{
std::istringstream iss(str);
boost::archive::text_iarchive ia(iss);
(ia >> ... >> data);
}
int main()
{
auto data = std::make_shared<Data>(1, 2, 3);
assert(data.unique());
// okay:
{
auto txt = do_write(data, data, data);
do_read(txt, data);
std::cout << "L:" << __LINE__ << " Success " << std::endl;
}
// still okay:
{
Unique ud{data};
auto txt = do_write(ud);
do_read(txt, ud);
std::cout << "L:" << __LINE__ << " Success " << std::endl;
assert(data.unique());
}
// not okay because not unique:
try
{
auto data_shared(data);
Unique ud{data}, ud_shared{data_shared};
assert(!data.unique());
assert(!data_shared.unique());
auto txt = do_write(ud, ud_shared);
do_read(txt, ud, ud_shared);
std::cout << "L:" << __LINE__ << " Success " << std::endl;
}catch(std::exception const& e) {
std::cout << "L:" << __LINE__ << " Failure " << e.what() << std::endl;
}
}
Prints
L:57 Success
L:65 Success
L:81 Failure Shared ownership not allowed
Summary
Don't do this, because you can't cleanly do it. The alternative is far worse (delving into the object tracking implementation details as some commenters suggested).
Simply
tighten the type constraints to express your invariant
perhaps add a validation member to check the invariant
|
70,185,973 | 70,186,799 | Box2D weird behavior with std::vector | lately I started playing with box2d and tried abstracting it to class
RigidBody::RigidBody() {
}
RigidBody::RigidBody(const RigidBody& other) {
m_fixture = other.m_fixture;
b2BodyDef bodyDef;
bodyDef.position = other.m_body->GetPosition();
bodyDef.type = other.m_body->GetType();
m_body = Runtime::PhysicsWorld.CreateBody(&bodyDef);
b2FixtureDef fixtureDef;
fixtureDef.shape = m_fixture->GetShape();
fixtureDef.density = m_fixture->GetDensity();
fixtureDef.friction = m_fixture->GetFriction();
fixtureDef.restitution = m_fixture->GetRestitution();
fixtureDef.restitutionThreshold = m_fixture->GetRestitutionThreshold();
m_fixture = m_body->CreateFixture(&fixtureDef);
}
RigidBody::RigidBody(sf::Vector2f pos, BodyType type) {
pos /= Constants::PPM;
b2BodyDef bodyDef;
bodyDef.position = pos;
bodyDef.type = (b2BodyType)type;
m_body = Runtime::PhysicsWorld.CreateBody(&bodyDef);
sf::Vector2f size(50.0f, 50.0f);
size /= 2.0f;
size /= Constants::PPM;
b2PolygonShape shape;
shape.SetAsBox(size.x, size.y);
b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.5f;
fixtureDef.restitution = 0.0f;
fixtureDef.restitutionThreshold = 0.5f;
m_body->CreateFixture(&fixtureDef);
}
RigidBody::~RigidBody() {
Runtime::PhysicsWorld.DestroyBody(m_body);
}
but vector is behaving really weird with it i know it's probably becasue of copy constructor or destructor but I can't figure this out
std::vector<hv::RigidBody> m_Bodies;
the problem is with vector erase when I call m_Bodies.erase(m_Bodies.begin()) for some reason it deletes the last objects
m_Bodies.erase(m_Bodies.begin());
And after I call m_Bodies.erase(m_Bodies.begin()) second time I get this
Also it doesn't matter how many objects is in vector if I call m_Bodies.erase(m_Bodies.begin() + 3) it will always delete the last one
*edit corrected question
| The problem was I didn't define operator =
resolved it by
RigidBody* RigidBody::operator=(const RigidBody& other) {
if(m_body)
Runtime::PhysicsWorld.DestroyBody(m_body);
m_fixture = other.m_fixture;
b2BodyDef bodyDef;
bodyDef.position = other.m_body->GetPosition();
bodyDef.type = other.m_body->GetType();
m_body = Runtime::PhysicsWorld.CreateBody(&bodyDef);
b2FixtureDef fixtureDef;
fixtureDef.shape = m_fixture->GetShape();
fixtureDef.density = m_fixture->GetDensity();
fixtureDef.friction = m_fixture->GetFriction();
fixtureDef.restitution = m_fixture->GetRestitution();
fixtureDef.restitutionThreshold = m_fixture->GetRestitutionThreshold();
m_fixture = m_body->CreateFixture(&fixtureDef);
return this;
}
|
70,186,254 | 70,207,179 | How to formulate the position of each number in a magic square? | How did this code formulate the position of each numbers? I'm kinda dumb at math and I can't contact the one who made this code. so can anyone enlighten me with this? especially on the test positions part.
#include <iostream>
using namespace std;
int main ()
{
int magicsq[3][3];
int i, j, x;
int row = 0; // start position of row
int col = 3 / 2; // and column
for ( i = 0; i < 3 ; i++ )
{
for ( j = 0 ; j < 3; j++ ) magicsq[i][j] = 0; //initialize to 0 your matrix
}
magicsq[row][col] = 1; //position to start the counting
for ( x = 2; x <= 3 * 3; x++ )
{
int r = row - 1, c = col - 1; // test positions
if (r < 0) r += 3;
if (c < 0) c += 3;
if ( magicsq[r][c]>0)
{
row++;
if ( row >= 3 ) row -= 3;
}
else
{
row = r;
col = c;
}
magicsq[row][col] = x;
}
for ( i = 0; i < 3; i++ )
{
for ( j = 0; j < 3; j++ ) cout << magicsq[i][j] << " ";
cout<<endl;
}
}
| This program is about creating a magic square according to the "de la Loubère" method. There is a very good explanation on Wikipedia here. You should read that. It has even animated graphics. Very nice.
The code that you found, is not nice. It is imply ugly and you should not waste your time in understanding it.
The mechanism tocreate a magix square is totally simple. Start at the top middle and then always go up and right (take boundaries into account). If the next place is already occupied, then go one down.
The link shows a step by step example.
This should answer your question.
Additionally, I will show you a different solution, with a better style and using C++ elements. (not C-Style arrays and stuff)
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <array>
// The maximumn dimension of the magic square
constexpr size_t MaxDimension{ 21u };
// Some abbreviations for less typing work. Square will be implemented as a 2 dimensional std::array
using Square = std::array< std::array <int, MaxDimension>, MaxDimension>;
// Create a magic square following the method of "De-la-Loubère"
void createMagicSquare(Square& square, int sizeOfSquare) {
// Reset all values in the square to 0
square = {};
// Starting row and column. Set to upper middle cell
int row{}; int column{ sizeOfSquare / 2};
// This will wrap a position if it leaves the boundary of the square
auto wrap = [&sizeOfSquare](const int position) { return (position + sizeOfSquare) % sizeOfSquare; };
// Now build the magic square and fill it with all numbers
for (int runningNumber{ 1 }; runningNumber <= (sizeOfSquare * sizeOfSquare); ++runningNumber) {
// Write number into cell at current position
square[row][column] = runningNumber;
// If the upper right cell is occupied
if (square[wrap(row-1)][wrap(column+1)] != 0) {
// Then just go one rowe down
row = wrap(row + 1);
}
else {
// Next position will be upper right
row = wrap(row - 1);
column = wrap(column + 1);
}
}
}
// Output of the magic square
void display(Square& square, int sizeOfSquare)
{
constexpr int Width = 4;
std::cout << "\nThe Magic square is: \n\n";
for (int row = 0; row < sizeOfSquare; ++row) {
for (int column = 0; column < sizeOfSquare; ++column)
std::cout << std::setw(Width) << square[row][column];
std::cout << "\n\n";
}
}
int main()
{
// Give instruction what to do
std::cout << "Enter The Size of the Magic Square (odd number (<=21): ";
// Read user inpuit and make sure that it is a correct value
if (int sizeOfSquare{}; (std::cin >> sizeOfSquare) and (sizeOfSquare <= MaxDimension) and (sizeOfSquare%2)) {
// Define the empty square
Square square{};
// Fill it with magic numbers
createMagicSquare(square, sizeOfSquare);
// Show result
display(square, sizeOfSquare);
}
else std::cerr << "\nError: Wrong Input\n";
}
|
70,186,333 | 70,187,028 | Advice on converting timestamp string in "HH:MM:SS.microseconds" format | I'm given a list of timestamps (suppose we have a ready-made std::vector<std::string>) in a string format of a kind std::vector<std::string> = {"12:27:37.740002", "19:37:17.314002", "20:00:07.140902",...}. No dates, no timezones. What would be a preferable way to parse these strings to some kind of C++ type (std::chrono::time_point ?) to be able to perform some comparisons and sorting later.
For example: compare value, which was parsed from "20:00:07.140902" and value, was parsed from "20:00:07.000000".
C++17 is ok, but I can't use any third-party library (Boost, Date etc).
Keeping microseconds precision essential.
| You can build this functionality completly with C++ standard library functionality.
For parsing the string use std::regex.
For time related datatypes use std::chrono
Example :
#include <stdexcept>
#include <regex>
#include <chrono>
#include <iostream>
auto parse_to_timepoint(const std::string& input)
{
// setup a regular expression to parse the input string
// https://regex101.com/
// each part between () is a group and will end up in the match
// [0-2] will match any character from 0 to 2 etc..
// [0-9]{6} will match exactly 6 digits
static const std::regex rx{ "([0-2][0-9]):([0-5][0-9]):([0-5][0-9])\\.([0-9]{6})" };
std::smatch match;
if (!std::regex_search(input, match, rx))
{
throw std::invalid_argument("input string is not a valid time string");
}
// convert each matched group to the corresponding value
// note match[0] is the complete matched string by the regular expression
// we only need the groups which start at index 1
const auto& hours = std::stoul(match[1]);
const auto& minutes = std::stoul(match[2]);
const auto& seconds = std::stoul(match[3]);
const auto& microseconds = std::stoul(match[4]);
// build up a duration
std::chrono::high_resolution_clock::duration duration{};
duration += std::chrono::hours(hours);
duration += std::chrono::minutes(minutes);
duration += std::chrono::seconds(seconds);
duration += std::chrono::microseconds(microseconds);
// then return a time_point (note this will not help you with correctly handling day boundaries)
// since there is no date in the input string
return std::chrono::high_resolution_clock::time_point{ duration };
}
int main()
{
std::string input1{ "20:00:07.140902" };
std::string input2{ "20:00:07.000000" };
auto tp1 = parse_to_timepoint(input1);
auto tp2 = parse_to_timepoint(input2);
std::cout << "start time = " << ((tp1 < tp2) ? input1 : input2) << "\n";
std::cout << "end time = " << ((tp1 >= tp2) ? input1 : input2) << "\n";
return 0;
}
|
70,186,672 | 70,189,478 | Eigen3 (cpp) select column given mask and sum where true | I have a Eigen::Matrix2Xf where row are X and Y positions and cols act as list index
I would like to have the sum of the columns (rowwise) where some column condition is true, here some example code:
Eigen::Vector2f computeStuff(Eigen::Matrix2Xf & values, const float max_norm){
const auto mask = values.colwise().norm().array() < max_norm;
return mask.select(values.colwise(), Eigen::Vector2f::Zero()).rowwise().sum();
}
But this code does not compile complaining about the types of the if/else matrices, what is the correct (and computationally faster) way to do it?
Also I know that there are similar question with an answer, but they create a new Eigen::Matrix2Xf with the filtered values given the mask, this code is meant to run inside a #pragma omp parallel for so the basic idea is to do not create a new matrix for maintaining cache coherency
Thanks
| The main problem with your code is that .select( ... ) needs at least one of its arguments to have the same shape as the mask. The arguments can be two matrices or a matrix and a scalar or vice-versa, but in all cases the matrices have to be shaped like the mask.
In your code mask is a row vector but values is a 2 by x matrix. One way to handle this is to just replicate the row vector into a two row matrix:
#include <Eigen/Dense>
#include <iostream>
Eigen::Vector2f computeStuff(Eigen::Matrix2Xf& values, const float max_norm) {
auto mask = (values.colwise().norm().array() < max_norm).replicate(2, 1);
return mask.select(values, 0).rowwise().sum();
}
int main() {
Eigen::Matrix2Xf mat(2,4);
mat << 1, 4, 3, 2,
1, 2, 4, 3;
auto val = computeStuff(mat, 5);
std::cout << val;
return 0;
}
In the above mask will be:
1 1 0 1
1 1 0 1
i.e. the row 1 1 0 1 duplicated once. Then mask.select(values, 0) yields
1 4 0 2
1 2 0 3
so the result will be
7
6
which i think is what you want, if I am understanding the question.
|
70,186,757 | 70,187,301 | g++ cannot find library although it's there | I'm compiling some cpp files with:
$ g++ -c --std=c++17 -I/antlr4/runtime/Cpp/runtime/src/ *.cpp
And everything goes fine:
$ ls -l *.cpp *.o
-rw-r--r-- 1 root root 76637 Dec 1 14:33 Java8Lexer.cpp
-rw-r--r-- 1 root root 370768 Dec 1 15:13 Java8Lexer.o
-rw-r--r-- 1 root root 925012 Dec 1 14:33 Java8Parser.cpp
-rw-r--r-- 1 root root 5037896 Dec 1 15:13 Java8Parser.o
-rw-r--r-- 1 root root 113 Dec 1 14:33 Java8ParserBaseListener.cpp
-rw-r--r-- 1 root root 2312 Dec 1 15:13 Java8ParserBaseListener.o
-rw-r--r-- 1 root root 109 Dec 1 14:33 Java8ParserListener.cpp
-rw-r--r-- 1 root root 2304 Dec 1 15:13 Java8ParserListener.o
-rw-r--r-- 1 root root 724 Dec 1 14:36 main.cpp
-rw-r--r-- 1 root root 324360 Dec 1 15:13 main.o
When I try to link with a library, it fails:
$ g++ *.o -l/antlr4/runtime/Cpp/dist/libantlr4-runtime.so.4.9.3
/usr/bin/ld: cannot find -l/antlr4/runtime/Cpp/dist/libantlr4-runtime.so.4.9.3
collect2: error: ld returned 1 exit status
This is weird because the shared library does exist:
$ ls -l /antlr4/runtime/Cpp/dist/libantlr4-runtime.so.4.9.3
-rwxr-xr-x 1 root root 1599624 Dec 1 14:28 /antlr4/runtime/Cpp/dist/libantlr4-runtime.so.4.9.3
| You can specify the directory with option -L and the library file with its abbreviated form (no lib prefix, no .so.xxx suffix):
g++ *.o -L /antlr4/runtime/Cpp/dist -lantlr4-runtime
|
70,187,432 | 70,187,577 | Is it implementation-defined that how to deal with [[no_unique_address]]? | Below is excerpted from cppref but reduced to demo:
#include <iostream>
struct Empty {}; // empty class
struct W
{
char c[2];
[[no_unique_address]] Empty e1, e2;
};
int main()
{
std::cout << std::boolalpha;
// e1 and e2 cannot have the same address, but one of them can share with
// c[0] and the other with c[1]
std::cout << "sizeof(W) == 2 is " << (sizeof(W) == 2) << '\n';
}
The documentation says the output might be:
sizeof(W) == 2 is true
However, both gcc and clang output as follows:
sizeof(W) == 2 is false
Is it implementation-defined that how to deal with [[no_unique_address]]?
| See [intro.object]/8:
An object has nonzero size if ... Otherwise, if the object is a base class subobject of a standard-layout class type with no non-static data members, it has zero size.
Otherwise, the circumstances under which the object has zero size are implementation-defined.
Empty base class optimization became mandatory for standard-layout classes in C++11 (see here for discussion). Empty member optimization is never mandatory. It is implementation-defined, as you suspected.
|
70,187,552 | 70,192,005 | can we define 'operator<' as member function of a class to work with std::less? | I am trying to write member function which can be used when we call std::less. I defined a 'pqueue' class which stores contents in dequeue internally and uses std::less to compare. Defined one more class 'myClass' and I am using pqueue to store objects of the class. Code is as below.
#include <iostream>
#include <deque>
#include <algorithm>
#include <functional>
using namespace std;
template <class T> class PQueue
{
public:
PQueue();
~PQueue();
void push(T & item);
void push(T && item);
T & front();
using Queue = std::deque<T>;
protected:
Queue q_;
};
template <class T> PQueue<T>::PriorityQueue()
{
}
template <class T> PQueue<T>::~PriorityQueue()
{
}
template <class T> void PQueue<T>::push(T & item)
{
q_.emplace_back(item);
}
template <class T> void PQueue<T>::push(T && item)
{
q_.emplace_back(item);
}
template <class T> T & PQueue<T>::front()
{
std::partial_sort(q_.begin(), q_.begin()+1, q_.end(), std::less<T>{});
return q_.front();
}
class myClass
{
public:
myClass(int x)
{
y = x;
}
int y;
friend bool operator < (const myClass &obj1, const myClass &obj2);
/*bool operator < (const myClass &obj)
{
return y < obj.y;
}*/
};
bool operator < (const myClass &obj1, const myClass &obj2)
{
return obj1.y < obj2.y;
}
int main()
{
myClass obj1(10);
myClass obj2(2);
myClass obj3(100);
PQueue<myClass> queue;
queue.push(obj1);
queue.push(obj2);
queue.push(obj3);
cout << queue.front().y;
return 0;
}
Above code is working fine if I define 'operator <' function as friend function of myClass. But if I define the 'operator <' function as member function of myClass as below, it is throwing error.
bool operator < (const myClass &obj)
{
return y < obj.y;
}
ERROR:
/usr/include/c++/9/bits/stl_function.h:386:20: error: no match for ‘operator<’ (operand types are ‘const myClass’ and ‘const myClass’)
386 | { return __x < __y; }
| ~~~~^~~~~
main.cpp:79:14: note: candidate: ‘bool myClass::operator<(const myClass&)’
79 | bool operator < (const myClass &obj)
| ^~~~~~~~
main.cpp:79:14: note: passing ‘const myClass*’ as ‘this’ argument discards qualifiers
As per the error, it is clear that operator< function should take const objects as arguments and it is not possible if we define this function as member function of the class. But as per one of stack overflow answers, we can define this as member function.
how to use overloaded std::less for std::map
Can anyone please let me know if we can define operator< function as member function to use for std::less and if yes, please let me know any errors in the code.
| This answer is from the comment 'Jarod42' posted.
Missing const (at the end) -> bool operator < (const myClass &obj) const else it is like if friend function would be friend bool operator < (myClass&, const myClass&).
|
70,187,754 | 70,188,484 | Find position of min element of a "masked vector" | I have a vector of some values and a mask vector of 0's and 1's. For example:
std::vector<int> mask{0, 0, 1, 0, 1, 1, 0};
std::vector<double> vec{7.1, 1.0, 3.2, 2.0, 1.8, 5.0, 0.0};
and I need to find the min element (its index) in vec but only where mask is 1. In this example it is 1.8 at index 4.
Here's my solution using a loop
double minVal = std::numeric_limits<double>::max();
int minIndex;
for (size_t i = 0; i < vec.size(); ++i)
{
if (vec[i] < minVal && mask[i] == 1)
{
minVal = vec[i];
minIndex = i;
}
}
But I was wondering if there is a way to do it by using the standard library (e.g. std::min_element and lambdas), ideally without using the for-loop?
| You can transform into a combined vector, using max double as a replacement for masked values, and use that with std::min_element
#include <algorithm>
#include <iostream>
#include <limits>
#include <vector>
int main()
{
std::vector<bool> mask{0, 0, 1, 0, 1, 1, 0};
std::vector<double> vec{7.1, 1.0, 3.2, 2.0, 1.8, 5.0, 0.0};
std::vector<double> combined;
std::transform(vec.begin(), vec.end(), mask.begin(),
std::back_inserter(combined),
[](double v, bool mask) {
return mask ? v : std::numeric_limits<double>::max(); });
auto it = std::min_element(combined.begin(), combined.end());
std::cout << "min=" << *it << "\n";
return 0;
}
See https://ideone.com/FncV2r for a live example.
Getting the index is fairly easy using std::distance
std::cout << "index=" << std::distance(combined.begin(), it) << "\n";
And applying this to the original vector would be
auto index = std::distance(combined.begin(), it);
auto it_vec = vec.begin() + index;
See https://ideone.com/U8AXtm
Keep in mind, that even though this solution uses std algorithms and a lambda, the questioner's simple for loop is more efficient.
This is because the for loop doesn't need extra space (the combined vector), and finishes in a single run, whereas transform and min_element take two turns to produce the same result.
So occasionally, there's a time for "old-fashioned" loops.
|
70,188,097 | 70,188,138 | Detecting memory leaks | Consider the following code:
int main(){
A c;
A array[5];
A *ptr;
}
Assuming that class A has no memory leaks. Does the above code have any memory leaks?
My thoughts:
The variables c and array of these six objects of type A will get allocated/instantiated.
The ptr variable is not assigned anything, so that nothing will get created there.
For both c and array, before the program exits, the destructor for them will be called.
So, there should not be any memory leaks.
I am not sure of my reasoning above.
Also, will the memory for the array be allocated - off the stack, off the heap, or in the global memory space?
| There are no memory leaks as there are no mismatched
malloc / free
new / delete
new[] / delete[]
The array array[5] has automatic storage duration. That's the formal term for being "on the stack". Conceptually it goes out of scope at the closing brace } of main(), after ptr has gone out of scope.
|
70,188,661 | 70,219,784 | Why would a program crash in DllMain() when linking Xinput.lib | I have created an input library and I link with xinput.lib. The program that uses my input library crashes on start up before any user code is executed so it makes it pretty hard to debug. The program crashes during xinput dll loading which appears to happen in the generated dllmain function of my library. The error I get with the crash is “xinput: an invalid parameter was passed to a function that considers an invalid parameter an error”. If I add an empty dllmain function in my input library, everything works correctly and no crash. What could be causing the crash when no dllmain function exists. Seems like it’s a corruption of some sort and nothing to do specifically with xinput. However no user code has been executed before the crash so I’m lost at what it could be. Any thoughts? I’m on windows 11 and I’m using visual studio 2022 with clang-cl tool chain. I’d also like to point out that this was never an issue when I was using VS 2019 and windows 10. Could it be an issue with the new tool chain or os? Thank you.
EDIT 1:
Here is what the stack trace looks like when there is no dllmain in my library:
When i un-comment that empty DllMain in my library, there is no crash and everything works perfectly. Makes no sense since that DllMain does absolutely nothing.
EDIT 2:
I can confirm that this exact same behavior works on a complete empty project that links to Xinput.lib. Bare-bones console application with simple main() function that calls a function from a blank library that references Xinput.lib
| I can confirm that this must be a bug in the latest clang-cl tool-chain (it worked about 2 years ago when i was heavily working on this project). After using the msvc tool-chain, everything works as expected. I will file a bug report with Microsoft Visual Studio.
|
70,188,797 | 70,220,729 | Reserving memory for an object in heap without calling its constructor on Arduino | I'm working on an arduino project, this is relevant since there's no support for STL nor dynamic allocation on arduino natively. I've noticed that a lot of classes I'm writing do nothing on construction, but have an .init() method that actually initializes any resources. This is because that way the class can be initialized in the global scope, and then when the setup function runs, actual initialization happens as .init() is called there.
For example:
const portn_t en=A5, rs=A4, d4=A0, d5=A1, d6=A2, d7=A3;
// making room for that object in the global scope
// this way it can be both used in ``setup()`` and ``loop()``
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
lcd.begin(16, 2); // Doing the actual initialization
}
void loop() {
lcd.clear();
lcd.write("Hello world!");
delay(500);
}
This works fine for classes that are designed with an init or begin method. This design pattern is common in most Arduino libraries, but for classes that don't implement this I'm currently using this as a workaround:
Button& get_btn_up() {
// The Button class actually does initialization at construcion
static Button bt(2, true);
return bt;
}
Button& get_btn_enter() {
static Button bt(3, true);
return bt;
}
Button& get_btn_down() {
static Button bt(4, true);
return bt;
}
void setup() {
// Initializes all the ``Button`` objects
get_btn_up();
get_btn_enter();
get_btn_down();
}
void loop() {
auto up = get_btn_up();
if (up.just_pressed()) {
...
}
...
}
Which I don't believe is an optimal solution, as there's a lot of boiler plate just to achieve something that could be done with new and some unique pointers.
Because of this I attempted making a DelayedInit container class, that would hold the required memory for the object in a union and handle its lifetime
template<typename T>
union MemoryOf {
uint8_t memory [sizeof(T)];
T obj;
};
template<typename T>
struct DelayedInit {
private:
MemoryOf<T> memory{.memory={ 0 }};
bool is_set = false;
public:
T& get() const {
memory.obj;
}
DelayedInit() {}
~DelayedInit() {
if (is_set)
get().~T();
}
T* operator->() const {
return &get();
}
T& operator*() {
is_set = true;
return get();
}
const T& operator*() const {
return get();
}
explicit operator bool() const {
return is_set;
}
};
This implementation is broken at the time, as it locks the arduino up whenever I try to call any methods of the boxed class. Here's how it's supposed to be used
DelayedInit<Button> up, enter, down;
void setup() {
*up = Button(2, true);
*enter= Button(3, true);
*down = Button(4, true);
}
void loop() {
if (up->just_pressed()) { // Locks up the arduino
...
}
...
}
I'm guessing there's some memory management error in the code that I'm not aware of. What errors are present in the DelayedInit implementation? Is there a better approach at solving this issue?
| This is the solution I ended up with. .init emulates the pattern that most classes in the arduino libraries use, without actually splitting the init logic in two methods. There's definitely room for improvement, but this works for global variables.
#pragma once
#include <new>
template<typename T>
union MemoryOf {
uint8_t memory [sizeof(T)];
T obj;
MemoryOf() : memory{ 0 } {};
~MemoryOf() {};
};
// Only tested with global variables
// so there might be bugs in the cleanup bits
template<typename T>
struct DelayedInit {
private:
MemoryOf<T> memory;
bool is_set = false;
public:
const T& get() const {
return memory.obj;
}
T& get() {
return memory.obj;
}
void remove() {
get().~T();
}
DelayedInit() {};
~DelayedInit() {
if (is_set)
remove();
}
template<typename ...Args>
inline void init(Args ...args) {
if (is_set) {
remove();
}
new (&memory.memory) T(args...); // == &memory.obj
is_set = true;
}
T* operator->() {
return &get();
}
const T* operator->() const {
return &get();
}
T& operator*() {
return get();
}
const T& operator*() const {
return get();
}
explicit operator bool() const {
return is_set;
}
};
Usage:
#include "delayed_init.hpp"
DelayedInit<Button> up, enter, down;
void setup() {
up.init(2, true);
enter.init(3, true);
down.init(4, true);
}
void loop() {
if (up->just_pressed()) {
...
}
...
}
Thanks to EOF for suggesting the use of placement new!
|
70,189,132 | 70,189,222 | C++ call function from class without instantiating it | In dice.h, I have
class dice {
public:
dice(int sides);
int roll() const;
static int globalRoll(int sides);
private:
int sides;
And in dice.cpp
dice::dice(int sides) {
this->sides = sides;
}
int dice::roll() const {
return rand() % sides + 1;
//Here sides refers to member field
}
int dice::globalRoll(int sides) {
return rand() % sides + 1;
//Here sides refers to parameter
}
Then, for example in a function rollInitiative(), I have the call
return dice.globalRoll(20) + getDexMod();
Which doesn't work because "type name [dice] is not allowed". I could do the following but I'd rather not create an instance for a single roll call.
dice d(20);
return d.roll() + getDexMod();
My assumption was that I'd be able to call a static function from a class without instantiating it, since my understanding is that static functions don't refer to an instance of the class.
| Ok I just needed to change dice. to dice::. I feel silly. I don't really understand the difference but I'll look into it.
Also, since overhead is irrelevant and it's bad practice to have different paths to accomplish the same thing (and most importantly it can still be all on one line), I have just deleted the static function and will instead use
dice(int).roll();
|
70,189,596 | 70,192,178 | Optimal access of NUMBER(14) column via ODBC instant client 32-bit driver | I am working on an application written in C++ that uses the 32-bit Instant Client drivers to access an Oracle database. The application uses the Record Field Exchange (RFX) methods to update the columns in the database tables. The database schema cannot be modified.
The C++ code was originally written to handle OID values as doubles because the OID column in the database is NUMBER(14), so a regular int won't be big enough. However, this leads to the database occasionally selecting a bad execution plan where it takes the OID values sent from the application and uses the to_binary_double function on them, rather than converting them to BIGINT. If this happens, the database does not do an index search over the data and instead does a full table scan.
We tried switching the OIDs to be type __int64 in the application, but there was an issue with the ODBC driver not supporting the BigInt type (or long long in C++). Similarly, when we tried to make the OIDs into longs, the database or the driver gave an error that the values sent to the database were too big for the column.
Working with the OIDs as Strings in C++ will work, but the database will never use the optimal index search because it has to convert the String to an integer before it can do any data retrieval. Because of this, we're just better off using the doubles we already have.
Does anyone have an idea of what we can do next? It is not the end of the world if we have to keep using doubles as before, but we were hoping to eliminate the chance for the database to run slowly.
| We actually went with the "Convert all the OIDs to Strings in the C++ code" option. It turns out the database was still able to run an indexed search after converting the OIDs from Strings to integers. It would have been better if we switched ODBC driver to one that could handle BigInt, but that wasn't really an option for us so this will suffice.
|
70,189,675 | 70,189,877 | Problem with union containing a glm::vec2 (non-trivial default constructor) | I have a the following struct:
struct Foo
{
union
{
glm::vec2 size;
struct { float width, height; };
};
Foo() = default;
};
If I create an instance of Foo with new, I get the following error:
call to implicitly-deleted default constructor of 'Foo'
Note that I've read a few answers on SO, all are talking about using placement-new, but I did not fully understand how to apply that to my simple test-case.
|
At most one non-static data member of a union may have a brace-or-equal-initializer. [Note: if any non-static data member of a union has a non-trivial default constructor (12.1), copy constructor (12.8), move constructor (12.8), copy assignment operator (12.8), move assignment operator (12.8), or destructor (12.4), the corresponding member function of the union must be user-provided or it will be implicitly deleted (8.4.3) for the union. — end note ]
The relevant part is
if any non-static data member of a union has a non-trivial [member function] [...], [then] the corresponding member function of the union must be user-provided or it will be implicitly deleted.
So you will have to manually implement the constructor and destructor (and if you need them also the copy constructor, move constructor, copy assignment operator and move assignment operator).
The compiler can't provide a default constructor because there's no way it could know which of the union members should be initialized by the default constructor, or which union member the destructor needs to destruct.
So using the default constructor or trying to =default; it won't work, you'll have to provide user-specified implementations.
A basic implementation could look like this:
struct Foo
{
bool isVector;
union
{
std::vector<float> vec;
struct { float width, height; };
};
// by default we construct a vector in the union
Foo() : vec(), isVector(true) {
}
void setStruct(float width, float height) {
if(isVector) {
vec.~vector();
isVector = false;
}
this->width = width;
this->height = height;
}
void setVector(std::vector<float> vec) {
if(!isVector) {
new (&this->vec) std::vector<float>();
isVector = true;
}
this->vec = vec;
}
~Foo() {
if(isVector) vec.~vector();
}
};
godbolt example
Note that you need to manually manage the lifetime of the union members, since the compiler won't do that for you.
In case the active union member is the struct, but you want to activate the vector member, you need to use placement new to construct a new vector in the union.
The same is true in the opposite direction: if you want to switch the active union member from the vector to the struct, you need to call the vector destructor first.
We don't need to clean up the struct, since it's trivial, so no need to call it's constructor / destructor.
If possible i would recommend using std::variant or boost::variant instead, since those do exactly that: they keep track of the active union member and call the required constructors / destructors as needed.
|
70,189,912 | 70,190,279 | C++ how to display text in child window at real time |
This application creates a child window (which is the white box) when I right click anywhere, and destroys the child window after another right click. I have implemented the mechanics to expand and shrink the red rectangle through Direct 2D. I would like the child window to display the width and height of the rectangle at real time, as I make changes to it. I do not interact with the child window at all: it doesn't need an "x" button for closing and stuff; it just prints out a couple lines of data.
Here is what I have in my main window procedure:
case WM_RBUTTONUP:
{
DemoApp *pDemoApp = reinterpret_cast<DemoApp *>(static_cast<LONG_PTR>(
::GetWindowLongPtrW(hwnd, GWLP_USERDATA)));
pDemoApp->showTextBox = !pDemoApp->showTextBox; //showTextBox is a boolean
if (pDemoApp->showTextBox) {
POINTS cursor = MAKEPOINTS(lParam);
pDemoApp->child_hwnd = CreateWindowEx(
WS_EX_TOPMOST,
"LISTBOX",
"I dont need a title here",
WS_CHILDWINDOW,
cursor.x,
cursor.y,
100,
200,
pDemoApp->main_hwnd,
NULL,
HINST_THISCOMPONENT,
pDemoApp
);
ShowWindow(pDemoApp->child_hwnd, SW_SHOWNORMAL);
UpdateWindow(pDemoApp->child_hwnd);
}
else {
DestroyWindow(pDemoApp->child_hwnd);
}
}
break;
How may I go from here? I would like to know:
Is using Direct Write to draw text in the child window my only option? I see the dashed lines in the white box so I assume there must be a way to display plain text.
I used LISTBOX here, which is a predefined windows class name. How do I set a procedure for it? What else predefined class name can better suit my need? Or do I have to register a custom one;
I would like to drag the child window around, how can I set it up so that the system handles dragging for me.
Would popping a dialog box to display text be better than popping a child window?
Thanks.
| Since you are using a Win32 LISTBOX control as the child window, then you have a couple of options for displaying the rectangle's dimensions in it:
give the ListBox the LBS_HASSTRINGS style, and add 1-2 items to it. Then, any time you change the rectangle, send LB_DELETESTRING and LB_ADDSTRING messages to the ListBox's HWND to display the updated dimensions as needed. A ListBox does not have a way to update an existing item, so to change an existing item's text, you have to remove the item and then re-add it with the new text.
give the ListBox an LBS_OWNERDRAW... style, and add 1-2 blank item(s) in it. Then have the ListBox's parent window handle WM_MEASUREITEM and WM_DRAWITEM notifications from the ListBox to display the rectangle's current dimensions in the item(s) as needed. Whenever the rectangle is changed, call InvalidateRect() on the ListBox's HWND to trigger a redraw.
|
70,189,974 | 70,190,032 | Beginner quesiton memory allocation c++ | I'am currently learning c++. During some heap allocation exercises I tried to generate a bad allocation. My physical memory is about 38GB. Why is it possible to allocate such a high amount of memory? Is my basic calculation of bytes wrong? I don't get it. Can anyone give me a hint please? Thx.
#include <iostream>
int main(int argc, char **argv){
const size_t MAXLOOPS {1'000'000'000};
const size_t NUMINTS {2'000'000'000};
int* p_memory {nullptr};
std::cout << "Starting program heap_overflow.cpp" << std::endl;
std::cout << "Max Loops: " << MAXLOOPS << std::endl;
std::cout << "Number of Int per allocation: " << NUMINTS << std::endl;
for(size_t loop=0; loop<MAXLOOPS; ++loop){
std::cout << "Trying to allocate new heap in loop " << loop
<< ". current allocated mem = " << (NUMINTS * loop * sizeof(int))
<< " Bytes." << std::endl;
p_memory = new (std::nothrow) int[NUMINTS];
if (nullptr != p_memory)
std::cout << "Mem Allocation ok." << std::endl;
else {
std::cout << "Mem Allocation FAILED!." << std::endl;
break;
}
}
return 0;
}
Output:
...
Trying to allocate new heap in loop 17590. current allocated mem = 140720000000000 Bytes.
Mem Allocation ok.
Trying to allocate new heap in loop 17591. current allocated mem = 140728000000000 Bytes.
Mem Allocation FAILED!.
| Many (but not all) virtual-memory-capable operating systems use a concept known as demand-paging - when you allocate memory, you perform bookkeeping allowing you to use that memory. However, you do not reserve actual pages of physical memory at that time.1
When you actually attempt to read or write to any byte within a page of that allocated memory, a page fault occurs. The fault handler detects that the page has been pre-allocated but not demand-paged in. It then reserves a page of physical memory, and sets up the PTE before returning control to the program.
If you attempt to write into the memory you allocate right after each allocation, you may find that you run out of physical memory much faster.
Notes:
1 It is possible to have an OS implementation that supports virtual memory but immediately allocates physical memory to back virtual allocations; virtual memory is a necessary, but not sufficient condition, to replicate your experiment.
One comment mentions swapping to disk. This is likely a red herring - the pagefile size is typically comparable in size to memory, and the total allocation was around 140 TB which is much larger than individual disks. It's also ineffective to page-to-disk empty, untouched pages.
|
70,190,066 | 70,192,893 | How to run Redis sadd commands with hiredis | My code contains a head file redis.h and a c++ source file redis.cpp.
This is a demo of sadd opeaion in redis. All the operations fail, becase of WRONGTYPE Operation against a key holding the wrong kind of value. I don't know what happened.
Please give me some suggestions.
//redis.h
#ifndef _REDIS_H_
#define _REDIS_H_
#include <iostream>
#include <string.h>
#include <string>
#include <stdio.h>
#include <hiredis/hiredis.h>
using namespace std;
class Redis{
public:
Redis(){}
~Redis(){
this->_connect =NULL;
this->_reply=NULL;
}
bool connect(string host, int port){
this->_connect = redisConnect(host.c_str(), port);
if(this->_connect != NULL && this->_connect->err){
printf("connect error: %s\n", this->_connect->errstr);
return 0;
}
return 1;
}
string set(string key, string value){
this->_reply = (redisReply*)redisCommand(this->_connect, "sadd %s %s", key.c_str(), value.c_str());
string str = this->_reply->str;
return str;
}
string output(string key){
this->_reply = (redisReply*)redisCommand(this->_connect, "smembers %s", key.c_str());
string str = this->_reply->str;
freeReplyObject(this->_reply);
return str;
}
private:
redisContext * _connect;
redisReply* _reply;
};
#endif //_REDIS_H
//redis.cpp
#include "redis.h"
int main(){
Redis *r = new Redis();
if(!r->connect("127.0.0.1", 6379)){
printf("connect error!\n");
return 0;
}
printf("Sadd names Andy %s\n", r->set("names", "Andy").c_str());
printf("Sadd names Andy %s\n", r->set("names", "Andy").c_str());
printf("Sadd names Alice %s\n", r->set("names", "Alice").c_str());
printf("names members: %s\n", r->output("names").c_str());
delete r;
return 0;
}
The result:
Sadd names Andy WRONGTYPE Operation against a key holding the wrong kind of value
Sadd names Andy WRONGTYPE Operation against a key holding the wrong kind of value
Sadd names Alice WRONGTYPE Operation against a key holding the wrong kind of value
names members: WRONGTYPE Operation against a key holding the wrong kind of value
|
WRONGTYPE Operation against a key holding the wrong kind of value
This means the key, i.e. names, has already been set, and its type is NOT a SET. You can run TYPE names with redis-cli to see the type of the key.
Also, your code has several problems:
redisConnect might return null pointer
you did not call redisFree to free the resource of redisReply in your set method
sadd and smembers do NOT return string reply, so you cannot get the correct reply
Since you're using C++, you can try redis-plus-plus, which is based on hiredis, and have more C++ friendly interface:
try {
auto r = sw::redis::Redis("tcp://127.0.0.1:6379");
r.sadd("names", "Andy");
r.sadd("names", "Alice");
std::vector<std::string> members;
r.smembers("names", std::back_inserter(members));
} catch (const sw::redis::Error &e) {
// error handle
}
Disclaimer: I'm the author of redis-plus-plus.
|
70,190,329 | 70,205,412 | Adding a toolbar to wxWidgets is generating a strange result | I'm trying to accomplish a very simple task, add a toolbar to an app. I tried the most simple thing I could come up with, but the result is kind of strange, and I was wondering if this is suppose to behave this way or if I'm missing something.
The code is below, note that I even tried to use a native image(commented), but the result was the same.
#include <wx/wx.h>
#include <wx/image.h>
// #include <wx/artprov.h>
class MyApp: public wxApp
{
public:
virtual bool OnInit();
};
class MyFrame: public wxFrame
{
public:
MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
};
wxIMPLEMENT_APP(MyApp);
bool MyApp::OnInit()
{
MyFrame *frame = new MyFrame("Simple test", wxPoint(50, 50), wxSize(450, 340) );
frame->Show( true );
return true;
}
MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame(NULL, wxID_ANY, title, pos, size)
{
// wxToolBar *toolbar = CreateToolBar();
// toolbar->AddTool(1001, _("New"), wxArtProvider::GetBitmap("wxART_NEW"));
// toolbar->Realize();
CreateStatusBar();
SetStatusText(wxT("Start"));
wxInitAllImageHandlers();
wxImage image(wxT("save.png"), wxBITMAP_TYPE_PNG);
if (image.Ok())
{
wxToolBar *toolbar = CreateToolBar();
toolbar->AddTool(1001, _("New"), image);
toolbar->Realize();
}
else
{
SetStatusText(wxT("image not ok"));
}
}
The result is here, note that the icon is in the app bar instead in a separate toolbar.
| This is how toolbars work in recent macOS versions and wxWidgets is all about using the native UI, so this is most definitely a feature and not a bug, as this is how the native apps look too -- just look at Finder, for example.
|
70,190,368 | 70,190,581 | Find element in a vector with previous and next element equal to 0 | I want to go through a given vector of integers and find an integer which the value of the next and previous integer are 0.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> sample = { 0,3,0 };
for (int i : sample)
{
if (sample[i - 1] == sample[i + 1] == 0)
{
cout << "hello";
}
}
}
However, I keep getting a "vector subscript out of range" error. I think it's because when i is 0, sample[-1] doesn't exist, same with i = 2.
Is there an easy fix for it?
| In a range-for loop, i is set to the value of each element in the array. It is NOT set to the index of each element, as you are currently assuming it does.
You need to use an indexed-based loop instead:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> sample = ...;
if (sample.size() > 2)
{
for (size_t i = 1; i < sample.size()-1; ++i)
{
if (sample[i-1] == 0 && sample[i+1] == 0)
{
cout << sample[i] << endl;
}
}
}
}
Otherwise, use an iterator-based loop instead:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> sample = ...;
if (sample.size() > 2)
{
for (auto iter = sample.begin()+1; iter != sample.end()-1; ++iter)
{
if (*(iter-1) == 0 && *(iter+1) == 0)
{
cout << *iter << endl;
}
}
}
}
|
70,190,651 | 70,190,778 | saving a lambda expression as parameter/variable inside a class to another class | I made a class and a struct.
The class is named Learning and the struct is named Action.
My Action constructor takes one parameter: object's function, and the function is a std::function<int(int)>.
This is my Action struct:
typedef std::function<int(int)> func;
struct Action {
// constructor
Action(func);
/// methods
/// operators
int operator()(int x);
/// members
func f;
};
Action(func f) {this->f = f; }
My Action struct is used by my Learning class by calling this function:
class Learning
{
public:
void addAction(Action);
Action getAction(int idx);
private:
std::vector<Action> actions;
};
void Learning::addAction(Action act)
{
actions.push_back(act);
}
int Learning::getAction(int idx)
{
return actions[idx];
}
int main(){
Learning robot;
robot.addAction(Action([](int y) ->int{return y++; }));
std::cout << robot.getAction(0)(0) << std::endl;
return 0;
}
Where the Action is saved inside an actions vector in my Learning class:
The method addAction() adds the created Action object into my actions vector. another method 'getAction(idx)' is used to call one action from action vector.
I used a lambda expression as the parameter because it looks cleaner.
But when I call robot.getAction(0)(0), or actions[0](0) inside the class, I get an exception:
Unhandled exception at 0x00007FFA4DE44F69 in RL_Q.exe: Microsoft C++ exception: std::bad_function_call at memory location 0x000000C09A7BE4C0.
When I debug this, my function f is empty after I instantiate my Action object with given parameters.
How do I solve this?
| You define
Learning::addAction(Action&)
with an action reference as argument. This means that you have to ensure the lifetime of the referenced object, and not let it get destroyed by going out of scope. But then you call it on an rvalue
// Action(...) immediately goes out of scope
robot.addAction(Action("Up", [](int y) ->int{return y++; }));
Therefore the references you put in your vectors are all invalid : they point toward long gone objects. You need to take ownership of them if you want it to work. This means :
class Learning
{
public:
void addAction(Action&&);
private:
std::vector<Action> actions;
};
// rvalue reference, so the vector can take ownership of the expiring object
void Learning::addAction(Action&& act)
{
actions.push_back(std::move(act));
}
|
70,191,042 | 70,191,520 | Call a member function with the same name as macro | Consider the following:
struct S {
void f() {}
};
#define f 42
int main() {
S s;
s.f(); // error: expected unqualified-id
}
How to call a member function S::f without undefining the macro f or changing member function name? Is it even possible?
If the macro was defined as #define f() 42 (with parentheses), I could fix the issue like (s,f)(). But there are no parentheses in macro definition.
|
How to call a member function S::f without undefining the macro f or changing member function name? Is it even possible?
It isn't possible in standard C++.
Problems such as this are the reasons why everyone recommends avoiding macros, and to separate the naming conventions between macro and non-macro identifiers.
In non standard C++ however, it is possible. Example using push and pop macro language extension:
#pragma push_macro("f")
#undef f
s.f();
#pragma pop_macro("f")
but there is WinAPI macros like SendMessage expanded to SendMessageA or SendMessageW depending on Unicode settings.
Dancing around the macros defined in various system headers is the harsh reality when you include system headers. When encountering these, it's often best to refrain from using the conflicting identifiers.
|
70,191,320 | 70,191,558 | Call the destructor of a template class, expected class-name before ‘(’ token | I have an exceptional situation where I need to call the destructor of a class to clear union memory. We can not use an std::variant yet. The class in the union is template based and defined similar to:
template<class TYPE>
class BaseTemplate
{
public:
BaseTemplate() = default;
~BaseTemplate() = default;
// Other useful functions.
private:
TYPE value;
}
Now we define different types with using:
using X = BaseTemplate<int>;
// Other using definitions
In an earlier situation X was a derived classes from BaseTemplate.
class X : public BaseTemplate<int>
{
X() = default;
~X() override = default; // In this case ~BaseTemplate was virtual.
// Nothing useful so we would like to remove this class.
};
In the old situation we were able to call the destructor like this:
X variableX;
variableX.~X();
In the new situation when using X = BaseTemplate<int>; is used this results in the error: expected class-name before ‘(’ token. So how do I call the destructor in this case?
Reproduction code:
#include <iostream>
namespace a
{
class Base
{
public:
Base() = default;
virtual ~Base() = default;
virtual void foo() = 0;
};
template<class TYPE>
class BaseTemplate : public Base
{
public:
BaseTemplate() = default;
~BaseTemplate() override = default;
// Other useful functions.
void set(const TYPE& v)
{
value = v;
}
TYPE get() const
{
return value;
}
void foo() final
{
value *= 2;
}
private:
TYPE value;
};
using X = BaseTemplate<int>;
using Y = BaseTemplate<unsigned int>;
using Z = BaseTemplate<float>;
} // End of namespace a
union XYZ
{
XYZ() {}
~XYZ() {}
a::X variableX;
a::Y variableY;
a::Z variableZ;
};
XYZ xyz;
int main()
{
// Inplace new operator to initialize x
new(&xyz.variableX) a::X;
xyz.variableX.set(1);
xyz.variableX.foo();
std::cout << "Result: " << xyz.variableX.get() << std::endl;
xyz.variableX.~X();
}
| variableX's destructor is called ~BaseTemplate(). However, if X is in scope and resolves to BaseTemplate<int>, it will also work as an alias for the destructor.
If X was not in scope:
some::random_namespace::X variableX;
// variableX.~X(); X not in scope, will not work
variableX.some::random_namespace::X::~X(); // Works, but confusing
// variableX.~decltype(variableX)(); // Supposed to work, but GCC does not like
using T = decltype(variableX); variableX.~T();
using X = some::random_namespace::X; variableX.~X();
using some::random_namespace::X; variableX.~X(); // Now in scope
The real solution is to use std::destroy_at(std::addressof(variableX))
std::destroy_at(&variableX); // Does not care about the name of the destructor
|
70,191,692 | 70,191,791 | Using '|' (pipe) operator with std::views does not compile | After a career diversion, I am trying to get up to speed with std::views (and functional programming in general). I am using the '|' (pipe) operator with std::views::filter on a vector, and I am puzzled why some code structures compile and others don't.
This code creates a vector of vectors of int, then filters them by sum. I've commented the three statements that are confusing me, the first two of which compile and the third doesn't.
Compilation error is:
'|': no operator found which takes a left-hand operand of type 'std::vector<std::vector<int,std::allocator<int>>,std::allocator<std::vector<int,std::allocator<int>>>>' (or there is no acceptable conversion)
(Using MSVC19, compiled with /std:c++latest)
I am puzzled as to why this doesn't compile while (2) especially does?
#include <vector>
#include <numeric>
#include <ranges>
template<typename T>
auto buildMultiples(const std::vector<T>& base)
{
std::vector<std::vector<T>> vRet;
for(T n= 1; n <= 5; n++)
{
auto v = base;
for (auto& m : v) m *= n;
vRet.push_back(v);
}
return vRet;
}
template<typename T>
struct sumGreaterThan
{
T _limit{ 0 };
auto operator()(const std::vector<T>& v) {return std::accumulate(v.cbegin(), v.cend(), 0) > _limit;}
};
int main()
{
using namespace std;
vector<int> nums{1,2,3,4,5,6,7,8,9};
auto mults = buildMultiples(nums);
for (auto& m : buildMultiples(nums)) {} //1. Compiles
sumGreaterThan sumFilter{ 10 };
auto vecs = buildMultiples(nums);
for (auto& m : vecs | views::filter(sumFilter)) {} //2. Compiles
for (auto& m : buildMultiples(nums) | views::filter(sumFilter)) {} //3. Compilation Error!!
for (auto vecs = buildMultiples(nums); auto & m : vecs | views::filter(sumFilter)) {} // 4. Compiles. Thanks @Aryter
}
| This is passing an lvalue vector into filter:
vecs | views::filter(sumFilter)
whereas this is passing an rvalue vector into filter:
buildMultiples(nums) | views::filter(sumFilter)
The current rule, which compilers implement, is that range adaptor pipelines cannot take rvalue non-view ranges (like vector, string, etc.). This is because the pipeline itself is non-owning (views were non-owning), and exists as a safety mechanism to prevent dangling.
The new rule, recently adopted as a defect, would allow this could and would cause filter to own the result of buildMultiples (this is P2415), but compilers don't implement it quite yet. With this change, your other version would also have compiled.
So for now, you will have to keep writing it this way (as you are already doing):
auto vecs = buildMultiples(nums);
for (auto& m : vecs | views::filter(sumFilter)) { ... }
|
70,191,997 | 70,192,120 | Is there a solution to override an argument in C++? | I just found something that I cant understand. I have a function that I want not only run in main(), but to use it in another function (for edit file) and I dont want to create an extra global variables.
int fileOut(bool = 1, char filename[] = 0);
//...
int fileOut(bool output, char filename[15]){
cin >> filename; // and if I do so, Ill got the error like this:
// Exception thrown: Write access violation. _Str was 0x1110112.
cout << filename;
return 0;
}
Soo, is theres a solution how to fix this and make possible change filename?
| In a function parameter, char filename[15] is actually treated by the compiler as simply char *filename, which you are defaulting to 0, aka NULL/nullptr. So, if the caller doesn't provide a buffer for filename, it won't point anywhere useful, so you can't write data to it, hence the crash.
In that situation, you can use a local variable to write to, eg:
int fileOut(bool output, char filename[15]){
char buffer[15] = {};
if (!filename) filename = buffer;
cin >> filename;
cout << filename;
return 0;
}
Just be careful of a buffer overflow, since the user could enter more than 15 characters! You can use cin.get() to mitigate that:
cin.get(filename, 15);
Though, you really should be using std::string instead of char[], eg:
int fileOut(bool = 1, std::string filename = "");
//...
int fileOut(bool output, std::string filename){
cin >> filename;
cout << filename;
return 0;
}
Either way, what is the point of letting the user pass in an input string if the function is just going to overwrite it? If the function always prompts the user, then just use a local variable instead of a parameter:
int fileOut(bool = 1);
//...
int fileOut(bool output){
char filename[15] = {};
cin.get(filename, 15);
cout << filename;
return 0;
}
Or:
int fileOut(bool = 1);
//...
int fileOut(bool output){
std::string filename;
cin >> filename;
cout << filename;
return 0;
}
Otherwise, if you want the caller to be able to provide a filename, and then prompt the user if no filename is given, try something more like this instead:
int fileOut(bool = 1, char filename[15] = 0);
//...
int fileOut(bool output, char filename[15]){
char buffer[15] = {};
if (!filename) filename = buffer;
if (*filename == 0)
cin.get(filename, 15);
cout << filename;
return 0;
}
Or:
int fileOut(bool = 1, std::string filename = "");
//...
int fileOut(bool output, std::string filename){
if (filename.empty())
cin >> filename;
cout << filename;
return 0;
}
|
70,192,113 | 70,192,237 | How to call macro that uses token pasting? | I am trying to print ffmpeg version in a C++ program. I see that in the /libavutil/version.h there is AV_VERSION which should tell the version number in the format x.x.x.
As a test I used some random numbers as function parameters like this: std::string version = AV_VERSION(3,4,2);. The same error I get if I use LIBAVUTIL_VERSION_MAJOR, LIBAVUTIL_VERSION_MINOR and LIBAVUTIL_VERSION_MICRO from the file. That was actually my first try to print the version number.
The error I get is invalid suffix '.2' on floating constant or invalid suffix '.101' on floating constant if I try to print std::cout << AV_VERSION(LIBAVUTIL_VERSION_MAJOR,LIBAVUTIL_VERSION_MINOR,LIBAVUTIL_VERSION_MICRO) << std::endl;
I do understand that the preprocessor is thinking that the token is a float, hence the error. How do you actually use this type of macro funtion?
That macro is in the file I mentioned above, so it must be a way to call that macro function without giving an error, thinking that is a mature library, and I guess other libraries use something similar for printing version number.
Here is how AV_VERSION is defined in the header file and how I call it:
#define AV_VERSION_INT(a, b, c) ((a)<<16 | (b)<<8 | (c))
#define AV_VERSION_DOT(a, b, c) a ##.## b ##.## c
#define AV_VERSION(a, b, c) AV_VERSION_DOT(a, b, c)
#define AV_VERSION_MAJOR(a) ((a) >> 16)
#define AV_VERSION_MINOR(a) (((a) & 0x00FF00) >> 8)
#define AV_VERSION_MICRO(a) ((a) & 0xFF)
#define LIBAVUTIL_VERSION_MAJOR 57
#define LIBAVUTIL_VERSION_MINOR 9
#define LIBAVUTIL_VERSION_MICRO 101
#define LIBAVUTIL_VERSION_INT AV_VERSION_INT(LIBAVUTIL_VERSION_MAJOR, \
LIBAVUTIL_VERSION_MINOR, \
LIBAVUTIL_VERSION_MICRO)
#define LIBAVUTIL_VERSION AV_VERSION(LIBAVUTIL_VERSION_MAJOR, \
LIBAVUTIL_VERSION_MINOR, \
LIBAVUTIL_VERSION_MICRO)
int main()
{
std::string version = AV_VERSION(3,4,2);
std::cout << AV_VERSION(LIBAVUTIL_VERSION_MAJOR,LIBAVUTIL_VERSION_MINOR,LIBAVUTIL_VERSION_MICRO) << std::endl;
return 0;
}
I coud've skip this error but as I'm trying to learn C++ I am pretty sure that I will find more of this type of macros so no point to avoid learning them now as I'm facing them.
Thanks in advance!
| You need to use a stringize expansion. Because of how the preprocessor works, this involves two macros:
#define STR(x) #x
#define XSTR(x) STR(x)
The macro STR will take whatever parameter you give it and make that a string literal.
The macro XSTR will first expand its parameter x and the result will be the parameter to STR.
To illustrate:
STR(LIBAVUTIL_VERSION) will give "LIBAVUTIL_VERSION"
XSTR(LIBAVUTIL_VERSION) will give "57.9.101"
Demo according to your code:
int main()
{
std::string version1 = XSTR(LIBAVUTIL_VERSION);
std::string version2 = XSTR(AV_VERSION(3,4,2));
std::cout << version1 << "\n";
std::cout << version2 << "\n";
return 0;
}
Output:
57.9.101
3.4.2
|
70,192,151 | 70,192,204 | How to call overridden child methods in a vector | I am trying to loop over multiple different child classes of a parent. Ideally I would like to save the child objects in a vector of smart pointers. The following outputs "Update idle" for every call to the method Update. I would like for the call to be the overridden variants of the method. What is the best way of solving this problem?
#include <iostream>
#include <memory>
#include <vector>
class Foo
{
public:
virtual void Update(){
std::cout << "Update idle" << std::endl;
};
};
class Foo1 : public Foo
{
public:
void Update() override
{
std::cout << "Update Foo1" << std::endl;
}
};
class Foo2 : public Foo
{
void Update() override
{
std::cout << Bar() << std::endl;
}
std::string Bar(){
return "Update Foo2";
}
};
int main() {
std::vector<std::shared_ptr<Foo>> vec{
std::make_shared<Foo>(Foo{}),
std::make_shared<Foo>(Foo1{}),
std::make_shared<Foo>(Foo2{})
};
for (auto &&ptr : vec)
{
ptr->Update();
}
}
| std::make_shared<T>(args) creates an new instance of T, passing args to T's constructor, and then returns that instance in a std::shared_ptr<T>.
As such, your code is not dynamically creating any Foo1 or Foo2 object for the vector at all. It is creating 3 dynamic Foo objects, all of which are copy-constructed from temporary Foo, Foo1 and Foo2 objects.
In other words:
std::make_shared<Foo>(Foo{}) is equivalent to new Foo(Foo{})
std::make_shared<Foo>(Foo1{}) is equivalent to new Foo(Foo1{})
std::make_shared<Foo>(Foo2{}) is equivalent to new Foo(Foo2{})
You actually want the equivalent of new Foo, new Foo1 and new Foo2, so use this instead:
std::vector<std::shared_ptr<Foo>> vec{
std::make_shared<Foo>(),
std::make_shared<Foo1>(),
std::make_shared<Foo2>()
};
Online Demo
Even though your std::vector holds std::shared_ptr<Foo> elements, but std::make_shared<Foo1>() will return a std::shared_ptr<Foo1>() and std::make_shared<Foo2>() will return a std::shared_ptr<Foo2>(), this is OK because std::shared_ptr<Foo1> and std::shared_ptr<Foo2> are convertible to std::shared_ptr<Foo> by virtue of the fact that Foo1 and Foo derive from Foo.
|
70,192,381 | 70,192,498 | Can I run a python script from C plus plus? | I made a basic C++ script that looks like this.
#include <iostream>
int main()
{
std::cout << "Hello World!" << std:endl;
}
I complied this and named that complied file pcpp.
Next, I made a python script named runcpp. This looks like this.
import os
com = 'sudo stdbuf -oL ./pcpp'
os.system(com)
Then, when I run this python script, I see the "Hello World!" message. However, now I want to do something totally opposite.
Let's assume I have a file name ppy.py. This has script like this.
print("Hello World!")
Now, I want to print this by running C++ compiler. How should I do this?
| If you just intend to run a Python script from C/C++ you could simply use system() to execute the Python script like system("./myscript.py"), which will use the interpreter specified in the shebang. This means say you have the script:
#!/usr/bin/python3
print("Hello!")
It will run the script using /usr/bin/python3 as that is specified in the shebang. Using system("python3 myscript.py") will use python3 in your shell's PATH.
Alternatively, if you want to execute Python code within your C++ program you can embed the Python interpreter into your program, see https://docs.python.org/3/extending/embedding.html.
|
70,192,457 | 70,192,528 | Initialize 2D array in constructor of CPP class | I was wondering what the best way to initialize a 2D array in a cpp class would be. I do not know its size until the constructor is called, ie,
Header file contains:
private:
int size;
bool* visited;
int edges;
int** matrix;
Default constructor (right now):
Digraph::Digraph(int n) {
int rows = (n * (n-1)/2);
int columns = 2;
matrix = new int[rows][2];
visited[size] = { 0 };
size = n;
edges = 0;
}
What I want is a 2D array of N rows and 2 columns.
This currently returns error: cannot convert 'int (*)[2]' to 'int**' in assignment when I try to compile.
NOTE: I cannot use Vectors, so please don't suggest them.
| matrix = new int[rows][2]; is not valid syntax. Allocating a 2D sparse array requires multiple new[] calls, eg:
private:
int size;
bool* visited;
int edges;
int** matrix;
int rows;
int columns;
...
Digraph::Digraph(int n) {
size = n;
edges = 0;
rows = (n * (n-1)/2);
columns = 2;
matrix = new int*[rows];
for(int x = 0; x < rows; ++x) {
matrix[x] = new int[columns];
for(int y = 0; y < columns; ++y)
matrix[x][y] = 0;
}
visited = new bool[size];
for(int x = 0; x < size; ++x)
visited[x] = false;
}
Digraph::~Digraph() {
for(int x = 0; x < rows; ++x) {
delete[] matrix[x];
}
delete[] matrix;
delete[] visited;
}
Alternatively, consider allocating the matrix as a 1D array, and then using 2D indexes when accessing its values, eg:
private:
int size;
bool* visited;
int edges;
int* matrix; // <-- 1 *, not 2 **
int rows;
int columns;
int& matrix_value(int row, int col) { return matrix[(row * rows) + col]; }
...
Digraph::Digraph(int n) {
size = n;
edges = 0;
rows = (n * (n-1)/2);
columns = 2;
n = rows * columns;
matrix = new int[n];
for(int x = 0; x < n; ++x)
matrix[n] = 0;
visited = new bool[size];
for(int x = 0; x < size; ++x)
visited[x] = false;
}
Digraph::~Digraph() {
delete[] matrix;
delete[] visited;
}
Either way, you will also need to implement (or disable) a copy constructor and copy assignment operator, and preferably a move constructor and move assignment operator, per the Rule of 3/5/0, eg:
Digraph::Digraph(const Digraph &src) {
size = src.size;
edges = src.edges;
rows = src.rows;
columns = src.columns;
matrix = new int*[rows];
for(int x = 0; x < rows; ++x) {
matrix[x] = new int[columns];
for (int y = 0; y < columns; ++y)
matrix[x][y] = src.matrix[x][y];
}
/* or:
n = rows * columns;
matrix = new int[n];
for(int x = 0; x < n; ++x)
matrix[n] = src.matrix[n];
*/
visited = new bool[size];
for(int x = 0; x < size; ++x)
visited[x] = src.visited[x];
}
Digraph::Digraph(Digraph &&src) {
size = 0;
edges = 0;
rows = 0;
columns = 0;
matrix = nullptr;
visited = nullptr;
src.swap(*this);
}
void Digraph::swap(Digraph &other) {
std::swap(size, other.size);
std::swap(edges, other.edges);
std::swap(rows, other.rows);
std::swap(columns, other.columns);
std::swap(matrix, src.matrix);
std::swap(visited, src.visited);
}
Digraph& Digraph::operator=(Digraph rhs) {
Digraph temp(std::move(rhs));
temp.swap(*this);
return this;
}
That being said, a better design would be to use std::vector instead of new[], and let it handle all of the memory management and copying/moving for you, eg:
#include <vector>
private:
int size;
std::vector<bool> visited;
int edges;
std::vector<std::vector<int>> matrix;
// or: std::vector<int> matrix;
int rows;
int columns;
...
Digraph::Digraph(int n) {
size = n;
edges = 0;
rows = (n * (n-1)/2);
columns = 2;
matrix.resize(rows);
for(int x = 0; x < rows; ++x)
matrix[x].resize(columns);
/* or:
matrix.resize(rows * columns);
*/
visited.resize(size);
}
// implicitly-generated copy/move constructors, copy/move assignment operators,
// and destructor will suffice, so no need to implement them manually...
If you can't use std::vector, consider implementing your own vector class with the proper semantics, and then use that instead. You should really strive to follow the Rule of 0 as much as possible, by using classes that implement the Rule of 3/5 for you.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.