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 |
|---|---|---|---|---|
72,136,219 | 72,136,351 | Creating a tuple from a folding expression return values | I try using the returning values of DecodeInternal function to create a tuple like this.
std::tuple<Types...> Decode(const uint8_t *bufferBegin)
{
uint8_t *offset = (uint8_t *)bufferBegin;
// (DecodeInternal<Types>(f, &offset), ...);
return std::make_tuple<Types...>((DecodeInternal<Types>(&offset), ...));
}
But when I compile with this template arguments
decoder.Decode<int, float, bool, std::string, std::string>(encoder.GetBuffer().data());
I get this error from the compiler
In file included from ./borsh-cpp/src/main.cpp:4:
./borsh-cpp/src/BorshCpp.hpp: In instantiation of ‘std::tuple<_Tps ...> BorshDecoder::Decode(const uint8_t*) [with Types = {int, float, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >}; uint8_t = unsigned char]’:
./borsh-cpp/src/main.cpp:42:110: required from here
./borsh-cpp/src/BorshCpp.hpp:244:35: error: invalid initialization of reference of type ‘int&&’ from expression of type ‘std::__cxx11::basic_string<char>’
244 | return std::make_tuple<Types...>((DecodeInternal<Types>(f, &offset), ...));
| ~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/include/c++/9/functional:54,
from ./borsh-cpp/src/BorshCpp.hpp:4,
from ./borsh-cpp/src/main.cpp:4:
/usr/include/c++/9/tuple:1470:27: note: in passing argument 1 of ‘constexpr std::tuple<typename std::__decay_and_strip<_Elements>::__type ...> std::make_tuple(_Elements&& ...) [with _Elements = {int, float, bool, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >}]’
1470 | make_tuple(_Elements&&... __args)
| (DecodeInternal<Types>(&offset), ...) is a comma operator whose value is equal to the result of the last expression. Also, you don't need to explicitly specify template arguments for make_tuple, so just
return std::make_tuple(DecodeInternal<Types>(&offset)...);
|
72,136,480 | 72,136,627 | comparing bytes in google unit test framework | I have a following test case where I want to compare bytes in google test. In Unity unit test frame work we have
TEST_ASSERT_BYTES_EQUAL(0xaa, output[4]);
Is similar ASSERT available in google test. I have following code in google test and test case failing.
TEST(sprintf, NoBufferOverRunsForNoFormatOperations) {
char output[5];
memset(output, 0xaa, sizeof output);
ASSERT_EQ(3, sprintf_s(output, "hey"));
ASSERT_STREQ("hey", output);
ASSERT_THAT(0xaa, output[4]);
}
Failed log
[ RUN ] sprintf.NoBufferOverRunsForNoFormatOperations
Value of: 0xaa
Expected: is equal to -86
Actual: 170 (of type int)
[ FAILED ] sprintf.NoBufferOverRunsForNoFormatOperations (0 ms)
Any clues and help are welcome.
| The problem is that you are comparing 0xaa, a literal of type int with a value of decimal 170, with the value of output[4] which is itself of type char. char is a signed type in C and C++. You wrote 0xaa or binary 10101010 into the byte in question. Because it is interpreted as a signed number, the leading 1 is considered as the sign bit in two's complement (which is undefined behavior up until C++20 I think) which gives it a value of -86 = 170 - 256.
|
72,136,940 | 72,137,133 | How to put a part of variable argument list into another function? | I'm dealing with such a problem, I have function f(std::initializer_list<double> list),and I want to put a part of variable argument list (the second variable argument to end) into another function like:
void f(std::initializer_list<double> list){
f1(*(list.begin()+1,...,*(list.end-1));
}
The f1 function is normal function like void f1(double x) or void f1(double x1,double x2), I want f can do with different variable argument number of f1, how can I get it?
| An initializer list does not seem to have constructors which take a pair of iterators, see here. But you can use a span for that:
#include<iostream>
#include<span>
void f1(double a, double b)
{
}
void f2(auto list)
{
for(auto i : list)
{
std::cout<<i<<std::endl;
}
}
void f(std::initializer_list<double> list){
size_t size = std::distance(std::begin(list),std::end(list))-1;
auto list = std::span{std::next(std::begin(list)), size};
f1(list[0],list[1]);
f2(list);
}
int main()
{
auto a = std::initializer_list<double>{1.0,2.0,3.0};
f(a);
}
DEMO
Note that the previous code can be made more generic. But it should be ok to get the idea.
|
72,137,275 | 72,137,788 | C++ union struct with struct member works on Clang and MSVC but not GCC | I am trying to define a union struct with some struct and primitive members overlapping in memory with a simple array. This works perfectly in Clang and MSVC, but it doesn't compile with GCC (G++).
struct Vector3 {
float x;
float y;
float z;
Vector3() {}
};
struct Plane {
union {
struct {
Vector3 normal;
float d;
};
float elements[4] = { 0 };
};
Plane() {}
};
With GCC, I get this compile error:
<source>:11:33: error: member 'Vector3 Plane::<unnamed union>::<unnamed struct>::normal' with constructor not allowed in anonymous aggregate
11 | Vector3 normal;
| ^~~~~~
Is the code example I gave valid C++? Why specifically is it not allowed in an anonymous aggregate, but it seems to work in a named one? What can I change about it to make it work in GCC that doesn't involve deleting the constructors or naming the struct in the union? What is the reason that it works in Clang and MSVC but not in GCC?
Is there a way to make it work if I replace struct { with struct Named {?
|
Is the code example I gave valid C++?
No. Anonymous structs are not allowed, so the program is ill-formed.
What is the reason that it works in Clang and MSVC
When an ill-formed program works, it is often due to a language extension.
but not in GCC
Differences in implementation of similar language extension perhaps. The limitations of such extension are not defined by the language of course. Since this extension is based on a C language feature, it sort of makes sense that it doesn't necessarily work with C++ features such as constructors.
What can I change about it to make it work in GCC that doesn't involve deleting the constructors or naming the struct in the union?
Only way to make the program well defined C++ is to not use an anonymous struct.
Bonus answer: If you were hoping to read elements after having written to normal or d or vice versa, then that's not allowed either. The behaviour of the program would be undefined.
How can I make differently named properties with overlapping memory? Aside from Plane, I also want to do this in other structs, such as by having a 3D Basis struct columns[3] with the array's members also accessible via x, y, and z.
C++ is limited in this regard and it cannot be done in a simple way. It can be done with a bit of complexity by relying on operator overloads:
template<class T, std::size_t size, std::size_t i>
struct Pun {
T a[size];
static_assert(i < size);
auto& operator=(T f) { a[i] = f; return *this; }
operator T&() & { return a[i]; }
operator const T&() const & { return a[i]; }
operator T () && { return a[i]; }
T * operator&() & { return a+i ; }
T const* operator&() const & { return a+i ; }
};
template<class T, std::size_t size>
struct Pun<T, size, size> {
T a[size];
using A = T[size];
operator A&() & { return a; }
operator const A&() const & { return a; }
A * operator&() & { return &a; }
A const* operator&() const & { return &a; }
};
union Plane {
Pun<float, 4, 4> elements;
Pun<float, 4, 0> x;
Pun<float, 4, 1> y;
Pun<float, 4, 2> z;
Pun<float, 4, 3> d;
};
Reading inactive members of Plane is allowed, because all elements are layout compatible structs. x etc. can implicitly convert to float and elements can implicitly convert to an array of float.
|
72,137,715 | 72,138,601 | Handle multiply cameras in Vulkan | I'm trying to implement rendering with different cameras.
When I use only one camera, everything is ok. But when I have two cameras with different transformation, rendering doesn't work properly, first scene is rendered with second camera transformation.
void Setup() {
...
// create uniform buffer (vmaCreateBuffer)
global_uniform_buffer = ...
// allocate descriptor set
global_descriptor_set = ...
// write descriptor set
...
}
void SetCameraProperties(Camera* camera) {
auto proj_view = camera->GetProjectionMatrix() * camera->GetViewMatrix();
global_uniform_buffer->update(&proj_view, sizeof(glm::mat4));
}
void BindGlobalDescriptorSet(vk::CommandBuffer cmd, vk::PipelineLayout pipeline_layout) {
cmd.bindDescriptorSets(
vk::PipelineBindPoint::eGraphics,
pipeline_layout,
0,
{ global_descriptor_set },
{}
);
}
void DrawScene() {
...
cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
BindGlobalDescriptorSet(cmd, pipeline_layout);
cmd.bindVertexBuffers(0, vtx->handle, vk::DeviceSize{0});
cmd.bindIndexBuffer(idx->handle, vk::DeviceSize{0}, vk::IndexType::eUint16);
cmd.drawIndexed(3, 1, 0, 0, 0);
...
}
void Loop() {
... // begin render pass with scene framebuffer
SetCameraProperties(Editor::Get()->GetEditorCamera()):
DrawScene();
... // end previous render pass
... // begin render pass with game frame buffer
SetCameraProperties(CameraSystem::Get()->GetMainCamera()):
DrawScene();
... // end previous render pass
... // present
}
| Looking at your code, you change the same uniform buffer between two draw calls at command buffer creation time. But the contents of the bound uniform buffer are consumed at submission time instead and not at creation time. So by the time you submit your command buffer, it uses the uniform buffer contents from your last update.
So your current setup won't work in Vulkan that way. To make this work, you could use one UBO per camera or one dynamic UBO with separate ranges for the cameras.
|
72,138,134 | 72,138,598 | How to subtract char out from string in c++? | Hello I want to know how to subract string from string
For example
If string s = "124ab"
I can easily extract integer by using sstream but I don't know how to extract string
I want to extract ab from s;
I have tons of string and they don't have any rule.
s can be "3456fdhgab" or "34a678"
| You can use std::isdigit to check if a character is a digit. You can use the erase-remove idiom to remove characters that are digits.
Because std::isdigit has an overload it has to be wrapped in a lambda to be used in the algorithm:
#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
int main() {
std::string inp{"124ab"};
inp.erase(std::remove_if(inp.begin(),inp.end(),[](char c){return std::isdigit(c);}),inp.end());
std::cout << inp;
}
Output:
ab
And because you asked for using a stringstream, here is how you can extract non-digits with a custom operator<<:
#include <string>
#include <iostream>
#include <cctype>
#include <sstream>
struct only_non_digits {
std::string& data;
};
std::ostream& operator<<(std::ostream& os, const only_non_digits& x) {
for (const auto& c : x.data){
if (std::isdigit(c)) continue;
os << c;
}
return os;
}
int main() {
std::string inp{"124ab"};
std::cout << only_non_digits{inp} << "\n";
std::stringstream ss;
ss << only_non_digits{inp};
std::cout << ss.str() << "\n";
}
Output:
ab
ab
|
72,138,147 | 72,138,226 | Weird bug in pointers | I was trying to access single bytes of an int value via the code below. My problem is that whenever I try to remove long int i=0; from the code, it gives me a segmentation fault. Is there any reason this happens? I am not using I anywhere in the code.
// Online C++ compiler to run C++ program online
#include <iostream>
int main() {
// Write C++ code here
unsigned int* a;
unsigned char* b1;
unsigned char* b2;
unsigned char* b3;
unsigned char* b4;
*a= 4294967295; //set to max val (4 bytes)
//*************************
long int i=0;//Q. Why long int/long long int?
//*************************
b1 = (unsigned char*)(a);
b2 = b1+(long long int)1;
b3 = b1+(long long int)2;
b4 = b1+(long long int)3;
std::cout <<*a<<" "<<(int)*b1<<" "<<(int)*b2<<" "<<(int)*b3<<" "<<(int)*b4<<std::endl;
return 0;
}
| This exhibits undefined behavior:
unsigned int* a;
*a= 4294967295; //set to max val (4 bytes)
The pointer variable a is never initialized to anything, so it points to a random memory address. Writing anything to that random garbage address (typically) causes a segmentation fault. It's just coincidence that adding another variable changes the behavior (due to a change in memory layout of the program).
|
72,138,637 | 73,205,183 | Remote Desktop - getting session information (id, session name, etc.) from client side | Let's consider the following scenario: take a Windows Server instance (2012 or newer), with multiple user accounts. Each of those accounts needs to run an individual instance of a target application, which requires an active GUI as well as orchestration, in an automated fashion. We have no control over this target application so we need to work around it.
After much research and experimenting trying to programmatically create interactive windows sessions (with a GUI) using win32 APIs such as WTS calls (or even LsaLogonUser), we gave up and tried creating these sessions using rdp or freerdp. This manages to create the required sessions.
Now for the issue at hand. Due to the nature of the target application as well as the fact that it requires orchestration and autonomous running (it needs to be triggered remotely, without user intervention), we opted for the following architecture:
a windows service that exposes an API (which can be used as the trigger) - let's call this the "command center".
a user-level application that is run automatically when each user logs on and receives commands from the previously mentioned service (via named pipes). Let's call this the "agent". This agent then automates the target application in respect to the commands received from the command center.
In order for the command center to properly push commands to each agent, each agent features a named pipe server that's named uniquely: agent_[username]_[sessionid]. This ensures that even if a particular user has multiple sessions running multiple agents, each one can be controlled individually.
In terms of triggering this functionality this is the flow:
an HTTP Rest request is sent to the command center
the command center programmatically creates a new session for the designated user using freerdp (C# with some C++)
the session is created and the agent starts automatically (from a scheduled task)
once the session is up and running the command center connects to the agent via the target named pipe server (as described in the naming scheme above).
Everything up to step 3 is done and works correctly, however, we're having issues determining the session id (and other session data) when creating new sessions (step 2), so that the command center knows the string id for the named pipe server (agent) which it needs to send commands to. In essence, it knows the username for which the session has been created but it lacks the session id.
What we need to do is figure out how to grab session data (mainly the session id) from the new freerdp session that's created. What we've thought about but haven't managed:
Querying session info using the WTSQuerySessionInformationA API call - this is not really robust enough as you can't really reliably monitor newly created sessions and reconciliate with existing sessions for the same user.
Creating the new freerdp session with custom session names (such as GUID), which would allow us to confidently identify and link sessions using the above API call. So far, all sessions that are created with freerdp have blank session names, so we haven't been able to assign custom names, but this might be a solution.
Retrieving client info from the rdp_rdp object we're using to create the session - no luck so far, as the documentation is pretty limited and we haven't managed to obtain this information - this however seems like the most direct and sure way to solve our issue.
To sum things up, we need a way to communicate between multiple distinctly named agents and a service app - and for this we need to determine the session id or name for each newly created windows session. Is there any way to do this, or maybe alternative approaches we haven't though about?
Many thanks!
| To come back on this, I have not found any viable way of setting custom session id for newly created session using freerdp. It might be possible if someone studied the whole protocol and reverse engineered the freerdp project, but it's a titanic task.
In the end, we imposed a restriction of a single active session per user. This allows us to easily query and communicate with the mentioned agents using a named pipe server.
|
72,138,731 | 72,138,798 | Vector point std::vector<cv::Point> | I am trying to draw a trajectory on an image and saving these trajectory points as std::vector<cv::Point> trajectoryPoint and I would like to access the data inside.
This a short snippet from my code:
cv::line(currentFrame, trajectoryPoint.back(), cv::Point(x, y), Scalar(255, 255, 255), 1, 8);
trajectoryPoint.push_back(Point(x, y));
std::cout << trajectoryPoint.at() << std::endl;
Normally, in Matlab it is easy to see the data inside vectors. However, I don't know how to continuously print out the data while drawing in C++ inside trajectoryPoint. Any suggestions?
| you can try to wrap a cv::Mat around it (which has nice printing ops):
std::vector<cv::Point> trajectoryPoint = ...
cv::Mat viz(trajectoryPoint);
std::cout << viz << std::endl;
|
72,138,745 | 72,138,836 | Incrementing iterator from end to begin | I want to iterate over a vector and when reaching the end it should loop back to the front.
This is a small example which does not compile
#include <vector>
std::vector<int>::iterator Next(const std::vector<int>& vec,
const std::vector<int>::iterator it)
{
auto itNext = it+1;
if (itNext == vec.end())
itNext = vec.begin(); // breaks
return itNext;
}
int main()
{
std::vector x{0, 2, 3, 4};
auto it = x.begin()+1;
return *Next(x,it);
}
and here a godbolt link.
The issue arises because of no available conversion between vector::const_iterator (result of begin()) and vector::iterator.
How can one fix this issue?
| You cannot convert a const_iterator to an iterator because this would break const-correctness.
You basically have two options. When it is ok to return a const_iterator then return a const_iterator:
#include <vector>
std::vector<int>::const_iterator Next(const std::vector<int>& vec,
std::vector<int>::const_iterator it)
{
auto itNext = it+1;
if (itNext == vec.end())
itNext = vec.begin();
return itNext;
}
int main()
{
std::vector x{0, 2, 3, 4};
auto it = x.begin()+1;
return *Next(x,it);
}
You can only get a const_iterator from a const std::vector&. Hence if you want to return an iterator the vector has to be passes as non-const reference:
#include <vector>
std::vector<int>::iterator Next(std::vector<int>& vec,
std::vector<int>::iterator it)
{
auto itNext = it+1;
if (itNext == vec.end())
itNext = vec.begin();
return itNext;
}
int main()
{
std::vector x{0, 2, 3, 4};
auto it = x.begin()+1;
return *Next(x,it);
}
To have both in one I would pass iterators and make the function a template, so it can be used with iterator or const_iterator. The function might grant you non-const access to the vectors elements, but for the function itself it doesn't matter that much if the iterators are const or not.
#include <vector>
template <typename IT>
IT Next(IT it,IT begin,IT end) {
auto itNext = it+1;
return (itNext == end) ? begin : itNext;
}
int main()
{
std::vector x{0, 2, 3, 4};
auto it = x.begin()+1;
auto it2 = Next(it,x.begin(),x.end());
*it2 = 42;
}
|
72,139,268 | 72,139,527 | Why does an optional argument in a template constructor for enable_if help the compiler to deduce the template parameter? | The minimal example is rather short:
#include <iostream>
#include <array>
#include <type_traits>
struct Foo{
//template <class C>
//Foo(C col, typename std::enable_if<true,C>::type* = 0){
// std::cout << "optional argument constructor works" << std::endl;
//}
template <class C>
Foo(typename std::enable_if<true, C>::type col){
std::cout << "no optional argument constructor works NOT" << std::endl;
}
};
int main()
{
auto foo = Foo(std::array<bool,3>{0,0,1});
}
The first constructor works as expected. However the second constructor does not compile and I get
error: no matching function for call to ‘Foo::Foo(std::array)’
However the given explanation
note: template argument deduction/substitution failed
does not help, as std::enable_if<true, C>::type should be C and such the first argument in both constructors should look exactly the same to the compiler. I'm clearly missing something. Why is the compiler behaving differently and are there any other solution for constructors and enable_if, which do not use an optional argument?
Complete error message:
main.cpp:18:45: error: no matching function for call to ‘Foo::Foo(std::array)’
18 | auto foo = Foo(std::array<bool,3>{0,0,1});
| ^
main.cpp:11:5: note: candidate: ‘template Foo::Foo(typename std::enable_if::type)’
11 | Foo(typename std::enable_if<true, C>::type col){
| ^~~
main.cpp:11:5: note: template argument deduction/substitution failed:
main.cpp:18:45: note: couldn’t deduce template parameter ‘C’
18 | auto foo = Foo(std::array<bool,3>{0,0,1});
| ^
main.cpp:5:8: note: candidate: ‘constexpr Foo::Foo(const Foo&)’
5 | struct Foo{
| ^~~
main.cpp:5:8: note: no known conversion for argument 1 from ‘std::array’ to ‘const Foo&’
main.cpp:5:8: note: candidate: ‘constexpr Foo::Foo(Foo&&)’
main.cpp:5:8: note: no known conversion for argument 1 from ‘std::array’ to ‘Foo&&’
| Template argument deduction does not work this way.
Suppose you have a template and a function using a type alias of that template:
template <typename T>
struct foo;
template <typename S>
void bar(foo<S>::type x) {}
When you call the function, eg foo(1) then the compiler will not try all instantiations of foo to see if any has a type that matches the type of 1. And it cannot do that because foo::type is not necessarily unambiguous. It could be that different instantiations have the same foo<T>::type:
template <>
struct foo<int> { using type = int; };
template <>
struct foo<double> { using type = int; };
Instead of even attempting this route and potentially resulting in ambiguity, foo<S>::type x is a nondeduced context. For details see What is a nondeduced context?.
|
72,139,531 | 72,139,662 | why do i getting boost.URL linking error? | This is my project :
https://github.com/Naseefabu/HFTBOT/blob/master/src/main.cpp
When i try to build it,
Error :
https://gist.github.com/Naseefabu/5a114956f39b6c853916bcaf66f939e4
Is it because that i included boost/url/src.hpp in both httpClient.cpp and httpClient.hpp ??
What's the solution here ?
please help and advance thanks!
| From the URL library:
To use as header-only; that is, to eliminate the requirement to link a program to a static or dynamic Boost.URL library, simply place the following line in exactly one new or existing source file in your project.
#include <boost/url/src.hpp>
[Emphasis mine]
You include that header file in one of your own header files, which is included in both your source files.
As the documentation says, it should be included in only one source file (my recommendation is that you do it in a separate source file, for that specific purpose).
|
72,139,656 | 72,139,888 | Unique_ptr in a class | The Human class turned out to be non-copied, since it contains a field of type unique_ptr, for which the copy constructor and the copying assignment operator have been removed. This prevents the compiler from automatically generating a copy constructor and assignment operator for the Human class.
How can I implement a copy constructor and a copy assignment operator in the Human class? A copy of the human must own a copy of the cat, if the original human owned it.
struct Cat {
Cat(const string& name, int age)
: name_(name)
, age_(age) //
{
}
const string& GetName() const noexcept {
return name_;
}
int GetAge() const noexcept {
return age_;
}
~Cat() {
}
void Speak() const {
cout << "Meow!"s << endl;
}
private:
string name_;
int age_;
};
unique_ptr<Cat> CreateCat(const string& name) {
return make_unique<Cat>(name, 2);
}
class Human {
public:
explicit Human(const string& name)
: name_(name) {
}
const string& GetName() const noexcept {
return name_;
}
void SetCat(unique_ptr<Cat>&& cat) noexcept {
cat_ = std::move(cat);
}
unique_ptr<Cat> ReleaseCat() noexcept {
return std::move(cat_);
}
private:
string name_;
unique_ptr<Cat> cat_;
};
| Your copy constructor might look like
Human::Human(const Human& rhs) :
name_(rhs.name_),
cat_(rhs.cat_ ? std::make_unique<Cat>(*rhs.cat_) : std::nullptr)
{}
but getting rid of std::unique_ptr and having Cat by value (or std::optional<Cat>) would be simpler:
Human::Human(const Human&) = default;
If Cat is polymorphic, a clone method would be required:
Human::Human(const Human& rhs) :
name_(rhs.name_),
animal_(rhs.animal_ ? rhs.animal_->clone() : std::nullptr)
{}
|
72,139,821 | 72,139,959 | Pass reference to function that takes `std::unique_ptr` | I have a reference to my object of type MyType, but I need to call a function, say myFunction that takes a std::unique_ptr<MyType>. What is the correct way to call myFunction? My attempt below seems to cause an "invalid pointer" error:
#include <memory>
class MyType {};
MyType myGlobalObj;
MyType& myGetter () {
return myGlobalObj;
}
void myFunction (std::unique_ptr<MyType> ptr) {
// Do important stuff
}
int main () {
MyType& myObj = myGetter();
std::unique_ptr<MyType> myPtr;
myPtr.reset(&myObj);
myFunction(std::move(myPtr)); // This causes "invalid pointer" at run time.
myPtr.release();
return 0;
}
| What you are trying to do is not possible without either doing a (deep-)copy of myGlobalObj or modifying myFunction.
A std::unique_ptr takes ownership of the memory that is used to store the contained object. That means that the std::unique_ptr may free (or reallocate, or whatever) the memory that it 'owns'. What it would do in your case: As soon as the ptr variable goes out of scope at the end of myFunction, it will attempt to free the memory that it points to. Since myGlobalObj is a global variable, its memory may never be freed (before a controlled shutdown of your program…)
Thus, you should not ever wrestle a global object into a std::unique_ptr (or a std::shared_ptr, for that matter). If there is really no way of refactoring that method to take anything else than a std::unique_ptr, you must make a copy (on the heap!) of myGlobalObj, wrap that into a std::unique_ptr, and pass it to myFunction. Keep in mind that this way, myFunction loses the ability to modify myGlobalObj.
|
72,140,255 | 72,140,567 | Tokenize a std::string to a struct | Let's say I have the following string that I want to tokenize as per the delimiter '>':
std::string veg = "orange>kiwi>apple>potato";
I want every item in the string to be placed in a structure that has the following format:
struct pack_item
{
std::string it1;
std::string it2;
std::string it3;
std::string it4;
};
I know how to do it this way:
pack_item pitem;
std::stringstream veg_ss(veg);
std::string veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it1 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it2 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it3 = veg_item;
std::getline(veg_ss, veg_item, '>')
pitem.it4 = veg_item;
Is there a better and one-liner kind of way to do it?
| You don't need an intermediate variable.
pack_item pitem;
std::stringstream veg_ss(veg);
std::getline(veg_ss, pitem.it1, '>');
std::getline(veg_ss, pitem.it2, '>');
std::getline(veg_ss, pitem.it3, '>');
std::getline(veg_ss, pitem.it4, '>');
You might want to make that a function, e.g. operator >> (with a similar operator <<)
std::istream& operator >>(std::istream& is, pack_item & pitem) {
std::getline(is, pitem.it1, '>');
std::getline(is, pitem.it2, '>');
std::getline(is, pitem.it3, '>');
std::getline(is, pitem.it4, '>');
return is;
}
std::ostream& operator <<(std::ostream& os, pack_item & pitem) {
return os << pitem.it1 << '>'
<< pitem.it2 << '>'
<< pitem.it3 << '>'
<< pitem.it4 << '>';
}
int main() {
std::stringstream veg_ss("orange>kiwi>apple>potato>");
pack_item pitem;
veg_ss >> pitem;
}
Is there a better and one-liner kind of way to do it?
You can make a type who's >> reads in a string up to a delimiter, and read all four elements in one statement. Is that really "better"?
template <bool is_const>
struct delimited_string;
template<>
struct delimited_string<true> {
const std::string & string;
char delim;
};
template<>
struct delimited_string<false> {
std::string & string;
char delim;
};
delimited_string(const std::string &, char) -> delimited_string<true>;
delimited_string(std::string &, char) -> delimited_string<false>;
std::istream& operator >>(std::istream& is, delimited_string<false> s) {
return std::getline(is, s.string, s.delim);
}
template <bool is_const>
std::ostream& operator <<(std::ostream& os, delimited_string<is_const> s) {
return os << s.string << s.delim;
}
std::istream& operator >>(std::istream& is, pack_item & pitem) {
return is >> delimited_string { pitem.it1, '>' }
>> delimited_string { pitem.it2, '>' }
>> delimited_string { pitem.it3, '>' }
>> delimited_string { pitem.it4, '>' };
}
std::ostream& operator <<(std::ostream& os, const pack_item & pitem) {
return os << delimited_string { pitem.it1, '>' }
<< delimited_string { pitem.it2, '>' }
<< delimited_string { pitem.it3, '>' }
<< delimited_string { pitem.it4, '>' };
}
|
72,140,974 | 72,141,207 | What is underlying data structure of std::deque and how does it's iterator work? | I know that std::deque has the different chunks of contiguous memory and iterator is invalidated by inserting or erasing the middle of deque.
In addition to it, if I insert to the end side of element of deque, iterator is not valid but reference is valid.
There are some other unintuitive behavior of iterator of deque. Refer to the link below.
enter link description here
I'm very curious why does the iterator should work like that. If I know the underlying data structure of deque, I can clearly understand it. But I can't find any detailed explanation of how does std::deque works yet.
Could anyone explain the underlying data structure of std::deque and why it's iterator works like that ?
| The key point is that a deque is made of several chunks of contiguous memory.
When you add an element in the first position then there are two situations:
Either the first chunk has still place to add an element:
| | | first element | second element | .... | ...
^
inserted element can be placed here
Or there is no place in the first chunk, then the inserted element is placed in a different chunk that was empty before the insertion.
In both cases, the elements that were already in the container need not be moved in memory. Hence references to them are still valid. Iterators are different, because they need addtional book-keeping (for example to reach the next chunk when you increment an iterator to the last element in a contiguous chunk). The same holds for inserting an element at the end. Inserting elements in the middle however requires to rearrange already existing elements.
|
72,141,695 | 72,141,778 | How arrays with an empty size works in c++? | I'm reading some materials about C++ and I just saw that array can be declared without a size (ex. int arr[], char x[][10]) and I'm wondering how/when it's actually used. Could someone explain both examples, please?
A more explicit example:
void foo(char[][10]);
Does that mean that any array like a[n][10], a[m][10] can be passed to the above function?
|
Does that mean that any array like a[n][10], a[m][10] can be passed to the above function?
Yes. The function signature void foo(char[][10]); is allowed as long as you pass a compatible argument, i.e. a char array with 2 dimensions in which the second has size 10.
In fact, technically, the argument will decay to a pointer, so it's the same as having void foo(char (*)[10]);, a pointer to array of ten, in this case chars. An argument of type char[] will also decay, this time to a pointer to char (char*).
Furthermore omitting the first dimension of an array is permitted on declaration as long as you initialize it. The fist dimension of the array will be deduced by the compiler based on the initialization content, i.e.:
int arr[]{1,2};
will have size 2 (arr[2]) whereas
int arr[][2]{{1,2},{2,4}};
will become arr[2][2] based on the aggregate initialization.
|
72,142,124 | 72,142,944 | Datetime parse and format in C++ | I'm using time_point the first time.
I want to parse datetime from string and found a difference when returning back to string from 1 hour.
std::chrono::system_clock::time_point timePoint;
std::stringstream ss("2021-01-01 00:00:09+01");
std::chrono::from_stream(ss, "%F %T%z", timePoint);
// timePoint == {_MyDur={_MyRep=16094556090000000 } }
std::string timePointStr = std::format("{:%Y/%m/%d %T}", floor<std::chrono::seconds>(timePoint));
// timePointStr = "2020/12/31 23:00:09"
I don't know what is wrong: the timepoint and the parsing or the formatting to string?
How can I get the same format as the parsed one?
| This is the expected behavior.
Explanation:
system_clock::time_point, and more generally, all time_points based on system_clock, have the semantics of Unix Time. This is a count of time since 1970-01-01 00:00:00 UTC, excluding leap seconds.
So when "2021-01-01 00:00:09+01" is parsed into a system_clock::time_point, the "2021-01-01 00:00:09" is interpreted as local time, and the "+01" is used to transform that local time into UTC. When formatting back out, there is no corresponding transformation back to local time (though that is possible with additional syntax1). The format statement simply prints out the UTC time (an hour earlier).
If you would prefer to parse "2021-01-01 00:00:09+01" without the transformation to UTC, that can be done by parsing into a std::chrono::local_time of whatever precision you desire. For example:
std::chrono::local_seconds timePoint;
std::stringstream ss("2021-01-01 00:00:09+01");
from_stream(ss, "%F %T%z", timePoint);
...
Now when you print it back out, you will get "2021/01/01 00:00:09". However the value in the rep is now 1609459209 (3600 seconds later).
1 To format out at sys_time as a local_time with a UTC offset of 1h it is necessary to choose a time_zone with a UTC offset of 1h at least at the UTC time you are formatting. For example the IANA time zone of "Etc/GMT-1" always has an offset of 1h ... yes, the signs of the offset are reversed. Using this to transform 2020-12-31 23:00:09 UTC back to 2021-01-01 00:00:09 would look like:
std::chrono::sys_seconds timePoint;
std::stringstream ss("2021-01-01 00:00:09+01");
std::chrono::from_stream(ss, "%F %T%z", timePoint);
// timePoint == 2020-12-31 23:00:09 UTC
std::string timePointStr = std::format("{:%Y/%m/%d %T}",
std::chrono::zoned_time{"Etc/GMT-1", timePoint});
cout << timePointStr << '\n'; // 2021/01/01 00:00:09
Disclaimer: I do not currently have a way to verify that MSVC supports the "Etc/GMT-1" std::chrono::time_zone.
Fwiw, using "Africa/Algiers" or "Europe/Amsterdam" in place of "Etc/GMT-1" should give the same result for this specific time stamp. And if your computer has its local time zone set to something that has a 1h UTC offset for this timestamp, then std::chrono::current_zone() in place of of "Etc/GMT-1" will also give the same result.
|
72,142,269 | 72,143,598 | How to interpret the explicit cast operator | As we can invoke the explicit cast operator, using static_cast, a C-style cast, or a constructor style cast. I am confusing how exactly the operator interpret to these three casts.
For example, consider the following code. The const Money& balance in display_balance() can be cast to double in three ways. So what are these cast interpret. What I thought is there is only one explicit cast operator in Money, so the calling may would be balance.operator (). I really can't figure out how does the three different casting be interpreted.
class Money
{
public:
Money() : amount{ 0.0 } {};
Money(double _amount) : amount{ _amount } {};
explicit operator double() const { return amount; }
private:
double amount;
};
void display_balance(const Money& balance)
{
std::cout << "The balance is: " << (double)balance << "\n";
std::cout << "The balance is: " << double(balance) << "\n";
std::cout << "The balance is: " << static_cast<double>(balance) << "\n";
}
| Type Casting
It isn't the syntax you use when casting that determines how that cast is performed, it's the context based on the variable types.
When the compiler sees that you're trying to cast from Money to double, it tries to figure out a way to accomplish that - in every case, it uses the Money::operator double() operator because in every case double was specified as the target type.
C++ almost always allows you to accomplish one task in multiple different ways due to historical reasons; even its name alludes to its original goal: extending the C language.
Consider the following syntaxes:
Money balance(100.0);
// C-Style Cast
(double)balance; //< double with value 100.0
// Functional Cast
double(balance); //< double with value 100.0
double{ balance }; //< double with value 100.0
// Static Cast
static_cast<double>(balance); //< double with value 100.0
Once this is compiled, there isn't really any difference in which syntax you used; all of them call Money::operator double().
Of course, casting is always subject to operator precedence.
Note: While in this case all of the approaches are the same, this is not true in all cases.
Whenever possible, use static_cast instead of c-style or functional casts - you can read more about why here.
Explicit vs. Implicit Type Casting
Consider the following objects:
Money is your class.
Cash is a copy of Money that allows implicit casting.
class Money
{
public:
Money() : amount{ 0.0 } {};
Money(double _amount) : amount{ _amount } {};
// This is an explicit casting operator:
explicit operator double() const { return amount; }
private:
double amount;
};
class Cash
{
public:
Cash() : amount{ 0.0 } {};
Cash(double _amount) : amount{ _amount } {};
// This is an implicit casting operator
operator double() const { return amount; }
private:
double amount;
};
Now consider the following function that accepts a double:
void BuySomething(double amount) {}
In order to BuySomething() with Money, we must explicitly cast it to double first:
Money money(500.0);
BuySomething(static_cast<double>(money));
BuySomething((double)money);
BuySomething(double(money));
BuySomething(double{ money });
// We can also just call the operator directly:
BuySomething(money.operator double());
However, we can BuySomething() with Cash without explicitly casting it first:
Cash cash(500.0);
BuySomething(cash);
// You can still use explicit casting:
BuySomething(static_cast<double>(cash));
BuySomething((double)cash);
BuySomething(double(cash));
BuySomething(double{ cash });
BuySomething(cash.operator double())
This is because when the compiler sees BuySomething(cash);, it knows that BuySomething() doesn't accept Cash - it accepts double - so rather than just throwing an error, it tries to figure out a way to convert Cash to double, and in the process finds our conversion operator.
If you notice something wrong with my explaination, let me know in the comments.
|
72,142,363 | 72,142,548 | How to get characters from a file and display on console? |
I got this code from notes about file handling. From what I understand about this code, I want to get characters till x is reached in the file using this code. Why am I getting only the first character? If this code is incorrect, how should I alter the code to get characters till x is reached? Please help me understand this.<
#include<iostream>
#include<fstream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
char a = '-';
do
{
ifstream obj("test.txt", ifstream::in);// in would mean import from txt to ram
// cout << obj << endl;
if (obj.good() && a != obj.peek())
{
a = obj.getline();
cout << a << endl;
}
obj.close();
} while (a != 'x');
return 0;
}
| a is a character and std::getline() returns an istream. Isn't there something wrong here? You cannot assign an istream to a char, so the code doesn't even compile.
You can simplify your code into this working example:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream obj("test.txt", ifstream::in);
if (obj.good())
{
std::string line;
while (std::getline(obj, line))
{
for (auto& i : line)
{
if (i == 'x') return 0;
cout << i << endl;
}
}
}
obj.close();
return 0;
}
test.txt:
This is
a
test fixle
Output:
T
h
i
s
i
s
a
t
e
s
t
f
i
|
72,142,518 | 72,144,807 | What will be the time complexity of this brute force apporach of finding largest valid bst in a binary tree? |
int size(Node* root){
if (root == nullptr) {
return 0;
}
return size(root->left) + 1 + size(root->right);
}
bool isBST(Node* node, int min, int max)
{
if (node == nullptr) {
return true;
}
if (node->data < min || node->data > max) {
return false;
}
return isBST(node->left, min, node->data) &&
isBST(node->right, node->data, max);
}
int findLargestBST(Node* root)
{
if (isBST(root, INT_MIN, INT_MAX)) {
return size(root);
}
return max(findLargestBST(root->left), findLargestBST(root->right));
}
This is a code to find largest bst in a binary tree.
So according to this post the worst case time complexity of brute force solution is O(n^2) but how? It should be O(n^3) no ? since we are passing size function also
| The size function is only ever used once and is O(n). So the complexity is O(n^2 + n) == O(n^2).
Update: Let me rephrase this as my reasoning wasn't clear at all.
The size function gets called many times. Either because a tree is BST or somewhere down there for each subtree when findLargestBST is called with each subtree. The size function also gets called recursively by size itself.
But for each node size is called at most once. So accumulated it is O(n). To see this you have to look at the two cases in findLargestBST.
If the tree is BST then size gets called for the whole tree and internally recurses to each element of the tree.
If the tree is not BST then the tree is split and size can be called for each subtree. But at most that looks at each element in the left tree and each element in the right tree. The two (or more) calls to size can never overlap and look at an element more than once.
Accumulated that is O(n).
|
72,142,979 | 72,143,479 | Returning a struct pointer from class method | EDIT: Changed example code to code from my project that doesn't work.
I'm writing code in C++, learning templates and got stuck with some problem.
There's a class:
template<class T, class Cmp>
class AVLtree {
public:
AVLtree(const Cmp& _cmp) : root(nullptr), cmp(_cmp) {}
AVLtree(const AVLtree& ref);
~AVLtree();
AVLtree& operator = (const AVLtree& ref);
void Add(const T& key);
void TraverseDfs(void (*visit)(const T& key));
private:
struct Node {
Node* left;
Node* right;
T key;
int balance;
unsigned int height;
unsigned int inheritence;
Node(const T& _key) : left(nullptr), right(nullptr), key(_key), balance(0), height(1), inheritence(1) {}
};
Node* root;
Cmp cmp;
void deleteTree(Node* root);
void traverse(Node* node, void(*visit) (const T& key));
Node* addNode(Node* node, const T& key);
Node* removeNode(Node* p, T key);
int bfactor(Node* node);
unsigned int height(Node* node);
void fixheight(Node* node);
Node* rotateRight(Node* p);
Node* rotateLeft(Node* q);
Node* balance(Node* p);
Node* findmin(Node* p);
Node* removemin(Node* p);
};
I want to define method addNode(Node* node, const T& key) out of class and here's what I write:
template<class T, class Cmp>
AVLtree<T, Cmp>::Node* AVLtree<T, Cmp>::addNode(Node* node, const T& key) {
return new Node(key);
if (!node) {
return new Node(key);
}
if (cmp(key, node->key)) {
node->left = addNode(node->left, key);
}
else {
node->right = addNode(node->right, key);
}
}
Then I try to run program and get such errors and warnings:
warning C4346: 'Node': dependent name is not a type
message : prefix with 'typename' to indicate a type
error C2061: syntax error: identifier 'Node'
error C2143: syntax error: missing ';' before '{'
error C2447: '{': missing function header (old-style formal list?)
It seems that I'm doing something wrong because, if I define method addNode(Node* node, const T& key) inside class, it works fine:
template<class T, class Cmp>
class AVLtree {
public:
...
private:
...
Node* addNode(Node* node, const T& key) {
return new Node(key);
if (!node) {
return new Node(key);
}
if (cmp(key, node->key)) {
node->left = addNode(node->left, key);
}
else {
node->right = addNode(node->right, key);
}
}
};
Any guesses what might be wrong?
| Thanks for answers. Got a solution:
Just added typename before method definition outside of class. It looks like this:
template<class T, class Cmp>
typename AVLtree<T, Cmp>::Node* AVLtree<T, Cmp>::addNode(Node* node, const T& key) {
...
}
It seems that this is some spicialization of Visual Studio because I can see that other compilers work fine with such code without any errors.
|
72,143,184 | 72,143,362 | Are there any good mappings between GCC and MSVC warnings? E.g. -Wredundant-move on MSVC | This question is somewhat two fold, one being more general than the other. The specific question is; does MSVC have equivalent warnings to -Wredundant-move? More generally, is there anywhere online, even if it's someone's blog, that has a reasonable mapping between GCC and MSVC warnings?
I'm aware that warnings don't have any requirement to be similar accross platforms, or even exist at all - that's why I'm interested to find out if there is any reasonable correlation?
For a small bit of background, I'm looking to enable specific -Werrors on a cross-platform project, and would prefer if each platform looked after roughly the same warnings instead of relying on the user to check on both platforms manually.
|
The specific question is; does MSVC have equivalent warnings to -Wredundant-move?
From what I've found, no, MSVC doesn't.
The subset of the warning messages that are generated by the Microsoft C/C++ compiler (Compiler warnings C4000 - C5999) does not have any similar warning.
The Compiler Warnings by compiler version page does not show one either.
Compiler warnings that are off by default is void of such warnings.
This implicitly answers the more general question if there's a good mapping between gcc and MSVC warnings.
But - the future looks promising for the particular kind of warning you asked about:
Under Review - Pessimizing Move Compiler Warning:
"LLVM supports a pessimizing-move compiler warning. In C++17 and newer, this fires when invoking std::move() on a temporary, this results in copy elision not occurring on the temporary. This seems a high value warning that is supported in Clang++ and GCC, but not MSVC."
|
72,143,535 | 72,143,648 | It is legal this approach for create a local variable in C++ | I'm new to C++ and try to understand how to create and use a class in C++.
For this I have the following code:
class MyClass
{
public:
MyClass()
{
_num = 0;
_name = "";
}
MyClass(MyClass* pMyClass)
{
_num = pMyClass->_num;
_name = pMyClass->_name;
}
void PrintValues() { std::cout << _name << ":" << _num << std::endl; }
void SetValues(int number, std::string name)
{
_num = number;
_name = name;
}
private:
int _num;
std::string _name;
};
int main()
{
std::vector<MyClass*> myClassArray;
MyClass myLocalObject = new MyClass();
for (int i = 0; i < 3; i++)
{
myLocalObject.SetValues(i, "test");
myClassArray.push_back(new MyClass(myLocalObject));
}
myClassArray[1]->PrintValues();
// use myClassArray further
}
I get a similar example from the internet and try to understand it.
My intentions is to populate myClassArray with new class objects.
If I compile the code above using VisualStudio 2022 I get no errors, but I'm not sure it doesn't produce memory leaks or if there is a faster and simple approach.
Especially I do not understand the following line:
MyClass myLocalObject = new MyClass();
myLocalObject is created on the stack but is initialized with a heap value (because of the new). If new operator is used where should delete must apply?
Thank you for any suggestions!
| You have a memory leak at MyClass myLocalObject = new MyClass();, since the dynamically-allocated object is used to converting-construct the new myLocalObject (this was almost but not quite a copy constructor) and then the pointer is lost.
You also didn't show the code using the vector, but if it doesn't delete the pointers inside, you will have more memory leaks.
There's no reason to have an almost-copy-constructor; the compiler has provided you with a better real copy-constructor.
The faster and simpler approach is to recognize that this code doesn't need pointers at all.
class MyClass
{
public:
MyClass()
: _num(), _name() // initialize is better than assignment
{
//_num = 0;
//_name = "";
}
// compiler provides a copy constructor taking const MyClass&
//MyClass(MyClass* pMyClass)
//{
// _num = pMyClass->_num;
// _name = pMyClass->_name;
//}
void PrintValues() { std::cout << _name << ":" << _num << std::endl; }
void SetValues(int number, std::string name)
{
_num = number;
_name = name;
}
private:
int _num;
std::string _name;
};
int main()
{
std::vector<MyClass> myClassArray; // not a pointer
MyClass myLocalObject; // = new MyClass(); // why copy a default instance when you can just default initialize?
for (int i = 0; i < 3; i++)
{
myLocalObject.SetValues(i, "test"); // works just as before
myClassArray.push_back(/*new MyClass*/(myLocalObject)); // don't need a pointer, vector knows how to copy objects
// also, this was using the "real" copy-constructor, not the conversion from pointer
}
myClassArray[1].PrintValues(); // instead of ->
// use myClassArray further
}
for cases where a pointer is necessary, for example polymorphism, use a smart pointer:
std::vector<std::unique_ptr<MyClass>> myClassArray; // smart pointer
myClassArray.push_back(make_unique<MyDerivedClass>(stuff));
std::unique_ptr will automatically free the object when it is removed from the vector (unless you explicitly move it out), avoiding the need to remember to delete.
|
72,143,753 | 72,143,862 | Is it possible to calculate the value after overflow? | I understand that if 1 is added to INT_MAX it will overflow and we will get the negative maximum. It is connected in a cycle. In the code below can I calculate the value after overflow.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a = 100000;
int b = 100000;
int c = a*b;
cout<<c;
return 0;
}
Output:
1410065408
Is it possible to calculate this number.
How is multiplication happening internally in this case
|
I understand that if 1 is added to INT_MAX it will overflow and we will get the negative maximum.
You've misuderstood. If 1 is added to INT_MAX, then the behaviour of the program is undefined.
can I calculate the value after overflow.
After signed integer overflow, the behaviour of the program is undefined, so doing anything is pointless.
If you were to use unsigned integers, then the result of any operation will be congruent with the "mathematically correct" result modulo M where M is the number of representable values i.e. max+1.
For example if unsigned is 32 bits, 100'000u * 100'000u would be 10'000'000'000 which is congruent with 1'410'065'408 modulo M=4'294'967'295. You can find the representable congruent value by repeatedly subtracting or adding M until the result is representable.
Another example of modular arithmetic that you may be familiar with is the clock. If you add 123 hours to a 24 hour clock starting from midnight, then what time will it show? If you add 10'000'000'000 hours to a 4'294'967'295 hour clock, what time will it show?
|
72,143,926 | 72,144,069 | std::stringstream's seekg does not work after while loop | I have this std::stringstream object whose contents I have to read (only) twice. For this I thought I could use its seekg member function to repeat the reading. But I can't make it work. Here's a MWE that reproduces the issues I'm having (adapted from the example in the docs).
#include <iostream>
#include <string>
#include <sstream>
int main()
{
const char *str = "Hello, world";
std::stringstream ss(str);
std::string word1 = "asdf";
std::string word2 = "qwer";
std::string word3 = "zxcv";
std::string word4 = "yuio";
ss >> word1;
ss.seekg(0); // rewind
ss >> word2;
while (ss >> word3) { }
ss.seekg(0); // rewind
ss >> word4;
std::cout << "word1 = " << word1 << '\n'
<< "word2 = " << word2 << '\n'
<< "word3 = " << word3 << '\n'
<< "word4 = " << word4 << '\n';
}
I expect the contents to be:
word1 = Hello,
word2 = Hello,
word3 = world
word4 = Hello,
since the call ss.seekg(0) after the while loop should put ss at the beginning of its contents. Why do I not get the expected output, but rather this?
word1 = Hello,
word2 = Hello,
word3 = world
word4 = yuio
This means that word4 is never updated, thus the statement ss >> word4 has no effect. But in this case, then the ss.seekg(0) does not have any effect either.
Is the while loop causing the ss object to fail to "rewind"? Perhaps the ss tried to read too much and now is in an error state (I have no idea).
How can I fix this? That is, how can I make the statement ss >> word4 read Hello,?
I'm using g++ (Ubuntu 11.1.0-1ubuntu1~20.04) 11.1.0 on C++17.
| seekg first constructs and checks the sentry object (used by cppstreams to represent any stream failure), if that sentry object represents any failure then the function just returns without doing anything.
After the while loop, ss's failbit and eofbit will be set. The call to seekg will behave as described before (won't do anything).
For seekg to take any affect, you will have to clear the failure bits by calling ss.clear()before calling seekg itself after the while loop. Then, the sentry object won't represent any failure and seekg will behave as expected.
Relevant links:
https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2
https://en.cppreference.com/w/cpp/io/basic_istream/seekg
|
72,144,090 | 72,144,215 | Receiving error: "error: static assertion failed: result type must be constructible from value type of input range" when constructing class vectors | I am trying to create a script that uses polymorphism to create a set of linking vectors within parent/child class structure. So far I have got the classes setup, but when trying to test the code I receive an error involving static assertion. When analysing the code line by line, I run into the error when I call 'vector.begin() & vector.end()'.
Here is the full script:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
vector<vector<A *>> Container;
};
class B : A
{
};
class C : A
{
};
class D : A
{
};
int main()
{
A ABaseClass;
B b1, b2;
C c1, c2;
D d1, d2;
vector<B *> b_classes = {&b1, &b2};
vector<C *> c_classes = {&c1, &c2};
vector<D *> d_classes = {&d1, &d2};
ABaseClass.Container = {
{b_classes.begin(), b_classes.end()},
{c_classes.begin(), c_classes.end()},
{d_classes.begin(), d_classes.end()}};
}
Compiling gives this error:
error: static assertion failed: result type must be constructible from value type of input range
138 | static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
| ^~~~~
error: static assertion failed: result type must be constructible from value type of input range
note: 'std::integral_constant<bool, false>::value' evaluates to false
I have narrowed down the cause of the error to this section:
ABaseClass.Container = {
{b_classes.begin(), b_classes.end()},
{c_classes.begin(), c_classes.end()},
{d_classes.begin(), d_classes.end()}};
Following the root of the problem leads me to the file 'stl_uninitialized.h', and the line:
[138] static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
^~~~~
I have been trying to get the child classes to be tracked by the parents but I am unfamiliar with vectors and pointers so I am a bit stuck. Any help with moving forward would be greatly appreciated.
| Upcast to a base class is ill-formed if the inheritance is not public. i.e
struct base {};
class derived : base {}; // private inheritance
int main(){
derived a;
auto & b = static_cast<base &>(a); // invalid
}
That's exactly what that last assignment expression is trying to do. You will need to inherit publically. i.e
class A
public:
vector<vector<A *>> Container;
};
class B : public A
{
};
class C : public A
{
};
class D : public A
{
};
EDIT:
This is the answer originally cited:
class A
public:
vector<vector<A *>> Container;
};
struct B : A
{
};
struct C : A
{
};
struct D : A
{
};
|
72,144,214 | 72,145,624 | How to constrain class template by disabling type argument of specialization itself, and why does(n't) it work? | Is it currently possible to constrain a class template that rejects type argument which is the specialization of the class template itself without using static_assert?
Since I cannot use requires expression to check if it is a valid typename, I have to create a class template instantiation validator that checks whether the class template passed is valid with template arguments:
template <template <typename...> typename Temp, typename... Ts>
requires requires { typename Temp<Ts...>; }
constexpr bool is_valid() { return true; }
template <template <typename...> typename, typename...>
constexpr bool is_valid() { return false; }
template <template <typename...> typename Temp, typename... Ts>
concept valid_instantiation = is_valid<Temp, Ts...>();
Since failed static_assert emits a hard error, just like this one:
template <typename>
class Hello;
template <typename>
inline constexpr bool is_hello_v = false;
template <typename T>
inline constexpr bool is_hello_v<Hello<T>> = true;
template <typename T>
class Hello {
static_assert(!is_hello_v<T>);
};
static_assert(valid_instantiation<Hello, int>);
static_assert(!valid_instantiation<Hello, Hello<int>>);
The second static assertion sure didn't compile unless I remove that ! that returns true which is not what I expected.
What I want to have is to silent the error and replace the static_assert, so that:
static_assert(valid_instantiation<Hello, int>);
static_assert(!valid_instantiation<Hello, Hello<int>>);
can be valid.
For the first static assertion, the Hello<int> instantiation is accepted just fine, while the second static assertion, Hello<Hello<int>> instantiation should be rejected because the template argument passed is the instantiation of the class template itself but I have no knowledge what constraints I'll be using to achieve these.
It's ok if it is impossible to do so, or otherwise.
| Not sure it is what you want, but
template <typename T> struct is_Hello;
template <typename T> requires (!is_Hello<T>::value) class Hello;
template <typename T> struct is_Hello : std::false_type{};
template <typename T> struct is_Hello<Hello<T>> : std::true_type{};
template <typename T>
requires (!is_Hello<T>::value) // So Hello<Hello<T>> is not possible
class Hello
{
// ...
};
Not sure how you want to SFINAE or test it (the trait seems equivalent), as Hello<Hello<T>> cannot exist.
Demo
|
72,144,761 | 72,145,006 | Why hasn't not_null made it into the C++ standard yet? | After adding the comment "// not null" to a raw pointer for the Nth time I wondered once again whatever happened to the not_null template.
The C++ core guidelines were created quite some time ago now and a few things have made into into the standard including for example std::span (some like string_view and std::array originated before the core guidelines themselves but are sometimes conflated). Given its relative simplicity why hasn't not_null (or anything similar) made it into the standard yet?
I scan the ISO mailings regularly (but perhaps not thoroughly) and I am not even aware of a proposal for it.
Possibly answering my own question. I do not recall coming across any cases where it would have prevented a bug in code I've worked on as we try not to write code that way.
The guidelines themselves are quite popular, making it into clang-tidy and sonar for example. The support libraries seem a little less popular.
For example boost has been available as a package on Linux from near the start. I am not aware of any implementation of GSL that is. Though, I presume it is bundled with Visual C++ on windows.
Since people have asked in the comments.
Myself I would use it to document intent.
A construct like not_null<> potentially has semantic value which a comment does not.
Enforcing it is secondary though I can see its place. This would preferably be done with zero overhead (perhaps at compile time only for a limited number of cases).
I was thinking mainly about the case of a raw pointer member variable. I had forgotten about the case of passing a pointer to a function for which I always use a reference to mean not-null and also to mean "I am not taking ownership".
Likewise (for class members) we could also document ownership owned<> not_owned<>.
I suppose there is also whether the associated object is allowed to be changed. This might be too high level though. You could use references members instead of pointers to document this. I avoid reference members myself because I almost always want copyable and assignable types. However, see for example Should I prefer pointers or references in member data? for some discussion of this.
Another dimension is whether another entity can modify a variable.
"const" says I promise not to modify it. In multi-threaded code we would like to say almost the opposite. That is "other code promises not to modify it while we are using it" (without an explicit lock) but this is way off topic...
| There is one big technical issue that is likely unsolvable which makes standardizing not_null a problem: it cannot work with move-only smart pointers.
The most important use case for not_null is with smart pointers (for raw pointers a reference usually is adequate, but even then, there are times when a reference won't work). not_null<shared_ptr<T>> is a useful thing that says something important about the API that consumes such an object.
But not_null<unique_ptr<T>> doesn't work. It cannot work. The reason being that moving from a unique pointer leaves the old object null. Which is exactly what not_null is expected to prevent. Therefore, not_null<T> always forces a copy on its contained T. Which... you can't do with a unique_ptr, because that's the whole point of the type.
Being able to say that the unqiue_ptr consumed by an API is not null is good and useful. But you can't actually do that with not_null, which puts a hole in its utility.
So long as move-only smart pointers can't work with not_null, standardizing the class becomes problematic.
|
72,144,944 | 72,145,346 | Mask from bitfield in C++ | Here's a little puzzle I couldn't find a good answer for:
Given a struct with bitfields, such as
struct A {
unsigned foo:13;
unsigned bar:19;
};
Is there a (portable) way in C++ to get the correct mask for one of the bitfields, preferably as a compile-time constant function or template?
Something like this:
constinit unsigned mask = getmask<A::bar>(); // mask should be 0xFFFFE000
In theory, at runtime, I could crudely do:
unsigned getmask_bar() {
union AA {
unsigned mask;
A fields;
} aa{};
aa.fields.bar -= 1;
return aa.mask;
}
That could even be wrapped in a macro (yuck!) to make it "generic".
But I guess you can readily see the various deficiencies of this method.
Is there a nicer, generic C++ way of doing it? Or even a not-so-nice way? Is there something useful coming up for the next C++ standard(s)? Reflection?
Edit: Let me add that I am trying to find a way of making bitfield manipulation more flexible, so that it is up to the programmer to modify multiple fields at the same time using masking. I am after terse notation, so that things can be expressed concisely without lots of boilerplate. Think working with hardware registers in I/O drivers as a use case.
| Unfortunately, there is no better way - in fact, there is no way to extract individual adjacent bit fields from a struct by inspecting its memory directly in C++.
From Cppreference:
The following properties of bit-fields are implementation-defined:
The value that results from assigning or initializing a signed bit-field with a value out of range, or from incrementing a signed
bit-field past its range.
Everything about the actual allocation details of bit-fields within the class object
For example, on some platforms, bit-fields don't straddle bytes, on others they do
Also, on some platforms, bit-fields are packed left-to-right, on others right-to-left
Your compiler might give you stronger guarantees; however, if you do rely on the behavior of a specific compiler, you can't expect your code to work with a different compiler/architecture pair. GCC doesn't even document their bit field packing, as far as I can tell, and it differs from one architecture to the next. So your code might work on a specific version of GCC on x86-64 but break on literally everything else, including other versions of the same compiler.
If you really want to be able to extract bitfields from a random structure in a generic way, your best bet is to pass a function pointer around (instead of a mask); that way, the function can access the field in a safe way and return the value to its caller (or set a value instead).
Something like this:
template<typename T>
auto extractThatBitField(const void *ptr) {
return static_cast<const T *>(ptr)->m_thatBitField;
}
auto *extractor1 = &extractThatBitField<Type1>;
auto *extractor2 = &extractThatBitField<Type2>;
/* ... */
Now, if you have a pair of {pointer, extractor}, you can get the value of the bitfield safely. (Of course, the extractor function has to match the type of the object behind that pointer.) It's not much overhead compared to having a {pointer, mask} pair instead; the function pointer is maybe 4 bytes larger than the mask on a 64-bit machine (if at all). The extractor function itself will just be a memory load, some bit twiddling, and a return instruction. It'll still be super fast.
This is portable and supported by the C++ standard, unlike inspecting the bits of a bitfield directly.
Alternatively, C++ allows casting between standard-layout structs that have common initial members. (Though keep in mind that this falls apart as soon as inheritance or private/protected members get involved! The first solution, above, works for all those cases as well.)
struct Common {
int m_a : 13;
int m_b : 19;
int : 0; //Needed to ensure the bit fields end on a byte boundary
};
struct Type1 {
int m_a : 13;
int m_b : 19;
int : 0;
Whatever m_whatever;
};
struct Type2 {
int m_a : 13;
int m_b : 19;
int : 0;
Something m_something;
};
int getFieldA(const void *ptr) {
//We still can't do type punning directly due
//to weirdness in various compilers' aliasing resolution.
//std::memcpy is the official way to do type punning.
//This won't compile to an actual memcpy call.
Common tmp;
std::memcpy(&tmp, ptr, sizeof(Common));
return tmp.m_a;
}
See also: Can memcpy be used for type punning?
|
72,145,179 | 72,145,260 | Recomended formating for temporarily inverting data at pointer and then passing pointer to temporarily inverted data | Long story short, I have a pointer to a value that is stored inverted, so when we are calculating a hash to verify data integrety, we need to invert the data that is used in the hash. The hash function, however, takes a pointer as input. So what we need to do is take our pointer, dereference it to get to the data, temporarily invert the data, and the pass a reference to the inverted data.
I've written up some pseudocode for how I had originally done it.
uint32_t hash = 0;
MemoryBlock pMemoryBlock = pAllocator->GetFirstMemoryBlock();
while(nullptr != pMemoryBlock)
{
uint32_t size = pMemoryBlock->getWordsUsed();
const uint32_t* pStartAddress = pMemoryBlock->GetStartAddress();
for (uint32_t i = 0; i < size; i++)
{
if (isDiagnostics)
{
uint32_t inverted_data = ~(pStartAddress[i]);
hash = Algorithim::Calculate(&inverted_data, hash);
}
else
{
hash = Algorithim::Calculate(&pStartAddress[i], hash);
}
}
pMemoryBlock->GetNextMemoryBlock();
}
return hash;
But a colleague on my code review wants me to avoid the temp variable and change it to.
uint32_t hash = 0;
MemoryBlock pMemoryBlock = pAllocator->GetFirstMemoryBlock();
while(nullptr != pMemoryBlock)
{
uint32_t size = pMemoryBlock->getWordsUsed();
const uint32_t* pStartAddress = pMemoryBlock->GetStartAddress();
for (uint32_t i = 0; i < size; i++)
{
if (isDiagnostics)
{
hash = Algorithim::Calculate(&~pStartAddress[i], hash);
}
else
{
hash = Algorithim::Calculate(&pStartAddress[i], hash);
}
}
pMemoryBlock->GetNextMemoryBlock();
}
return hash;
I was wondering if there was any real reason to avoid using the temp variable. If it even works to dereference a pointer, do an operator on the data, and then pass a reference to it without assigning the value to anything (cause i'm fairly certain it doesn't). And if there are any better ways to do this than the first example.
| You need the temp variable. This expression:
hash = Algorithim::Calculate(&~pStartAddress[i], hash);
Is invalid because the result of the ~ operator is not an lvalue, and the & operator requires an lvalue.
On a side note, you can reduce repetition in your code by using the temp value in both cases:
uint32_t data = isDiagnostics ? ~pStartAddress[i] : pStartAddress[i];
hash = Algorithim::Calculate(&data, hash);
|
72,145,613 | 72,145,836 | malloc(): corrupted top size Process finished with exit code 134 (interrupted by signal 6: SIGABRT) | please tell me why memory is not allocated in the line CLNAME* tmp=new CLNAME[this->Capacity_Ram]; the second day I'm looking for a problem, I can not understand what the problem is. The task is to write self-written vectors
Code:
header:
#pragma once
#include <iostream>
#include <memory.h>
using namespace std;
template <class CLNAME>
class MyVector{
protected:
CLNAME* Array;
int Size_Ram = 0;
int Capacity_Ram = 5;
public:
MyVector();
MyVector(const MyVector<CLNAME> &other);
int Capacity();
int Size();
void PushBack(CLNAME item);
};
#include "MyVector.ipp"
ipp:
//Конструкторы
template <class CLNAME>
MyVector<CLNAME>::MyVector() {
this->Array = new CLNAME[this->Capacity_Ram];
}
template <class CLNAME>
MyVector<CLNAME>::MyVector(const MyVector<CLNAME> &other) {
this->Capacity_Ram=other.Capacity_Ram;
this->Size_Ram=other.Size_Ram;
Array = new CLNAME[other.Capacity_Ram];
for (int i=0;i<other.Size_Ram;i++){
this->Array[i]=other.Array[i];
}
}
//Методы
template <class CLNAME>
int MyVector<CLNAME>::Capacity(){
return(this->Capacity_Ram);
};
template <class CLNAME>
int MyVector<CLNAME>::Size(){
return(this->Size_Ram);
};
template <class CLNAME>
void MyVector<CLNAME>::PushBack(CLNAME item) {
if (this->Size_Ram==0){
Array = new CLNAME[this->Capacity_Ram];
this->Capacity_Ram=Capacity_Ram*2;
}
if(Size_Ram==Capacity_Ram){
this->Capacity_Ram=Capacity_Ram*2;
CLNAME* tmp=new CLNAME[this->Capacity_Ram];
for (int i=0;i<Size_Ram;i++){
tmp[i]=Array[i];
}
delete [] Array;
Array = tmp;
}
Array[Size_Ram]=item;
Size_Ram+=1;
}
//template <class CLNAME>
//MyVector<CLNAME> MyVector<CLNAME>::operator=(MyVector<CLNAME> other) {
//if (*this == other){
//return *this
//}
//this->Size_Ram=other.Size;
//this->Capacity_Ram=other.Capacity;
//this->Array=other.Array;
//};
main:
#include <iostream>
#include "MyVector.h"
int main() {
MyVector<int> vectors;
int a=65;
cout<<vectors.Capacity()<<endl;
cout<<vectors.Size()<<endl;
for (int i=0;i<=10;i++) {
vectors.PushBack(i);
}
cout<<vectors.Size()<<endl;
cout<<vectors.Capacity()<<endl;
}
| In MyVector<CLNAME>::PushBack
if (this->Size_Ram==0){
Array = new CLNAME[this->Capacity_Ram]; // already done in constructor, leaks.
// sets capacity of 5
this->Capacity_Ram=Capacity_Ram*2; // advertises a capacity of 10, not 5.
}
makes 2 mistakes. 1) storage was already allocated in the constructor so this leaks the constructor's allocation and is unnecessary. 2) Array = new CLNAME[this->Capacity_Ram]; asks for an array of Capacity_Ram elements and then resets the capacity to Capacity_Ram=Capacity_Ram*2; ruining the if(Size_Ram==Capacity_Ram) capacity tests later in the program and allowing out-of-bounds accesses.
Solution: Remove the entire first if and block. The constructor did this already.
Side note: This class needs an assignment operator and a destructor to go along with the copy constructor.
|
72,146,555 | 72,146,594 | Is there an alternative to the builder pattern that is preferred in C++? | I'm coming from Java where the builder pattern is used heavily, e.g.
Foo foo = new FooBuilder()
.setBar(43)
.setBaz("hello, world!")
.enableCache(true)
.build();
Automapper for example is popular library that generates this pattern via Java annotations.
I don't see any such library for C++—only gists and blog posts online with example ad hoc implementations.
Does the lack of a library imply that the builder pattern is not preferred in C++? What is the alternative or preferred idiom then?
Maybe it helps to describe what I actually want. I like the grammar that the builder pattern affords me, for example if there are 20 fields I could set (e.g. a large configuration), but may only set 4 or may set all 20, without having to create explicit constructors for each case.
| A common pattern is aggregate initialisation:
Foo foo = {
.bar=43,
.baz="hello, world!",
.enableCache=true,
};
Note that designated initialisers such as used here were introduced in C++20. Prior to that, you could only initialise sub objects positionally.
Another pattern, common in absence of designated initialisers, is value initialisation followed by assignment of data members:
Foo foo = {};
foo.bar = 43;
foo.baz = "hello, world!";
foo.enableCache = true;
Usage of neither pattern requires the use of a library.
|
72,146,745 | 72,151,959 | Repeat a cubemap texture on a cube face with OpenGL | Is it possible to make a cube map texture (GL_TEXTURE_CUBE_MAP_POSITIVE_X...) repeat on a given face with OpenGL?
I have a simple unit cube with 24 vertexes centered around the origin (xyz between (-0.5, -0.5, -0.5) and (0.5, 0.5, 0.5)). Among its attributes, initially I set the uvw coords to the xyz position in the fragment shader as was done in the cubemap learnopengl.com tutorial. I obviously tried also to have separate uvw coordinates set to values equal to the scale, but the texture wasnt't repeating on any cube face as can be seen from the one displayed below (I painted the uvw coordinates in the fragment shader) :
height (y-coord of top pixels) = 3.5 in the image above, so by setting v = 3.5 for the vertex at the top, I'd expect the gradient to repeat vertically (which is not the case).
If it's not possible, the only way left for me to fix it is to assign a 2D Texture with custom uv coordinates on each vertex, right?
| No, it's not possible to have wrapping with GL_REPEAT for cubemaps. You should probably look to the alternatives people have suggested in the comments.
The reason for this, is that the coordinates that you pass to the cubemap sampler are interpreted as a direction. The length of this direction is ignored. You can think of it as if the vec3 used for sampling gets normalized — therefore, wrapping won't ever happen.
If, for any reason, you need to use a cubemap, you could make a modification to the sample direction in the shader.
vec3 tweakSampleDirForReapeat(vec3 dir, float repeatScale)
{
for(int i = 0; i < 3; i++) {
float d = abs(dir[i]);
if(abs(d) >= 0.5) // skip dominant direction (assuming a coordinate in a unit cube centered at the origin)
continue;
d += 0.5; // transform from [-0.5, +0.5] range to [0, 1]
d *= repeatScale; // transform from [0, 1] range to [0, repeatScale]
d = fract(d); // wrap [0, repeatScale] to multiple [0, 1] ranges
d -= 0.5; // transform from [0, 1] range to [-0.5, +0.5]
dir[i] = d;
}
return dir;
}
Disclaimer: this code should work but I haven't actually tried it.
This code could be adapted to support different repearScales per face.
EDIT:
I will try to explain what this code does.
Imagine that we have a point that lays in the +X face of the cube.
We are trying to modify the location of this blue dot. We don't know yet where to place this point exactly. But this point will be in the same face.
In this case, the X value is equal to +0.5. The other coordinates (Y and Z) will have values smaller than 0.5 in absolute value.
That's what we are checking in this if:
if(abs(d) >= 0.5) // skip dominant direction
continue;
So basically, if X is -0.5 or +0.5, we don't want to change X, in order to keep it on the same face.
We will only modify Y and Z.
Now lets see the cube from a different perspective. Now we see the +X face facing towards us.
With this perspective we can clearly see that Y and Z are both < 0.5 (in absolute value), as the point is inside the box.
Now let's bring in a texture.
By default we would get whole the texture splatted onto the face.
But we would like something like this.
That's what this transformation is trying to do:
d += 0.5; // transform from [-0.5, +0.5] range to [0, 1]
d *= repeatScale; // transform from [0, 1] range to [0, repeatScale]
d = fract(d); // wrap [0, repeatScale] to multiple [0, 1] ranges
d -= 0.5; // transform from [0, 1] range to [-0.5, +0.5]
I recommend you go through the algorithm with a few examples, using paper and pencil. I'm sure you will end up understanding it, it's just a matter of putting in some time. Good luck!
Quiz question: what would be "repeatScale" for the previous image?
|
72,146,860 | 72,146,922 | Different C++ fork() behavior between CentOS 7.5 & RockyLinux 8.4, Ubunu 20.04 | I'm working with some legacy code. It works fine on a CentOS 7 system. The args array gets hosed on both a Rocky 8.4 and Ubuntu 20.04 system. I've simplified the problem and added print statements. The execv() was launching another program. The args going into the execv get messed up. Without the fork, the code works as expected. Baffled.
I have two simple test programs, one of which does nothing.
test9.cpp
int main(){}
and test10.cpp
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
int main()
{
std::vector<std::string> stringArgs;
std::string a{"./test9.x"};
std::string b{"test10.cpp"};
stringArgs.push_back(a);
stringArgs.push_back(b);
char* args[stringArgs.size()+1];
if(fork() == 0){
for(uint8_t i = 0; i < stringArgs.size(); i++) {
std::string tmp(stringArgs[i]);
args[i] = const_cast<char*>(tmp.c_str());
std::cout << "\n\t"<<args[i]<<"'\n\n";
}
std::cout << "\n\t"<<args[0]<<"'\n\n";
std::cout << "\n\t"<<args[1]<<"'\n\n";
// last argument has to be NULL
args[stringArgs.size()] = NULL;
execv(args[0],&args[0]);
std::cout << "\n\tERROR: Could not run '"<<args[0]<<"'\n\n";
}
else
std::cout<<"parent\n";
}
g++ -o test9.x test9.cpp; g++ -o test10.x test10.cpp
On the CentOS 7 I get:
$ ./test10.x
./test9.x
test10.cpp
./test9.x
test10.cpp
parent
And on both Rocky Linux 8.4 and Ubuntu 20.04 I get this. Notice the test9.x gets replaced by test10.cpp after the for loop.
./test10.x
parent
./test9.x
test10.cpp
test10.cpp
test10.cpp
ERROR: Could not run test10.cpp
| THis loop
for(uint8_t i = 0; i < stringArgs.size(); i++) {
std::string tmp(stringArgs[i]);
args[i] = const_cast<char*>(tmp.c_str());
std::cout << "\n\t"<<args[i]<<"'\n\n";
}
is creating an array of pointers to a temporary on the stack, or some internal implementation defined part of std::string
do this instead
for(uint8_t i = 0; i < stringArgs.size(); i++) {
args[i] = strdup(stringArgs[i]);
std::cout << "\n\t"<<args[i]<<"'\n\n";
}
|
72,147,214 | 72,147,349 | How can I repair this error that occurs occasionally when my code is running? | Sometimes the code runs till the end without any errors while other times it stops in the middle and gives me this error Thread 1: EXC_BAD_ACCESS (code=EXC_I386_GPFLT) here is a picture of it (https://i.stack.imgur.com/uZDX1.png). The error is in my header file named Functions, and the compiler used in this picture is Xcode on a Mac device. I also tried another compiler "Visual Studio" on a Windows device and the code never runs till the end, it always stops in the middle of running and gives me an error in the same line of code, here is a picture of the error Visual Studio gave me Error in Visual Studio.
#include <iostream>
using namespace std;
//products' data
struct products{
int ID;
string Name;
double Price;
int Quantity;
};
//receipt
struct receipt{
string name;
double price;
receipt* link;
};
struct linkedListFunctions{
//inserts node at the end of the list
void insert(receipt** head_name_ref, string new_name, double new_price)
{
receipt* new_name_node = new receipt();
receipt *last = *head_name_ref;
new_name_node->name = new_name;
new_name_node->price = new_price;
new_name_node->link = NULL;
if (*head_name_ref == NULL)
{
*head_name_ref = new_name_node;
return;
}
while (last->link != NULL)//The error is right here
{
last = last->link;
}
last->link = new_name_node;
return;
}
//prints list
void printReceipt(receipt* n){
while(n!=NULL){
cout<<n->name<<": ";
cout<<n->price<<'\t'<<" ";
cout<<endl;
n=n->link;
}
}
//removes first node in the list
receipt* removeFirstreceipt(struct receipt* head)
{
if (head == NULL)
return NULL;
receipt* temp = head;
head = head->link;
delete temp;
return head;
}
};
The first two code boxes are in the header file named Functions.h
The error is in the second code box at line 15, it has a comment next to it
#include "Functions.h"
int main(){
struct products details[5];
details[0] = {0, "Apple Juice", 12, 240};
details[1] = {1,"Bread", 10, 100};
details[2] = {2, "Chocolate", 5, 500};
details[3] = {3, "Dates", 50, 150};
details[4] = {4, "Eggs", 30, 360};
linkedListFunctions list;
//declaring first node in receipt linked list
receipt* head = NULL;
head = new receipt;
//prints all products IDs and Names
for (int i=0; i<5; i++) {
cout<<details[i].ID<<": ";
cout<<details[i].Name<<" ";
cout<<details[i].Price<<"LE"<<endl;
}
char buyAgain;
while ((buyAgain='y' && buyAgain!='n')){
//choosing a product
cout<<"Enter the product's ID to choose it: ";
int chooseProduct;
cin>>chooseProduct;
cout<<"ID: "<<details[chooseProduct].ID<<endl
<<"Name: "<<details[chooseProduct].Name<<endl
<<"Price: "<<details[chooseProduct].Price<<endl
<<"Quantity: "<<details[chooseProduct].Quantity<<endl<<"********"<<endl;
//choosing the quantity
cout<<"How much "<<details[chooseProduct].Name<<" do you want? ";
int chooseQuantity;
cin>>chooseQuantity;
list.insert(&head, details[chooseProduct].Name, details[chooseProduct].Price*chooseQuantity);//
details[chooseProduct].Quantity=details[chooseProduct].Quantity-chooseQuantity;
cout<<details[chooseProduct].Name<<" Left: "<<details[chooseProduct].Quantity<<endl<<"********"<<endl;
cout<<"Would you like to order something else? y=yes n=no";
cin>> buyAgain;
switch(buyAgain) {
case 'y':
break;
case 'n':
//prints receipt
cout<<"***Receipt***"<<endl;
list.printReceipt(head);
}
}
}
The last code box is the main function
| For starters these lines:
receipt* head = NULL;
head = new receipt;
do not make a great sense. The operator new creates an uninitialized object of the type receipt (for example the data member link can have an indeterminate value) that is a reason of undefined behavior when the pointer used in functions. What you need is just to write:
receipt* head = NULL;
The condition in this while loop:
while ((buyAgain='y' && buyAgain!='n')){
does not make a sense. buyAgain is always set to 'y' in this sub-expression:
buyAgain='y'
It seems you mean:
while ( buyAgain == 'y' ){
or:
while ( buyAgain != 'n' ){
But before the while loop you have to initialize the variable buyAgain
char buyAgain = 'y';
As the structure receipt is an aggregate then instead of these statements within the function insert:
receipt* new_name_node = new receipt();
new_name_node->name = new_name;
new_name_node->price = new_price;
new_name_node->link = NULL;
you could write:
receipt* new_name_node = new receipt
{
new_name, new_price, nullptr
};
Pay attention to that the functions for processing the list declared in the structure struct linkedListFunctions should be at least static member functions.
The parameter of the function printReceipt should have the qualifier const:
void printReceipt( const receipt* n);
and the output of blanks:
cout<<n->price<<'\t'<<" ";
^^^^^^^^^^^^
in fact has no effect due to the next line
cout<<endl;
|
72,147,303 | 72,147,740 | Programs which accept uppercase and lowercase commands as input | I'm trying to add a help/information box in my program that pops whenever someone type in a /h, /?, /help commands. I want to make sure that my program accepts all characters in both upper and lower case. From what I have, I can check the most frequent cases of these commands, but not all (ie. /HeLp). Looking for way to cover all bases. Here's my current code:
....
bool CheckParseArguments(LPWSTR* argv, int argc)
{
for (int i = 0; i <= argc; i++)
{
const wchar_t* help[] = { L"/h", L"/H", L"/?", L"/Help", L"/HELP", L"/help"};
for (int h = 0; h <= 5; h++)
if (argc == (i + 1) && wcscmp(argv[i], help[h]) == 0)
{
MessageBoxW(NULL, L"Correct input is ...", L"Help", MB_OK);
return false;
}
}
.... continue with other checks....
| With the Microsoft compiler (which you seem to be using), you can use the function _wcsicmp instead of wcscmp to perform a case-insensitive compare.
Other platforms have similar functions, such as strcasecmp and wcscasecmp on Linux.
ISO C++ itself does not provide a function which performs a case-insensitive compare. However, it is possible to convert the entire string to lowercase using the function std::tolower or std::towlower, before performing the compare. Afterwards, you won't need a case-insensitive compare, but can perform a standard case-sensitive compare.
|
72,147,549 | 72,148,008 | How do you use std::distance in a range-based loop? | This is my code that won't compile:
for( auto occurances : occ ){
if( occurances == 1 )
cout << distance( occ.begin(), occurances )
}
It gave me the following error:
candidate template ignored: deduced conflicting types for parameter '_InputIter'
('std::__wrap_iter<int *>' vs. 'int')
This is the fifth time I encountered this error. Each time, after a bit of research and frustration, I just give up and use the basic for-loop. The problem here is that I am too lazy to write the basic for-loop like:
for( size_t occurances = 0; occurances < occ.size(); occurances++ ){
if( occ[ occurances ] == 1 )
// do something with size_t occurances
}
I tried to insert a * infront of occ.begin() ( i don't really understand pointers ). The error changed to this:
candidate template ignored: substitution failure [with _InputIter = int]: no type
named 'difference_type' in 'std::iterator_traits<int>'
distance(_InputIter __first, _InputIter __last)
How do I fix this? Thanks everyone for answers, really apreciate it. Sorry if this is a duplicate question, I really couln't find the answer.
| You could count the iterations round the loop yourself:
size_t loop_count = 0;
for( auto occurances : occ ){
if( occurances == 1 )
cout << loop_count;
++loop_count;
}
But that's really no easier than just coding the for loop explicitly, and you might forget to bump the counter.
OK, since the OP is interested in doing this for a vector, here's a solution that works for std::vector and std::string ONLY. It works because, for these containers, operator[] returns a reference to the element or character corresponding to the index you pass in, and it is legal (and, here, useful) to take the address of that reference.
Since these containers both guarantee contiguous storage these days, you can just use the difference between two addresses obtained in this way to get what you want.
Here's a simple example:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string s = "abcde";
std::vector <int> v ( { 100, 101, 102, 103, 104 } );
for (const auto &c : s)
{
if (c == 'c')
std::cout << &c - &s [0] << "\n";
}
for (const auto &e : v)
{
if (e == 103)
std::cout << &e - &v [0] << "\n";
}
}
Output:
2
3
Note that, as mentioned in the comments, you need to use auto &, rather than just auto, because auto passes copies into the loop and that would wreck the whole idea.
Live demo.
|
72,147,678 | 72,153,669 | Meshes loaded via Assimp look distorted | So I'm trying to load and render mesh with assimp and DirectX11.(Im loosely following tutorials on youtube) The problem is that it looks weird and distorted. I've checked my meshes - blender and assimp viewer load them correctly.
Results of rendering suzanne from obj file:
Suzanne from obj file
It looks kinda like the index buffer is wrong but i do not see a mistake when propagating it;
Mesh loading code:
struct Vertex
{
struct
{
float x;
float y;
float z;
}Position;
};
Model::Model(const std::string & path)
{
Ref<Zephyr::VertexShader> VertexShader = Zephyr::VertexShader::Create("MinimalShaders.hlsl", "VertexShaderMain");
AddBindable(VertexShader);
AddBindable(Zephyr::PixelShader::Create("MinimalShaders.hlsl", "PixelShaderMain"));
AddBindable(Zephyr::Topology::Create(Zephyr::Topology::TopologyType::TriangleList));
std::vector<Zephyr::InputLayout::InputLayoutElement> InputLayout =
{
{"Position",Zephyr::InputLayout::InputDataType::Float3}
};
AddBindable(Zephyr::InputLayout::Create(InputLayout, VertexShader));
Assimp::Importer Imp;
auto model = Imp.ReadFile(path, aiProcess_JoinIdenticalVertices | aiProcess_Triangulate);
const auto Mesh = model->mMeshes[0];
std::vector<Vertex> Vertices;
Vertices.reserve(Mesh->mNumVertices);
for (unsigned int i = 0; i < Mesh->mNumVertices; i++)
{
Vertex buf;
buf.Position = { Mesh->mVertices[i].x,Mesh->mVertices[i].y ,Mesh->mVertices[i].z };
Vertices.push_back(buf);
}
std::vector<unsigned short> Indices;
Indices.reserve(Mesh->mNumFaces * 3);
for (unsigned int i = 0; i < Mesh->mNumFaces; i++)
{
const auto & face = Mesh->mFaces[i];
if (face.mNumIndices != 3)
{
Zephyr::Log::Error("More than 3 indices per face ?!"); continue;
}
Indices.push_back(face.mIndices[0]);
Indices.push_back(face.mIndices[1]);
Indices.push_back(face.mIndices[2]);
}
AddBindable(Zephyr::VertexBuffer::Create(Vertices));
BindIndexBuffer(Zephyr::IndexBuffer::Create(Indices));
}
My shaders are pretty minimal to
cbuffer CBuff
{
matrix transform;
};
float4 VertexShaderMain(float3 position : Position) : SV_POSITION
{
return mul(float4(position, 1.0), transform);
}
float4 PixelShaderMain() : SV_TARGET
{
return float4(1.0,1.0,1.0,1.0);
}
My pipeline renders correctly, f. ex. cubes which are hard coded, but when i try to load cube from file this happens:
distorted cube
Assimp opens the file and loads the correct number of vertices. Also number of indices seems to be ok(for cube there are 12 triangles and 36 indices)
Honestly at this point I have no idea what im doing wrong. Am i missing sth obvious?
Thanks in advance
| So I've figured it out. The issue was that in some other file i already defined structure named Vertex. That structure contained also uv's so ultimately my vertex buffer ended up being a mess. Silly mistake.
|
72,148,047 | 72,152,028 | Intel MKL for matrix multiplication when rows are not memory-contiguous | Our hardware is Intel Xeon Phi so we are encouraged to get the most out of it by replacing hand-written linear algebra ops (e.g. square matrix multiplications) using Intel MKL.
The question is which should be the correct MKL usage for this case, as the problem of our matrices' rows not being contiguous in memory may forbid the usage of certain functions, e.g. cblas_dgemm.
Is this a use-case for sparse BLAS?
Example of matrix with non contiguous rows:
#include <iostream>
int main()
{
// construct this matrix:
//
// ( 1 2 3 )
// ( 4 5 6 )
const int NCOLS = 3;
// allocate two perhaps-not-contiguous blocks of memory
double *row1 = (double*)malloc(NCOLS * sizeof(double));
double *row2 = (double*)malloc(NCOLS * sizeof(double));
// initialize them to the desired values, i.e.
row1[0] = 1;
row1[1] = 2;
row1[2] = 3;
row2[0] = 4;
row2[1] = 5;
row2[2] = 6;
// allocate a block of two memory elements the size of a pointer
double **matrix = (double**)malloc(2 * sizeof(double*));
// set them to point to the two (perhaps-not-contiguous) previous blocks
matrix[0] = &row1[0];
matrix[1] = &row2[0];
// print
for (auto j=0; j<2; j++)
{
for (auto i=0; i<3; i++)
{
std::cout << matrix[j][i] << ",";
}
std::cout << "\n";
}
}
| Dense BLAS operations can operate on matrices with a given fixed stride but in your case the stride is not constant. Sparse matrices are meant to operate on matrices containing a lot of zeros which is apparently not your case (at least not in the provided example).
Since your matrices is huge in practice (20k x 20k), the fastest solution is to copy the matrix lines in a big contiguous one. Indeed, BLAS dense operations would not be efficient on arrays of arrays even if it was supported (which is AFAIK not the case anyway). This is because arrays of arrays are generally not efficiently stored in cache (if you are lucky, lines can be allocated nearly contiguously though) and require a more complex indexing.
For example, on a x86-64 PC like mine with a ~40 GB/s RAM and a i5-9600KF processor capable of operating at ~300 GFlops on such matrices, a O(n**3) matrix multiplication would require about 2 * 20_000**3 / 300e9 = 53.3 seconds. Meanwhile an optimal copy of the matrix would require about 2 * 8 * 20_000**2 / 40e9 = 0.16 seconds. Thus, the time of the copy is negligible compared to the actual matrix multiplication time. That being said, three copy are certainly needed (the two input matrices and the output one). Additionally, fast BLAS implementations use the Strassen algorithm with a better asymptotic complexity that should be about 2~3 faster in this case. Still, the time of all the copies (~0.5 s) is very small compared to the actual matrix multiplication time (>17.8 s).
On a KNL Xeon Phi, the MCDRAM reach a throughput of ~400 GB/s, the main RAM reach a throughput of ~90 GB/s while the processor can reach 3 TFlops. Thus, if you store the matrices in the MCDRAM, the results should be 1.8~5.3 second for the matrix multiplication and 0.05 second for all the copies. If the matrices are stored in the slow DRAM, then the copy time is 0.21 second which is significantly bigger but still not so big compared to the computation time. If you do not have enough space to store the matrices in MCDRAM, then you can split the matrices in big tiles (eg. 10k x 10k) and compute each tile separately (using copies and a BLAS DGEMM for each tile).
If you want to achieve higher performance, then you can dedicate few threads of the Xeon Phi processor to make copy of some block so to overlap the copy time with the computation time. However, this will certainly make the code much more complex for a small improvement.
|
72,148,345 | 72,148,368 | Array gives different values in main() and in a function() | I am trying to store a 1d array that stores random numbers into another 2d array.
So as you can see, I am trying to store the passed random array a1 from the main() function to the test() function. And then I am adding it into p[][]. But I don't know why when I am trying to output the array p[][] in the main function, it is giving different values from what I have passed to it!
I would highly appreciate your help. As I need to reuse the stored data in p[][] in order to finish my task.
Code:
#include <iostream>
#include <cstring>
using namespace std;
int p[9][9];
void test(int arr[], int rowCount){
for(int j=0; j<9; j++){
p[rowCount][j]=arr[j];
cout << p[rowCount][j] << " ";
}
cout <<endl;
}
int main()
{
int a1[9];
int p[9][9];
int rowCount=0;
int no = 9;
while(no!=0){
for(int i=0; i<9; i++){
a1[i] = rand()%100;
}
test(a1, rowCount++);
no--;
}
for(int i=0; i<9; i++){
for(int j=0; j<9; j++){
cout<<p[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output:
P[][] array in test()
41 67 34 0 69 24 78 58 62
64 5 45 81 27 61 91 95 42
27 36 91 4 2 53 92 82 21
16 18 95 47 26 71 38 69 12
67 99 35 94 3 11 22 33 73
64 41 11 53 68 47 44 62 57
37 59 23 41 29 78 16 35 90
42 88 6 40 42 64 48 46 5
90 29 70 50 6 1 93 48 29
P[][] array in main()
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
-858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460 -858993460
| You have two different p arrays: One in main and one global. The print loop in main is accessing the local p in main while test accesses the global one. That means only the global p gets filled with data and main is stuck with a different array that wasn't filled with data.
Remove the int p[9][9]; in main. That line creates a second array that shadows the first (global) one.
|
72,148,673 | 72,152,877 | Win32 application not finding icon for window | I created a icon as a resource
I checked explorer and it works just fine, my exe now has that icon
Next, I used hIcon to set the icon of my window but it says that IDI_ICON1 is undefined
Code:
wc.hIcon = LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1));
Is there any idea of why this is happening?
| Symbolic constants for resource identifiers (such as IDI_ICON1) are usually stored in a separate header file called Resource.h by default. This allows both the resource script (.rc file) as well as source code to access the same symbols.
To use the constants in source code you need to introduce them through an #include directive. Otherwise the compiler is unable to find them, as the error messages indicates.
|
72,149,102 | 72,164,672 | Add Serialize to SFML Color | I am working on serialization of color data for SFML objects and ran into an issue where they are not supported by default, as they are not a default type. I tried making a wraparound class, which failed but I found info of adding the type to cereal itself. Based off of what I read at Serialize/deserialize SFML Vectors class using cereal, the following code supposedly should work, I have this currently in a .h file.
#include <SFML/Graphics.hpp>
#include <SFML/Config.hpp>
namespace /*cereal*/ sf
{
template<class Archive>
void serialize(Archive& archive, sf::Color& c)
{
archive(
CEREAL_NVP(this->r),
CEREAL_NVP(this->g),
CEREAL_NVP(this->b),
CEREAL_NVP(this->a)
);
}
}
however, I end up with an error still, as follows:
Error C2338 cereal could not find any output serialization functions for the provided type and archive combination. SFML_Tiles C:\Users\97cwe\Documents\Visual Studio Libraries\Cereal\cereal-1.3.2\include\cereal\cereal.hpp 570
I cannot parse the documentation to understand it more, nor does the stack overflow post linked above offer any insight. I probably need to include it somewhere, but as I don't know where, or even if this is the right format, I am asking here
Any help will be greatly appreciated. Thank you
| dergvern47 on Reddit helped me with this. The issue was 2 fold. Accessing the values inside cannot be done with this, but with the object inside the function, and that the .h file this is inside needs to be #include in the highest .h file existing in the project. The original post can be found here https://www.reddit.com/r/cpp_questions/comments/ul7c3v/c_cereal_add_serialization_to_class_in_imported/i7tswiv/?context=3
and the code that they made:
#include <SFML/Graphics.hpp>
#include <cereal/archives/json.hpp>
namespace sf {
template<class Archive>
void serialize(Archive& archive, sf::Color& c)
{
archive(
CEREAL_NVP(c.r),
CEREAL_NVP(c.g),
CEREAL_NVP(c.b),
CEREAL_NVP(c.a)
);
}
}
int main()
{
{
cereal::JSONOutputArchive archive(std::cout);
archive(sf::Color::Magenta);
}
return 0;
}
|
72,150,508 | 72,151,922 | How to represent the relationship for this demo code snippet? | How to represent the relationship between class ResMulti and class Do_work when drawing a class diagram for this demo code snippet (see on godbolt):
#include <thread>
#include <future>
#include <functional>
class Res4ClassA{};
class Res4ClassB{};
Res4ClassA Calculate_A(){return Res4ClassA{};}
Res4ClassB Calculate_B(){return Res4ClassB{};}
class ResMulti
{
public:
void SetRes4ClassA (const Res4ClassA& res_a)
{
res_a_ = res_a;
}
void SetRes4ClassB (const Res4ClassB& res_b)
{
res_b_ = res_b;
}
const Res4ClassA& GetRes4ClassA ()
{
return res_a_;
}
const Res4ClassB& GetRes4ClassB ()
{
return res_b_;
}
private:
Res4ClassA res_a_;
Res4ClassB res_b_;
};
class Do_work
{
public:
void Run(const Res4ClassA* res){}
};
int main()
{
Res4ClassA res_a = Calculate_A();
ResMulti res_multi;
res_multi.SetRes4ClassA(res_a);
Do_work work;
work.Run(&res_multi.GetRes4ClassA());
}
Question: How to represent the relationship between class ResMulti and class Do_work when drawing a class diagram for this demo code snippet?
| There is no direct relationship between ResMulti and Do_work:
Do_work may be dependent on Res4ClassA because it may need to know about that type (not formally in C++, because the pointer is used without ever being dereferenced, but if possibly in the design, if we’d expect the operation to to anything maningful with the referred object);
ResMulti could have a composite aggregation with a Res4ClassA component since it has a C++ member of that type and in view of the language semantics.
main() happens to make the glue. But it is not a structural relationship: it’s a dynamic one that emerges from the behaviors of main() implementation.
|
72,151,124 | 72,151,358 | why alignas(64) not aligned with 64 | why alignas(64) not aligned with 64? for example:
struct alignas(32) st32
{
float a;
uint16_t b;
uint64_t c;
};
struct alignas(64) st64
{
float a;
uint16_t b;
uint64_t c;
};
int main()
{
st32 x;
st64 y;
std::cout
<< "alignof(st32) = " << alignof(st32) << '\n'
<< "alignof(st64) = " << alignof(st64) << '\n'
<< "&st32 a: " << &x.a << '\n'
<< "&st32 b: " << &x.b << '\n'
<< "&st32 c: " << &x.c << '\n'
<< "&st64 a: " << &y.a << '\n'
<< "&st64 b: " << &y.b << '\n'
<< "&st64 c: " << &y.c << '\n';
}
The results is
alignof(st32) = 32
alignof(st64) = 64
&st32 a: 0x7ffc59fc9660
&st32 b: 0x7ffc59fc9664
&st32 c: 0x7ffc59fc9668
&st64 a: 0x7ffc59fc9680
&st64 b: 0x7ffc59fc9684
&st64 c: 0x7ffc59fc9688
why &st64 b: 0x7ffc59fc9684 is not 0x7ffc59fc9688, beacause the address need to 64bits aligned, we should leave 0x7ffc59fc9684-0x7ffc59fc9688 blank, and start next data at 0x7ffc59fc9688.
|
why &st64 b: 0x7ffc59fc9684 is not 0x7ffc59fc9688
Aligning a structure does not affect the alignment of the sub objects of the structure. The address of the enclosing structure is 64 byte aligned, and b is the second member after a 4 byte sized a, so it's reasonable to expect b to not be 64 byte aligned.
if alignas don't align the sub object, then what's the point of this syntax before struct.
The point is to align the class itself. This is sometimes needed for example for SIMD instructions.
|
72,151,184 | 72,151,416 | Moving the function templates definition to different translation unit resolves the ambiguity error | I was using function templates when I noticed that moving the definition of one of the function template to a different translation unit resolves the ambiguous error. Below are the two examples that I tried. The first example produces ambiguous error as expected but when I move the definition of one of the function template into another translation unit then the error is gone.
Example 1
#include <iostream>
template<typename X, typename Y>
void func(X, Y)
{
std::cout<<"X-Y in order version called"<<std::endl;
}
template<typename X, typename Y>
//--------v--v----->order changed
void func(Y, X)
{
std::cout<<"Y-X in order version called"<<std::endl;
}
int main()
{
func(2,2); //this is ambiguous as expected
}
Demo showing that we get ambiguous error as expected.
My question is about the second example given below:
Example 2
main.cpp
#include <iostream>
template<typename X, typename Y>
void func(X, Y)
{
std::cout<<"X-Y in order version called"<<std::endl;
}
extern void init();
int main()
{
func(2,2); //WORKS BUT HOW? How does the compiler resolves the ambiguity here
init();
}
source2.cpp
#include <iostream>
//moved to source2.cpp
template<typename X, typename Y>
//--------v--v----->order changed
void func(Y, X)
{
std::cout<<"Y-X in order version called"<<std::endl;
}
void init()
{
func(2,2);
}
The second version given above successfully compiles and produces the output:
X-Y in order version called
Y-X in order version called
My questions are:
How is the ambiguity resolved when i moved the definition of the second overload to a different translation unit? I mean we still have two intantiations(one from the overload in the main.cpp and other from the overload in source2.cpp) as before but now we're not getting the ambiguity error. So how does the C++ standard resolves this ambiguity.
How does the C++ standard allows the first overload to be selected/preferred instead of the second. I mean is there a reference in the standard that says that the instantiation from the overload in the same translation unit should be selected.
Summary
Note that my second question is about why the first version is preferred over the one in the other translation unit. While my first question is about how is the ambiguity removed when moving the definition to another translation unit.
|
how does the C++ standard resolves this ambiguity.
From temp.over.link#1:
1. It is possible to overload function templates so that two different function template specializations have the same type.
2. Such specializations are distinct functions and do not violate the one-definition rule.
(emphasis mine)
Now, in the given example both the specializations resulting from the two overloads will have the same type void (int, int) and as quoted in the points above, this usage is allowed.
How does the C++ standard allows the first overload to be selected/preferred instead of the second.
To answer the second question, during overload resolution the call func(2,2) inside function init in source2.cpp was already bound to the instantiated version from the second overload. Similarly, for the call expression func(2,2) inside main.cpp, it is bound to the instantiated version from the first overload.
Thus, when init is called from inside main.cpp, the second version is called. If we changed the order of the calls inside main.cpp, then the output will be reversed because the call was already bound to their respective version during overload resolution.
|
72,151,450 | 72,151,535 | On the conversion from std::string type to template T type in C++ | I've found on this forum the following snippet witten by user Ben Voigt:
//forward declaration
template<typename T>
T getline_as(std::istream& s);
template<>
std::string getline_as<std::string>(std::istream& s)
{
std::string str;
std::getline(s,str);
return str;
}
template<typename T>
T getline_as(std::istream& s)
{
std::stringstream convert(getline_as<std::string>(s));
T value;
convert >> value;
return value;
}
I am looking for a way to handle possible failures of convert >> value;. My goal would be
to iterate the request to the user to make it insert a given input correctly:
int main()
{
std::cout << "Please enter a number: ";
double number{getline_as<double>(std::cin)};
}
My idea was to create a do-while loop inside getline_as but I can't make it work.
template<typename T>
T getline_as(std::istream& s)
{
std::stringstream convert;
T value;
do
{
convert(getline_as<std::string>(s));
}
while(!(convert >> value));
return value;
}
| std::stringstream convert(...); is a constructor call, but trying to do convert(...); after the stream is created is illegal (it would require the stream to overload operator(), which it doesn't do). convert = std::stringstream(...) would work, but I'd just completely recreate the stream.
You also should use a read-only std::istringstream, since you never write anything to it.
I also made some cosmetic changes and ended up with following:
template <typename T>
[[nodiscard]] T getline_as(std::istream &s);
template <>
[[nodiscard]] std::string getline_as<std::string>(std::istream &s)
{
std::string str;
std::getline(s, str);
return str;
}
template <typename T>
[[nodiscard]] T getline_as(std::istream &s)
{
while (true)
{
T value{};
std::istringstream convert(getline_as<std::string>(s));
if (convert >> value)
return value;
}
}
|
72,151,546 | 72,151,690 | Too many copies of the function to use std::move in C++ | I have 2 classes: A and B. I need to pass instances of them to a function that will push them into a vector. I want to have good efficiency in my program, so I try to use move semantics. So in that function I need const A& and A&& type for A as well as for B.
It forces me to create 2^N number of functions where N is the number of parameters to that function. In my case N is 2 and this means that I need to create 4 almost identical copies of the function.
Code:
struct A {
std::vector<int> v;
};
struct B {
std::vector<int> v;
};
static std::vector<std::pair<A, B>> elements;
void Function(const A &a, const B &b) {
elements.emplace_back(a, b);
}
void Function(A &&a, const B &b) {
elements.emplace_back(std::move(a), b);
}
void Function(const A &a, B &&b) {
elements.emplace_back(a, std::move(b));
}
void Function(A &&a, B &&b) {
elements.emplace_back(std::move(a), std::move(b));
}
The code is simplified. In my real code, the Function is bigger.
So, I want to know if there is another, better way of doing this?
Hope for your help!
| You can create a template function and use std::forward to pass on the value with the correct reference type:
template<class T, class U>
void Function(T&& a, U&& b) // note: universal references are used here, not rvalue references
{
elements.emplace_back(std::forward<T>(a), std::forward<U>(b));
}
|
72,151,600 | 72,151,685 | value of set::find() if not found in container | I am trying to understand std::find(). Below is my code.
std::set::find searches the container for an element equivalent to
val and returns an iterator to it if found, otherwise it returns an
iterator to set::end.
But when I gave find(100) I am getting 7 rather than 20.
#include <iostream>
#include <set>
using namespace std;
int main()
{
set <int> s1{20, 7, 2};
s1.insert(10);
s1.insert(5);
s1.insert(15);
s1.insert(1);
cout << "size() : " << s1.size() << endl;
cout << "max_size() : " << s1.max_size() << endl;
cout << "empty() : " << s1.empty() << endl;
for(auto itr = s1.begin(); itr != s1.end(); itr++)
cout << *itr << " ";
cout << endl;
cout << endl << "---- find(value) ----" << endl;
auto a1 = s1.find(10);
//cout << "find(10) : " << a1 << " " << *a1 << endl;
cout << "find(10) : " << *a1 << endl;
auto a2 = s1.find(100);
cout << "find(100) : " << *a2 << endl;
cout << endl << "---- count(value) ----" << endl;
cout << "s1.count(10) : " << s1.count(10) << endl;
cout << "s1.count(100) : " << s1.count(100) << endl;
return 0;
}
Output:
size() : 7
max_size() : 107374182
empty() : 0
1 2 5 7 10 15 20
---- find(value) ----
find(10) : 10
find(100) : 7
---- count(value) ----
s1.count(10) : 1
s1.count(100) : 0
|
auto a2 = s1.find(100);
cout << "find(100) : " << *a2 << endl;
Here you dereference (*a2) the end iterator. That is undefined behaviour - remember that s1.end() points to one past the last element and must not be dereferenced.
You're unlucky that you got a value from that dereference - it would be more convenient if your program crashed or otherwise reported the problem. But UB doesn't have to be diagnosed in any way.
You might have spotted the problem if you had run your program using Valgrind's memory checker (or your preferred equivalent). But there's a good chance that's unable to detect it (if the set has over-allocated, which is likely).
|
72,152,281 | 72,152,718 | *char conversion to/from bool in call to strstr | I have code that is supposed to remove all characters in one C-string from another.
The problem arises when I try to use the function strstr: both an array and a char* get converted to bool. Obviously it doesn't work because strstr needs to receive 2 char* arguments.
#include <iostream>
#include <ctype.h>
#include <string.h>
#include <malloc.h>
using namespace std;
char* temp_char(char* orig,char* del)
{ char *str_temp, *temp, *p, *c;
char symbol[2];
int i=0;
int len = strlen(orig);
temp=(char *)calloc(len,1);
str_temp = (char *)calloc(len,1);
strcpy(str_temp,orig);
for(i=0;i<strlen(del);i++){
symbol[0]=del[i];
symbol[1]=0;
temp[0]=0;
while( p=strstr(str_temp,del)!=NULL){
strncat(temp,str_temp,p-str_temp);
p++;
str_temp=p;
}
strcat(temp,str_temp);
strcpy(str_temp,temp);
}
cout<<temp;
return temp;
}
int main () {
char a[]="stuccsess",b[]="test";
temp_char(a,b);}
Any help would be appreciated.
| You have two errors in one line of your code. The first is not addressing the issue that the != operator has higher priority than =. Thus, in the following line:
while( p=strstr(str_temp,del)!=NULL) {
the comparison is actually:
while( p = ( strstr(str_temp,del)!=NULL ) ){
So, you are attempting to assign the result of the != test, which will be a bool value, to a char* variable (p).
You can fix this, easily, by putting the assignment expression in parentheses.
However, although that will fix the compiler error, it will not address the second error. Just a few lines above that while statement, you assign one of the characters of the del string to the first of the symbol string (and, properly, add a nul terminator to that) … but you never then actually use that symbol string. Instead, you pass the entire del string as the second argument in the call to strstr. You should be passing your created symbol as that second argument.
So, changing that while line to the following will make the code work:
while ((p = strstr(str_temp, symbol)) != nullptr) { // Use nullptr in C++
But that leaves other errors in your function. How will you ever be able to free the memory allocated in the str_temp = (char*)calloc(len, 1); call? Once you have subsequently modified that str_temp pointer (in the str_temp = p; line), you no longer have the original pointer value, which must be used when calling free(). So, you need to save that value, just after you have made the allocation. (The temp memory pointer is returned, so that can be freed in the main function.)
There are other issues in your code that could be improved, like using new[] and delete[] in C++, rather than the old, C-language calloc, and that your index and length variables should really be of size_t type, rather than int. Here's a version with the corrections and suggestions discussed applied:
#include <iostream>
#include <cstring>
using std::cout;
char* temp_char(char* orig, char* del)
{
size_t len = strlen(orig);
char* temp = new char[len + 1];
char* str_temp = new char[len + 1];
char* save_temp = temp; // Save it so we can call delete...
strcpy(str_temp, orig);
for (size_t i = 0; i < strlen(del); i++) {
char symbol[2];
symbol[0] = del[i];
symbol[1] = 0;
temp[0] = 0;
char* p;
while ((p = strstr(str_temp, symbol)) != nullptr) {
strncat(temp, str_temp, static_cast<size_t>(p - str_temp));
p++;
str_temp = p;
}
strcat(temp, str_temp);
strcpy(str_temp, temp);
}
cout << temp;
delete[] save_temp; // ... don't forget to free this.
return temp;
}
int main()
{
char a[] = "stuccsess", b[] = "test";
char* answer = temp_char(a, b);
delete[] answer; // We should free the memory allocated!
return 0;
}
But your approach is far more complicated than it need be. You can simply loop through the original string and check each character to see if it is in the 'delete' string (using the strchr function, for example); if it is not (i.e. that strchr returns nullptr), then append the character to the accumulated temp and increase the running length:
char* temp_char(char* orig, char* del)
{
size_t len = strlen(orig);
char* temp = new char[len + 1];
int newlen = 0;
for (char* cp = orig; *cp != '\0'; ++cp) {
if (strchr(del, *cp) == nullptr) temp[newlen++] = *cp;
}
temp[newlen] = '\0'; // Add null terminator
std::cout << temp;
return temp;
}
|
72,153,026 | 72,154,762 | c++ Cannot create magnifier window | Im trying to make a magnification program, but I cannot create the child window without the error 1407, The child window also makes the host windows gui disappear.
hwnd = CreateWindowEx(WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_LAYERED, wc.lpszClassName, skCrypt(_T("magnifier")), WS_POPUP | WS_CLIPCHILDREN, rect.left, rect.top, widthh, heightt, nullptr, nullptr, NULL, nullptr);
RegisterClassEx(&wc2);
magHwnd = CreateWindow(WC_MAGNIFIER, "a", WS_VISIBLE | WS_CHILD, 250, 250, 250, 250, hwnd, NULL, wc2.hInstance, NULL);
if (!magHwnd) {
MessageBox(NULL, std::to_string(GetLastError()).c_str(), "Window Creation", MB_OK);
}
EDIT: the second CreateWindow function works until i add the WC_MAGNIFIER flag
| Thank you to the people that helped me fix this.
I fixed this by changing the classname in wc2 to "Magnifier"
|
72,153,033 | 72,153,249 | Problem passing a method of a class as a std::function parameter | I am trying to write this function:
void CChristianLifeMinistryEditorDlg::PerformAutoAssignForAssignment(
const MSAToolsLibrary::AssignmentType eAssignType,
const CString strStartingName,
std::function<void(CString)> funcSetAssignName)
{
CString strName = L"abc";
CChristianLifeMinistryEntry *pEntry = xxx;
// ...
pEntry->funcSetAssignName(strName);
}
I am having difficulty in passing a function to it:
PerformAutoAssignForAssignment(MSAToolsLibrary::AssignmentType_Host, L"Name 1" );
PerformAutoAssignForAssignment(MSAToolsLibrary::AssignmentType_CoHost, L"Name 2");
PerformAutoAssignForAssignment(MSAToolsLibrary::AssignmentType_ConductorCBS, L"Name 3");
PerformAutoAssignForAssignment(MSAToolsLibrary::AssignmentType_ReaderCBS, L"Name 4");
At the moment I am not passing a function:
void CChristianLifeMinistryEditorDlg::PerformAutoAssignForAssignment(
const MSAToolsLibrary::AssignmentType eAssignType,
const CString strStartingName)
{
CString strName = L"abc";
CChristianLifeMinistryEntry *pEntry = xxx;
// ...
pEntry->funcSetAssignName(strName);
if (eAssignType == MSAToolsLibrary::AssignmentType_ConductorCBS)
{
pEntry->SetCBSConductor(strNameToUse);
}
else if (eAssignType == MSAToolsLibrary::AssignmentType_ReaderCBS)
{
pEntry->SetCBSReader(strNameToUse);
}
else if (eAssignType == MSAToolsLibrary::AssignmentType_Host)
{
pEntry->SetVideoHost(strNameToUse);
}
else if (eAssignType == MSAToolsLibrary::AssignmentType_CoHost)
{
pEntry->SetVideoCohost(strNameToUse);
}
}
Can you see what I am trying to do? I had hoped to avoid the if/else ladder because eventually I will have more functions to add to the ladder for other assignments. I had hoped I could pass them as a function.
| In order make a method of a class callable, you must supply a this object.
Wrapping such a method in a std::function can be done in 2 ways. Both of them associate a specific class instance with a method, making it callable:
Use std::bind - see the documentation: std::bind, and a specific stackoverflow post regarding this issue: Using generic std::function objects with member functions in one class.
Use lambda functions, that keep the this context as a data member of the lambda object. See some general info here: What is a lambda expression in C++11?.
The code below demonstrates this 2 ways.
I used std::string instead of MFC's CString, but the principle is the same.
#include <iostream>
#include <string>
#include <functional>
struct A
{
void Do1(std::string const & str) { std::cout << "A::Do1" << std::endl; };
void Do2(std::string const & str) { std::cout << "A::Do2" << std::endl; };
void Do3(std::string const & str) { std::cout << "A::Do3" << std::endl; };
};
struct Dlg
{
A a;
void Perform(std::string const & str, std::function<void(std::string)> funcSetAssignName)
{
funcSetAssignName(str);
}
void m()
{
std::string str = "abc";
// Pass method as std::function using std::bind:
Perform(str, std::bind(&A::Do1, a, std::placeholders::_1));
Perform(str, std::bind(&A::Do2, a, std::placeholders::_1));
Perform(str, std::bind(&A::Do3, a, std::placeholders::_1));
// Pass method as std::function using lambdas:
Perform(str, [this](std::string const & str) { this->a.Do1(str); });
Perform(str, [this](std::string const & str) { this->a.Do2(str); });
Perform(str, [this](std::string const & str) { this->a.Do3(str); });
}
};
int main()
{
Dlg dlg;
dlg.m();
return 0;
}
The output:
A::Do1
A::Do2
A::Do3
A::Do1
A::Do2
A::Do3
UPDATE:
Following the OP's question in the comment below:
In order to let you determine the instance to apply the method inside Perform, you can use pointer to method. The downside is that the method you pass must be of a specified class (A in my example below). I.e. you loose the ability to pass callables from various classes (or global).
See the code example below:
#include <iostream>
#include <string>
struct A
{
void Do1(std::string const & str) { std::cout << "A::Do1" << std::endl; };
void Do2(std::string const & str) { std::cout << "A::Do2" << std::endl; };
void Do3(std::string const & str) { std::cout << "A::Do3" << std::endl; };
};
struct Dlg
{
A a;
void Perform(std::string const & str, void (A::*funcSetAssignName)(std::string const & str))
{
// Here the instance for class A can be determined (I simply used `a`):
(a.*funcSetAssignName)(str);
}
void m()
{
std::string str = "abc";
// Pass pointer to method:
Perform(str, &A::Do1);
Perform(str, &A::Do2);
Perform(str, &A::Do3);
}
};
int main()
{
Dlg dlg;
dlg.m();
return 0;
}
You can see some more examples here: Calling C++ member functions via a function pointer.
|
72,153,420 | 72,153,563 | Is `auto(expr)` treated as cast at the beginning of the expression statement? | I have a simple code snippet shown below (https://godbolt.org/z/cPT3PhYdj):
int main() {
int x = 1;
auto(1); // ok in GCC, error in Clang
auto{1}; // ok in GCC, error in Clang
static_cast<void>(auto(x)); // ok
auto{x}; // ok in GCC, error in Clang
auto(x); // both error in GCC an Clang
}
Where both GCC and Clang emit an error showing:
// by GCC Trunk [-std=c++23]
<source>: In function 'int main()':
<source>:7:3: error: declaration of 'auto x' has no initializer
7 | auto(x); // why
| ^~~~
Compiler returned: 1
// by Clang Trunk [-std=c++2b]
<source>:3:8: error: expected unqualified-id
auto(1); // why
^
<source>:3:8: error: expected ')'
<source>:3:7: note: to match this '('
auto(1); // why
^
<source>:4:7: error: expected unqualified-id
auto{1}; // why
^
<source>:6:7: error: expected unqualified-id
auto{x}; // why
^
<source>:7:8: error: redefinition of 'x'
auto(x); // why
^
<source>:2:7: note: previous definition is here
int x = 1;
^
<source>:7:8: error: declaration of variable 'x' with deduced type 'auto' requires an initializer
auto(x); // why
^
6 errors generated.
Compiler returned: 1
If C++23 is experimental, and will they be able to fix the ambiguity or change the disambiguation since another auto(expr) is introduced, or just leave it be?
Are these expressions supposed to be parsed as explicit type decay conversion auto(expr) or auto{expr} in expression statements or parsed as a declaration?
If there is no ambiguity, then which priority comes first:
auto(identifier) as auto identifier?, or
auto(identifier) as cast expression?
| From Explicit cast conversion:
auto ( expression ) (8) (since C++23)
auto { expression } (9) (since C++23)
8,9) The auto specifier is replaced with the deduced type of the invented variable x declared with auto x(expression); (which is never interpreted as a function declaration) or auto x{expression}; respectively. The result is always a prvalue of an object type.
So your usage seems to be allowed(in accordance with ) by the above quoted statement.
Here is a working demo of your code. Note in the linked demo, only the usage auto(x) produces an error, all other cases work fine.
Also note that from PR105516:
auto(x); is interpreted as auto x;. Use +auto(x); if you want that to be an expression.
If there is no ambiguity, then which priority comes first:
This is one of the examples showing how C++ is a context sensitive language. A construct cannot always be understood without knowing its wider contexts. Consider the following example:
int main()
{
int x = 0 ;
int k ;
//------vvvvvvv----->here auto(x) is behaves as an expression as it is used as an expression
k = auto(x) ;
auto(p) ; //this a declaration and not an explicit case unlike the above
}
|
72,153,514 | 72,154,577 | Estimation of time required for calculation in Eratosthene's sieve algorithm | I am using Qt and cpp to calculate some time consuming calculation like prime number calculation using Eratosthene's sieve algorithm as shown below.
QElapsedTimer timer;
timer.start();
int p;
for ( p = 2ull; p * p <= n; p++)
{
// If prime[p] is not changed,
// then it is a prime
qDebug() << p << "something inside prime number calculation";
emit progressBarUpdatePrime(p*p+2);
if (prime[p] == true)
{
// Update all multiples
// of p greater than or
// equal to the square of it
// numbers which are multiple
// of p and are less than p^2
// are already been marked.
sync.lock();
if(pausePrime)
pauseCond.wait(&sync); // in this place, your thread will stop to execute until someone calls resume
sync.unlock();
qDebug() << p << "is a prime number";
MyThread2().msleep(1000);
emit NumberChanged(p);
for (int i = p * p; i <= n; i += p){
prime[i] = false;
}
}
}
emit NumberChanged(9999ull);
if(p * p >= n){
qDebug() << p << "p value here";
emit progressBarUpdatePrime(n);
emit elapsedTimePrime(timer.elapsed());
emit estimatedTimePrime((n * log10(log10(n))) + 2);
}
My question is how to calculate he estimated time for this calculation. I used n * log10(log10(n) but that counts for number of iterations.
| Lets ignore if a number is prime or not. Estimating that is a big math problem involving the density of primes and such. Lets just assume every number is prime. That gives:
The code marks all even numbers, so that is N/2 operations. Then all numbers divisible by 3, so N/3 operations. Then N/4, N/5, N/6, N/7, ...
So overall it's the sum i = 2 to sqrt(N): N/i. There is probably a formula to compute or estimate this.
Now in the outer loop we can advance the progress by n / p. If p is prime then the algorithm actually does the work but we just count it as doing n / p work every time. So the progress bar will jump a bit for non primes. It will also speed up towards the end because the work for p isn't actually n / p but n / p - p. You could use that figure in the sum above but then I don't think there is a formula for it and you have to sum it up in a loop.
Note: update the progress after the work for p has been done at the end of the loop, not at the start.
As a side node some improvements for your algorithm:
start with emit NumberChanged(2);, we now 2 is a prime and all other even numbers are not. No need to have them in the sieve at all.
Half the size of the prime array (+ 1 iirc to avoid out of bounds) and change all prime[x] to prime[x / 2]
The outer loop becomes for ( p = 3ull; p * p <= n; p += 2). Only odd numbers are checked
The inner loop becomes for (int i = p * p; i <= n; i += 2 * p). Only odd multiples of p must be marked.
This improvement uses half the memory, skips the most expensive p=2 step and step 4 doubles the speed.
|
72,153,701 | 72,153,870 | unpack variadic arguments and pass it's elements accordingly | suppose I got a struct i.e. Coord that contains two static member variables, then pass it as an argument of variadic template function variadic_print_coord(), how do I unpack the variadic expressions, to call the print_pair() function that shown below.
template<class T1, class T2>
void print_pair(T1 t1, T2 t2)
{
std::cout << t1 << " and " << t2 << '\n';
}
template<class T1, class T2, class ...Ts>
void print_pair(T1 t1, T2 t2, Ts... ts)
{
print_pair(t1, t2);
print_pair(ts... );
}
template<int X, int Y>
struct Coord
{
static const int valueX = X;
static const int valueY = Y;
}
template<class... COORDs>
void variadic_print_coord()
{
print_pair(COORD1::valueX, COORD1::valueY, COORD2::valueX, COORD2::valueY, ...,
COORDs::valueX, COORDs::valueY);
//how could I manipulating the pack expressions to get something like this
}
int main()
{
print_pair<Coord<0,1>, Coord<2,3>, Coord<4,5>>();
//result:
//0 and 1
//2 and 3
//4 and 5
}
many thanks!
| You can use the following construct involving a fold expression
template<class... COORDs>
void variadic_print_coord()
{
(print_pair(COORDs::X, COORDs::Y), ...);
}
In this case you won't need the variadic version of print_pair, as the calls basically decouple.
#include <iostream>
template<class T1, class T2>
void print_pair(T1 t1, T2 t2)
{
std::cout << t1 << " and " << t2 << '\n';
}
template<int X, int Y>
struct Coord
{
static const int valueX = X;
static const int valueY = Y;
};
template<class... COORDs>
void variadic_print_coord()
{
(print_pair(COORDs::valueX, COORDs::valueY), ...);
}
int main()
{
variadic_print_coord<Coord<0,1>, Coord<2,3>, Coord<4,5>>();
//result:
//0 and 1
//2 and 3
//4 and 5
}
|
72,153,819 | 72,153,956 | assigning new array to reference variable | void byReference(int (&p)[3]){
int q[3] = {8, 9, 10};
p = q;
}
I want to write function where i can reassign the p with new array. I am not sure if we can do that.
My goal :
i want to change the original array, like we do swapping of two number by call-by reference.
Edit:
my working solution :
void byReference(int*& p){
int* q = new int[2];
q[0] = 8;
q[1] = 9;
p = q;
}
int main(){
int *x = new int[2];
x[0] = 1;
x[1] = 2;
byReference(x);
return 0;
}
| In c++ it is recomended to use std::array for fixed size arrays, and std::vector for a dynamic size arrays.
Both of them can be passed by refernce, to be modified by a function.
This requires the function to declare that the argument is passed by refernce using the & symbol.
See the example below:
#include <array>
#include <vector>
// Get an array (with a fixed size of 3) by refernce and modify it:
void ModifyStdArray(std::array<int, 3> & a) {
a = std::array<int, 3>{8, 9, 10};
// or:
a[0] = 8;
a[1] = 9;
// etc.
}
// Get a vector by refernce and modify it:
void ModifyStdVector(std::vector<int> & v) {
v = std::vector<int>{ 1,2,3,4 };
// or:
v.clear();
v.push_back(1);
v.push_back(2);
// etc.
}
int main()
{
std::array<int, 3> a1;
// Pass a1 by reference:
ModifyStdArray(a1);
// Here a1 will be modified.
std::vector<int> v1;
// Pass v1 by reference:
ModifyStdVector(v1);
// Here v1 will be modified.
}
|
72,153,836 | 72,154,029 | Issue running c++ code from 2013 using Clion | [I have very little experience with c++, and this is the first time I use it after more than 10 years].
I need to run some c++ code from 2013, and I am having issues doing so. I am using Clion on OSX Monterey (M1 Silicon chip). If I run a very simple script (main.cc below), I get the error
Undefined symbols for architecture arm64:
"Hair::read(char const*, bool)", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture arm64
Is this because the code I am trying to run was written in a different version of c++ than the one I am using to compile it? Or is it an issue related to the architecture I am using? Thanks!
The dataset and the original code is available here.
main.cpp
#include <opencv2/opencv.hpp>
#include <iostream>
#include <Hair.h>
using namespace cv;
using namespace std;
int main() {
const char *path = "strands00001.data";
Hair hair;
hair.read(path, false);
return 0;
}
Here is the function I'm trying to call:
bool Hair::read(const char *filename, bool flip_strands /* = false */)
{
bool ok = ends_with(filename, ".data") ?
read_bin(filename) : read_asc(filename);
if (!ok)
return false;
if (flip_strands) {
int nstrands = strands.size();
for (int i = 0; i < nstrands; i++)
reverse(strands[i].begin(), strands[i].end());
}
// Look for a .xf file, and apply it if found
xform xf;
if (xf.read(xfname(filename)))
apply_xf(xf);
return true;
}
CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project( OpenCVTest )
find_package(OpenCV REQUIRED)
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( OpenCVTest main.cpp )
target_link_libraries( OpenCVTest ${OpenCV_LIBS})
| The problem has nothing to do with architecture or the version of C++. The definition of Hair::read couldn't be found because your CMakeLists.txt wasn't compiling the file that contained it. You need to tell it to compile Hair.cpp in addition to main.cpp, like this:
add_executable( OpenCVTest main.cpp Hair.cpp )
|
72,153,965 | 72,154,433 | C++ method for non class or struct | Is there any way in C++ to have a method for variable which is not a class or struct? Suppose I have a defined type dogs for convenience.
using dogs = std::unordered_map<std::string, dog>;
dogs d;
Now, what I want to achieve is to have a method, e.g. print() which operated on the dogs type variable d.
d.print();
| Your d.print() means invocation of the method print that std::unordered_map<std::string, dog> actually hasn't. You can't add new methods to an existing class in C++ in contrast to e.g. Python because C++ is a statically typed language. The only way to add new method to a class is creating a new class that inherits to the interested class like
struct dogs : std::unordered_map<std::string, dog>{
void print();
};
... // define your dogs::print();
void foo()
{
dogs d;
d.print(); //now you can use it
}
|
72,153,990 | 72,154,236 | C++20: Unable to properly use concepts to enforce that a constructor template parameter is a base of one of two types | I am a bit of a noob to C++20, and I only recently have been able to use C++11/14 so I am trying to update my knowledge and I'm having a bit of trouble trying to use concept requirements. My goal is to ensure that a class of type SocketAddress only takes a type of IpV4Address or IpV6Address in its constructor, while using a template constructor so that I don't have to have 6 different constructor definitions for passing by value, ref, or r-value.
I am able to compile the class of SocketAddress when it is defined as:
template <typename T>
concept IpAddress = std::is_base_of<IpV4Address, T>::value || std::is_base_of<IpV6Address, T>::value;
class SocketAddress
{
public:
SocketAddress() = delete;
template <typename T> requires IpAddress<T>
SocketAddress(T&& ip_address, const uint16_t port) noexcept;
};
template <typename T> requires IpAddress<T>
SocketAddress::SocketAddress(T&& ip_address, const uint16_t port) noexcept :
m_ip_address(std::forward<T>(ip_address))
{
}
However, when I actually attempt to construct a SocketAddress in my tests I get the compiler error:
error C2661: 'CrossPlatformSockets::SocketAddress::SocketAddress': no overloaded function takes 2 arguments
Where my test code is:
SocketAddress socket_address(IpV4Address("127.0.0.1"), 8000);
I'm not really sure what I am missing here such that the compiler is unable to detect the constructor I have defined that takes two inputs. If anyone can help me learn how to use these concepts or point out what is wrong I would greatly appreciate it! I know I could not use concepts, and use some form of static assert/ugly SNFINAE-type solution, however I want to learn the new stuff!
| This is dumb but a clean and rebuild literally fixed my problem.
Additionally given @PatrickRoberts suggestion, my concept is now defined as:
template <typename T>
concept IpAddress = std::is_base_of<IpV4Address, std::remove_cvref_t<T>>::value ||
std::is_base_of<IpV6Address, std::remove_cvref_t<T>>::value;
|
72,154,006 | 72,154,042 | "error: break statement not within loop or switch" in arduino one | i don´t have any idea of coding but i´m doing a school exersice and it gives me the error of the title
while (distancia<200 && distancia>100);
{
lcd.print("ALTO");
delay(1000);
lcd.clear();
delay(1000);
if(distancia<100)
{
break;
}
}
if(distancia<100);
{
lcd.print("INTRUSO EN");
lcd.setCursor(0,1);
lcd.print("LA PUERTA");
tone(11,700,250);
digitalWrite(8,HIGH);
delay(500);
lcd.clear();
digitalWrite(8,LOW);
delay(500);
}
}
It is in arduino and I want that it returns to the first while if (100<distancia) and that ("ALTO") disapear when (distancia<100), pls help, I have no idea of what I´m doing
| Here
while (distancia<200 && distancia>100);
--------------------------------------^
remove that semicolon, it terminates the while right there
while (distancia<200 && distancia>100)
|
72,154,506 | 72,154,778 | Is auto(x); considered a declaration of a variable named x or an explicit type cast in C++23 | I came across this which states:
Not a bug, auto(x); is interpreted as auto x;. Use +auto(x); if you want that to be an expression.
The above seems to imply that since auto(x); is a declaration(equivalent to auto x;) it should be rejected since we're using auto and don't have an initializer.
While this states:
Yes this changed in C++23 so auto(X) creates an rvalue of the decayed type of x.
The above quoted statements seems to be contradicting each other. So my question is what does the C++23 standard say about this? I mean is auto(x); a declaration or a explicit type cast.
| Note the code referenced by the GCC bug in question:
int main() {
int x = 0;
float t;
t = auto(x);
}
auto(x) here is not a statement; it is unequivocally an expression. If auto(x) is used as an expression, it will behave as an expression. If it however is used in a way that makes it a statement, then it will behave as such.
|
72,154,546 | 72,154,572 | Can someone point out the problem in my linked list implementation? | When I compile the following code, I get compile error that " head does not name a type".
Can someone explain what goes wrong ?
#include <iostream>
using namespace std;
/* Link list node */
struct node {
int val;
struct node* next;
node(int x)
{
this->val = x;
next = NULL;
}
};
struct node *head = new node(3);
head -> next = new node(4); // error: head does not name a type.
head -> next->next = new node(5); // error: head does not name a type.
void print(){
struct node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
}
int main()
{
print();
return 0;
}
I cannot figure out why am i getting the error . Please someone help me out .
| Only declarations are allowed outside of functions. Expressions such as head->next = node(4) need to be inside a function. You should move that code into main().
|
72,154,655 | 72,154,795 | How to pass the Image pointer to Image_dos_header in windows | How to properly construct the NtHeader when calling PIMAGE_NT_HEADERS64 Microsoft docs does not seem to have much remarks on this function, the problem is that casting from void* to DWORD fails
int runPE64(void* Image)
{
/*
non relevant code
*/
char CurrentFilePath[1024];
DOSHeader = PIMAGE_DOS_HEADER(Image); // Initialize Variable
NtHeader = PIMAGE_NT_HEADERS64( DWORD(Image) + DOSHeader->e_lfanew); // Initialize
GetModuleFileNameA(0, CurrentFilePath, 1024); // path to current executable
return 0;
}
int main()
{
unsigned char data[] = {0x4D,0x5A,0x00}; // this is dummy data
runPE64(data);
return 0;
}
Error when compiling
$ g++ runPE64.cpp
runPE64.cpp: In function 'int runPE64(void*)':
runPE64.cpp:31:41: error: cast from 'void*' to 'DWORD' {aka 'long unsigned int'} loses precision [-fpermissive]
31 | NtHeader = PIMAGE_NT_HEADERS64( DWORD(Image) + DOSHeader->e_lfanew); // Initialize
| ^~~~~~~~~~~~
runPE64.cpp:31:20: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
31 | NtHeader = PIMAGE_NT_HEADERS64( DWORD(Image) + DOSHeader->e_lfanew); // Initialize
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is there another way to do this or is there any good explanation of what to pass PIMAGE_NT_HEADERS64
| DWORD is 32 bits (4 bytes) in size, in both 32-bit and 64-bit systems.
The compiler is warning you that the size of DWORD is different than the size of a void* pointer in your compilation, so you will lose bits. This means you must be compiling a 64-bit executable, where pointers are 64 bits (8 bytes) in size.
You need to typecast to DWORD_PTR instead, which is the same size as a pointer, whether you compile for 32-bit or 64-bit.
NtHeader = PIMAGE_NT_HEADERS64( DWORD_PTR(Image) + DOSHeader->e_lfanew);
Alternatively, you can use pointer arithmetic instead of integer arithmetic:
NtHeader = PIMAGE_NT_HEADERS64( LPBYTE(Image) + DOSHeader->e_lfanew); // Initialize
|
72,154,684 | 72,156,665 | Printing decimal precision upto desiired number in cpp | I have an application I want to print the precision of the calculated prime number up to the desired number. But the number is omitted on the terminal as shown below.
The code I used for this is as
int main ()
{
cout << "Enter the precision for calculation" << endl;
long num_steps ;
cin >> num_steps ;
cout << "Precision = " << num_steps << endl;
double step;
double x=0.0, pi, sum = 0.0;
cout << "Enter the number of CPU core involved in calculation" << endl;
int numberOfCpuCore = 0;
cin >> numberOfCpuCore;
int i;
step = 1.0l/( double) num_steps;
}
pi = step * sum;
printf("Pi value = %.10le\n", pi);
return 0;
}
My question is how can I print the precision to the desired number as entered from the command line.
| use iomanip. first add #include <iomanip> and then std::setprecision(num_steps) like this program:
This code was written based on Calculate Pi from Geeks For Geeks.
#include <cstdio>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// Initialize denominator
double k = 1;
// Initialize sum
double s = 0;
for (auto i(0); i < 10000; i++)
{
if (i % 2 == 0)
{
s += 4 / k;
}
else
{
s -= 4 / k;
}
// denominator is odd
k += 2;
}
cout << "Pi value =" << std::setprecision(k) << s << endl;
// printf("Pi value = %.10le\n", pi);
return 0;
}
This will be the output:
|
72,154,759 | 72,154,847 | The "break statement" is just not working like it should | This is the code but for some reason, when (distancia<100) the ("ALTO") still appears, and the same with the other while loop
while (distancia<200 && distancia>100)
{
lcd.print("ALTO");
delay(1000);
lcd.clear();
delay(1000);
if(distancia<100)
{
break;
}
}
while(distancia<100)
{
lcd.print("INTRUSO EN");
lcd.setCursor(0,1);
lcd.print("LA PUERTA");
tone(11,700,250);
digitalWrite(8,HIGH);
delay(500);
lcd.clear();
digitalWrite(8,LOW);
delay(500);
if(distancia>100);
{
break;
}
}
}
| this is your while loop:
while (distancia<200 && distancia>100)
and this is your if:
if(distancia<100);
{
break;
}
a variable can't be greater and smaller than 100 at the same time so that if is basically useless
|
72,155,084 | 72,155,259 | Is there a way to turn input string to input stream in c++? | What I want to do is get user input from the terminal and use this input in other functions in my program. Since my functions only take input streams as arguments I want to convert the input string into an input stream.
int main(int argc, char** argv)
{
std::vector<std::string> args(argv, argv + argc);
if(args.size() == 1){ //if no arguments are passed in the console
std::string from_console;
std::istringstream is;
std::vector<std::string> input;
while(!getline(std::cin,from_console).eof()){
input.emplace_back(from_console);
}
for(std::string str : input){
std::cout << "\n" << str;
}
}
Another questions that arose when I was trying this code, was that when I ended the console input with a bunch of characters and not with a new line(pressing enter then ctrl+d) the line was ignored and didn't get printed out.
Example:
When I typed the following:
aaa bbb
ccc ctrl+d
I got only the first line(aaa bbb) and not ccc printed out.
But:
aaa bbb
ccc
ctrl+d
prints out ccc as well, but it does ignore the new line. So why is this happening?
| The std::istringstream class has a constructor that takes a std::string as an argument, which uses a copy of the string passed as the initial content of the stream.
So, rather than use a std::vector to store all your input lines from the console, just keep adding those to a single (different) std::string object, remembering to add the newlines after each, then construct your std::istringstream from that.
Here is a trivial example that shows how you can use std::getline (which, like your functions, takes an input stream as its first argument) equally well on std::cin and a std::istringstream object created like that:
#include <iostream>
#include <sstream>
int main()
{
std::string buffer; // Create an empty buffer to start with
std::string input;
// Fill buffer with input ...
do {
getline(std::cin, input);
buffer += input;
buffer += '\n';
} while (!input.empty()); // ... until we enter a blank line
// Create stringstream from buffer ...
std::istringstream iss{ buffer };
// Feed input back:
do {
getline(iss, input);
std::cout << input << "\n";
} while (!input.empty());
return 0;
}
|
72,155,568 | 72,155,624 | Circular main in makefile | when i run "make" with the Makefile I wrote, it says "Circular main <- main dependency dropped." how to solve it?
main: main main.cpp pair.cpp
g++ -o main main.cpp pair.cpp
generate:
g++ -shared -fPIC -o libpair.so pair.cpp
clean:
rm main.exe
| main: main main.cpp pair.cpp
g++ -o main main.cpp pair.cpp
There are too many mains in your makefile, make sure that you know the first main is the target name, and the second one is an executable that generated by "something else".
tar_main: main_exec main.cpp pair.cpp
g++ -o main_exec main.cpp pair.cpp
Assume we modify your makefile as this to identify the two mains. Here, to generate the target tar_main, make requires main.cpp, pair.cpp and main_exec. But we have no main_exec yet and it can only generated by target tar_main...
So tar_main is waiting for someone to generate main_exec and provides to it, and tar_main can only be generated by tar_main itself, in your makefile. That's a dead-lock, and the cycle can be detected, make will refuse to run this.
|
72,155,603 | 72,155,738 | how to evaluate concept to false upon expression compilation error | I was trying to change the following example concept code that, under certain inputs, caused an error instead of evaluating false:
template <typename T>
constexpr bool inner = T::prop;
template <typename T>
concept outer = inner<T>;
struct pass {static constexpr bool prop = true;};
struct fail {static constexpr bool prop = false;};
struct bad_fail {static constexpr std::tuple<> prop{};};
static_assert(outer<pass>);
static_assert(not outer<fail>);
static_assert(not outer<bad_fail>);
This has compile error cannot convert 'const std::tuple<>' to 'const bool'.
I attempted to only evaluate inner when it would compile using a requires clause:
template <typename T>
constexpr bool inner = T::prop;
template <typename T>
concept outer = []() consteval -> bool {
if constexpr (
requires() {{
inner<T>
} -> std::same_as<const bool&>;}
) {
return inner<T>;
} else {
return false;
}
}();
struct pass {static constexpr bool prop = true;};
struct fail {static constexpr bool prop = false;};
struct bad_fail {static constexpr std::tuple<> prop{};};
static_assert(outer<pass>);
static_assert(not outer<fail>);
static_assert(not outer<bad_fail>);
This results in a confusing error:
error: non-constant condition for static assertion ... static_assert(not outer<bad_fail>)
And the same cannot convert 'const std::tuple<>' to 'const bool' which appears to be from the 2nd inner. (The compiler does not specify)
I then attempted to combine the compilation check and truth check into a static_assert check within a requires clause:
template <typename T>
constexpr bool inner = T::prop;
template <typename T>
concept outer = requires() {{
[]() constexpr {
static_assert(inner<T>);
}()
} -> std::same_as<void>;};
struct pass {static constexpr bool prop = true;};
struct fail {static constexpr bool prop = false;};
struct bad_fail {static constexpr std::tuple<> prop{};};
static_assert(outer<pass>);
static_assert(not outer<fail>);
//static_assert(not outer<bad_fail>);
This results in a confusing error:
error: static assertion failed ... static_assert(not outer<fail>)
This is confusing because:
error: static assertion failed ... static_assert(inner<T>)
Is also thrown, implying that static_assert escapes requires clauses. Which sure enough is true:
template <std::monostate>
concept should_false = requires() {{
[]() constexpr {
static_assert(false);
}()
} -> std::same_as<void>;};
As this has compile error error: static assertion failed ... static_assert(false)!
How can I have outer<bad_fail> evaluate to false with no compilation errors?
| You can use requires-clause to initialize inner, which first requires that the return type of T::prop must be const bool&, then use nested requires with T::prop as its value
#include <concepts>
template <typename T>
constexpr bool inner = requires {
{T::prop} -> std::same_as<const bool&>;
requires T::prop;
};
template <typename T>
concept outer = inner<T>;
Demo
|
72,155,848 | 72,156,635 | Loading C++ dll in python doesn't work with C++ libs | So I am trying to make a C/C++ dll for a project but any C++ library I include in my header, ends up causing loading problems when I try to load it using ctypes in python. I'm guessing maybe ctypes doesn't have c++ libs paths included? I made a simple demonstration to my problem.
init2.h: Generic Header file for dll and execs using the dll
#ifndef INIT2_H
#define INIT2_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
void func11();
#ifdef __cplusplus
}
#endif
#endif
init2.cc: dll code (loads fine)
// This works fine
#include "init2.h"
void func11() {
printf("Func11\n");
}
init.c: exe code that loads dll
#include "init2.h"
int main() {
func11();
return 0;
}
Makefile
CFLAGS = -Wall -std=c11 -g
CCFLAGS = -Wall -std=c++11 -g
all: libmain.dll main
main.o: init2.cc
g++ $(CCFLAGS) init2.cc -fpic -c -o main.o
libmain.dll: main.o
g++ $(CCFLAGS) -shared main.o -o libmain.dll
main: init.c
gcc $(CFLAGS) -L. -lmain init.c -o main
clean:
del *.o *.exe *.dll *.txt
script.py
from ctypes import *
lib = CDLL('D:\Projects\Learning-C++\libmain.dll')
lib.func11()
The above compiles, links and loads fine in the generated main.exe and script.py. The problem occurs when I add a c++ lib in my dll.
init2.cc: With iostream (loads in main.exe only)
#include "init2.h"
#include <iostream>
void func11() {
std::cout << "Func11\n";
}
Compiling that into the dll, while everything stays the same loads fine into the main.exe (init.c code) but gives me the following loading error in script.py.
Traceback (most recent call last):
File "D:\Projects\Learning-C++\script.py", line 3, in <module>
lib = CDLL('D:\Projects\Learning-C++\libmain.dll')
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3312.0_x64__qbz5n2kfra8p0\lib\ctypes\__init__.py", line 374, in __init__
self._handle = _dlopen(self._name, mode)
FileNotFoundError: Could not find module 'D:\Projects\Learning-C++\libmain.dll' (or one of its dependencies). Try using the full path with constructor syntax.
How can I fix this? My bad if these seems obvious, but I'm fairly new to C++ and haven't got the integration down yet. Thanks in advance!
| The problem was as I expected due to cdll not able to find the C++ library. The file name for my case was libstdc++-6.dll. Which is located in the bin folder in my compiler's directory. To make cdll search for the dependencies in that folder I did the following:
import os
# add dependency directory
os.add_dll_directory('C:\\Program Files\\CodeBlocks\\MinGW\\bin')
# load the dll
lib = CDLL('D:\\Projects\\Learning-C++\\libmain.dll')
lib.func11()
The dll may have many dependencies located in other directories e.g. You defined libDLL.dll and bin/libDependency.dll. You will need to add the /path/to/dir/bin directory using the above method if you're trying to load libDLL.dll in python. You can find all the dependencies of a dll using dependency walker or
dumpbin /dependents libDLL.dll
in the VS dev powershell.
|
72,156,800 | 72,157,004 | Replace every occurrence with double in string | I'm trying to write a function whose first parameter is a string and the second parameter is vector of real numbers. The function should return as a result a new string in which each occurrence replaces the sequences "%d" or "%f" with one number each from the vector, in the order in which they appear. In doing so, if the sequence is "%d", any decimals in the number are truncated, while in the sequence "%f" they are retained.
For example, if the string reads “abc%dxx%fyy %d” and if the vector contains the numbers 12.25, 34.13, 25 and 47, the new string should read “abc12xx34.13yy 25” (data 47 which is “redundant” is simply ignored).
#include <iostream>
#include <string>
#include <vector>
std::string Replace(std::string s, std::vector < double > vek) {
std::string str;
int j = 0;
for (int i = 0; i < s.length(); i++) {
while (s[i] != '%' && i < s.length()) {
if (s[i] != 'f' && s[i] != 'd')
str += s[i];
i++;
}
if (s[i] == '%' && (s[i + 1] == 'd' || s[i + 1] == 'f')) {
if (s[i + 1] == 'd')
str += (std::to_string(int(vek[j])));
if (s[i + 1] == 'f') {
std::string temp = std::to_string(vek[j]);
int l = 0;
while (temp[l] != '0') {
str += temp[l];
l++;
}
}
j++;
if (j > vek.size())
throw std::range_error("Not enough elements");
if (i == s.length()) break;
}
}
return str;
}
int main() {
try {
std::cout<<Replace("abc%dxx%fyy %d",{12.25, 34.13, 25});
std::cout << "\n" << "abc12xx34.13yy 25";
} catch (std::range_error e) {
std::cout << e.what();
}
return 0;
}
OUTPUT:
abc12xx34.13yy 25
abc12xx34.13yy 25
Output is correct. How could I modify this to work with less lines of code? Is there any way to make this more elegant and efficient?
| You could use:
regular expressions to search for the pattern (%d|%f), i.e., %d or %f, and
a string stream to create the string to return.
Going into some more detail:
The code is basically a while (std::regex_search).
std::regex_search will return whatever was in the input string before the matched pattern (what you want in the output string), the matched pattern (what you will need to check in order to decide if you want to write out an int or a double), and whatever is left to parse.
By using std::ostringstream, you can simply write out ints or doubles without converting them to strings yourself.
vek.at() will throw an std::out_of_range exception if you run out of data in the vector.
Notice as well that, whereas for this implementation it's good to pass the string s by value (since we are modifying it within the function), you should pass vek as a const reference to avoid a copy of the whole vector.
[Demo]
#include <iostream>
#include <regex>
#include <stdexcept>
#include <sstream>
#include <string>
#include <vector>
std::string Replace(std::string s, const std::vector<double>& vek) {
std::regex pattern{"(%d|%f)"};
std::smatch match{};
std::ostringstream oss{};
for (auto i{0}; std::regex_search(s, match, pattern); ++i) {
oss << match.prefix();
auto d{vek.at(i)};
oss << ((match[0] == "%d") ? static_cast<int>(d) : d);
s = match.suffix();
}
return oss.str();
}
int main() {
try {
std::cout << Replace("abc%dxx%fyy %d", {12.25, 34.13, 25});
std::cout << "\n"
<< "abc12xx34.13yy 25";
} catch (std::out_of_range& e) {
std::cout << e.what();
}
}
// Outputs:
//
// abc12xx34.13yy 25
// abc12xx34.13yy 25
[EDIT] A possible way to do it without std::regex_search would be to search for the (%d|%f) pattern manually, using std::string::find in a loop until the end of the string is reached.
The code below takes into account that:
the input string could not have that pattern, and that
it could have a % character followed by neither d nor f.
[Demo]
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
std::string Replace(std::string s, const std::vector<double>& vek) {
std::ostringstream oss{};
size_t previous_pos{0};
size_t pos{0};
auto i{0};
while (previous_pos != s.size()) {
if ((pos = s.find('%', previous_pos)) == std::string::npos) {
oss << s.substr(previous_pos);
break;
}
oss << s.substr(previous_pos, pos - previous_pos);
bool pattern_found{false};
if (s.size() > pos + 1) {
auto c{s[pos + 1]};
if (c == 'd') {
oss << static_cast<int>(vek.at(i));
pattern_found = true;
} else if (c == 'f') {
oss << vek.at(i);
pattern_found = true;
}
}
if (pattern_found) {
++i;
previous_pos = pos + 2;
} else {
oss << s[pos];
previous_pos = pos + 1;
}
}
return oss.str();
}
int main() {
try {
std::cout << Replace("abc%%dx%x%fyy %d", {12.25, 34.13, 25}) << "\n";
std::cout << "abc%12x%x34.13yy 25\n";
std::cout << Replace("abcdxxfyy d", {12.25, 34.13, 25}) << "\n";
std::cout << "abcdxxfyy d\n";
} catch (std::out_of_range& e) {
std::cout << e.what();
}
}
// Outputs:
//
// abc%12x%x34.13yy 25
// abc%12x%x34.13yy 25
// abcdxxfyy d
// abcdxxfyy d
|
72,156,970 | 72,161,464 | xt::random::binomial returns different results based on output size | I am writing code to generate an NxN matrix of 0s and 1s in XTensor where the probability of an entry being 1 is 1/N. Additionally, I want to discard all values on the diagonal and above. Finally, I want to find the indices of all 1s. Hence, I am using the following code:
auto binomial = xt::tril(
xt::random::binomial(
xt::shape<uint32_t>({N, N}), 1, 1/N
),
1
);
std::vector<std::array<unsigned int, 2>> vals = xt::argwhere(binomial);
The expected size of vals here should be N. This is true when I try N=100, N=1000, N=10000, but does not hold when I try N=100000. Are there any limitations to this approach that I am not aware of?
| It appears that you have to worry about types here. Internally, you should be able to resolve indices up the N * N. For you N = 1e5 that means 1e10. The maximum size of uint32_t is about 4e9, so that means that you overflow.
What does seem to work is
size_t N = 100000;
auto binomial = xt::tril(
xt::random::binomial(
xt::shape<size_t>({N, N}), 1, 1/(double)N
),
1
);
auto vals = xt::argwhere(binomial);
I wonder if this should be considered a bug though. Looking at the API I would expect that xt::shape<uint32_t>({N, N}) should be of a type that is able to handle the maximum N that you want. Rather, it seems that xt::shape<T> sets T for internal sizes, so that T should be of a type that can handle N^d. I wonder if it should be considered fair that you are able to influence internal types in this way. Please consider opening a bug report (with a link to this question) to resolve this.
|
72,157,313 | 72,158,973 | How to retrieve a previously declared variable with __COUNTER__ pasted inside its name in C++? | I have the following problem:
#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
If I wanted to retrieve a specific variable##__COUNTER__ later in the code how can I achieve this? I only need to get the previous one, something like:
#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
#define GET_NAME_PREV(N, VAL) CONCAT(N, VAL)
auto CREATE_NAME(v);
auto test_current_counter_value = GET_NAME_PREV(v, __COUNTER__ -1);
Thank you.
| BOOST_PP_SUB macro from boost library can be evaluated and expanded to an identifier.
#include <boost/preprocessor/arithmetic/sub.hpp>
#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
#define GET_NAME_PREV(N) CONCAT(N, BOOST_PP_SUB(__COUNTER__, 1))
auto CREATE_NAME(v) = true;
auto test_current_counter_value = GET_NAME_PREV(v);
Try it on Compiler Explorer.
|
72,157,397 | 72,157,403 | clang++ library not found even when providing library path | I was trying to create a new OpenGL project with glfw and glad using vs code on an m1 Mac, and setup the files such that I have the include folder and lib folder which contains the necessary headers and library (libglfw3.a) files and the src folder that contains the glad.c and main.cpp, all in my workspace folder.
I have modified the tasks.json file like such:
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: clang++ build active file",
"command": "/usr/bin/clang++",
"args": [
"-fdiagnostics-color=always",
"-g",
"-std=c++17",
"-I${workspaceFolder}/include",
"-L${workspaceFolder}/lib",
"${workspaceFolder}/src/*.cpp",
"${workspaceFolder}/src/glad.c",
"-llibglfw3",
"-o",
"${workspaceFolder}/game"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "compiler: /usr/bin/clang++"
}
]
}
However, I get the following error:
ld: library not found for -llibglfw3
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I thought that I had properly included the path to the glfw library, but it says that it could not find the library. What am I doing wrong?
As a side-note, I have followed this tutorial to setup the program, but this post assumes that you have a windows machine, so I had downloaded/changed some things to my knowledge of what would work with the m1 mac.
| Normally when you give libraries to link with the -l flag, you omit the lib prefix. For example: "-lglfw3" links the file "libglfw3.a". It looks like you should change your -llibglfw3 option.
|
72,157,815 | 72,157,918 | Ctrl still pressed with keyb_event() | i'm trying to help a friend with a macro for his mouse, but i've been strugling with an error.
But when i use :
if(GetAsyncKeyState(VK_XBUTTON2)){
keybd_event(VK_LCONTROL, 0xA2, 0x0001, 0);
Sleep(50);
keybd_event(VK_LCONTROL, 0xA2, 0x0002, 0);
Sleep(50); }
My ctrl still holded unless i click in my console and press ctrl again.
| Don't use magic numbers in your code, it makes it harder to read and understand. Use named constants instead. In this case, KEYEVENTF_EXTENDEDKEY and KEYEVENTF_KEYUP. Then you will notice that you are not specifying the KEYEVENTF_EXTENDEDKEY flag when releasing the key. Use the | (bitwise OR) operator to combine flags.
Also, don't hard-code the scan code, as it may differ on different machines. Use MapVirtualKey() instead.
Try this:
const BYTE scanCode = MapVirtualKey(VK_LCONTROL, MAPVK_VK_TO_VSC);
...
if (GetAsyncKeyState(VK_XBUTTON2)){
keybd_event(VK_LCONTROL, scanCode, KEYEVENTF_EXTENDEDKEY, 0);
Sleep(50);
keybd_event(VK_LCONTROL, scanCode, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
Sleep(50);
}
That said, keybd_event() is deprecated, use SendInput() instead:
INPUT input = {};
input.type = INPUT_KEYBOARD;
input.ki.wVk = VK_LCONTROL;
input.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;
...
if (GetAsyncKeyState(VK_XBUTTON2)){
input.ki.dwFlags &= ~KEYEVENTF_KEYUP;
SendInput(1, &input, sizeof(INPUT));
Sleep(50);
input.ki.dwFlags |= KEYEVENTF_KEYUP;
SendInput(1, &input, sizeof(INPUT));
Sleep(50);
}
|
72,157,936 | 72,157,962 | This is a question from GFG. I am trying to analyse and understand this code | This is a code I have taken from GeeksForGeeks. I am trying to understand the code.
In the line in the function deleteEle which says if(i==n) return n, how could i become n if it is running for < n times in the for loop just above it?
#include <iostream >
#include <cmath>
using namespace std;
int deleteEle(int arr[], int n, int x)
{
int i = 0;
for(i = 0; i < n; i++)
{
if(arr[i] == x)
break;
}
cout << i << endl;
if(i == n)
cout<<i;
return n;
for(int j = i; j < n - 1; j++)
{
arr[j] = arr[j + 1];
}
return n-1;
}
int main() {
int arr[] = {3, 8, 12, 5, 6}, x = 13, n = 5;
cout<<"Before Deletion"<<endl;
for(int i=0; i < n; i++)
{
cout<<arr[I]<<" ";
}
cout<<endl;
n = deleteEle(arr, n, x);
cout<<"After Deletion"<<endl;
for(int i=0; i < n; i++)
{
cout<<arr[I]<<" ";
}
}
|
how could I become n if it is running for < n times in the for loop just above it?
Because it may happen that the if condition arr[i] == x inside the preceding for loop is never satisfied which in turn means that the break is never executed in which case the last iteration will increment i so that i becomes equal to n.
|
72,157,975 | 72,158,307 | C++ Set: thread 1 is inserting, is the inserting result visible to iterator in thread 2? | I have following code
#include <thread>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <set>
#include <string>
#include <chrono>
#include <atomic>
using namespace std;
set<string> messages_;
mutex mu;
void thread1() {
for(int i=0; i<20; ++i) {
{
lock_guard<mutex> lock(mu);
messages_.insert(to_string(i));
}
this_thread::sleep_for(chrono::milliseconds(20));
}
}
condition_variable cond;
mutex mutex_;
atomic<bool> stop{false};
int workaround = 0;
mutex* GetCoutMutex() {
static std::mutex mu;
return μ
}
void Work() {
workaround++;
unique_lock<mutex> lock(mu);
for(auto it=messages_.begin(); it!=messages_.end(); ) {
lock.unlock();
{
lock_guard<mutex> cout_lock(*GetCoutMutex());
cout << "work around: " << workaround << ", message: " << *it << endl;
}
lock.lock();
it=messages_.erase(it);
}
}
void thread2() {
while(!stop.load(memory_order_acquire)) {
Work();
unique_lock<mutex> lock(mutex_);
cond.wait_for(lock, chrono::milliseconds(50), []{ return stop.load(memory_order_acquire); });
}
}
int main() {
thread t1(thread1), t2(thread2);
t1.join();
this_thread::sleep_for(chrono::milliseconds(100));
stop.store(true, memory_order_release);
cond.notify_one();
t2.join();
}
My expected output is
work around: 1, message: 0
work around: 2, message: 1
work around: 2, message: 2
work around: 3, message: 3
work around: 3, message: 4
work around: 4, message: 5
work around: 4, message: 6
work around: 4, message: 7
work around: 5, message: 8
work around: 5, message: 9
work around: 6, message: 10
work around: 6, message: 11
work around: 7, message: 12
work around: 7, message: 13
work around: 7, message: 14
work around: 8, message: 15
work around: 8, message: 16
work around: 9, message: 17
work around: 9, message: 18
work around: 9, message: 19
in which, the message number is a increasing sequence 0,1,2,...,19 and most executions meet the expection.
However, I got following output in some execution:
work around: 1, message: 0
work around: 2, message: 1
work around: 2, message: 2
work around: 3, message: 3
work around: 3, message: 4
work around: 4, message: 5
work around: 4, message: 6
work around: 5, message: 7
work around: 5, message: 8
work around: 6, message: 10
work around: 6, message: 11
work around: 6, message: 9
work around: 7, message: 12
work around: 7, message: 13
work around: 8, message: 14
work around: 8, message: 15
work around: 9, message: 16
work around: 9, message: 17
work around: 9, message: 18
work around: 10, message: 19
As far as I know, thread1 and thread2 are synchronized with mu, so the insertion of thread1 should be visible to thread2. As thread1 insert 9 before 10, and thread2 is iterating the set in order, so 9 should be output first by thread2.
I'm confused. Can someone explain why 10 is output before 9?
| Since the set contains std::string, the elements are sorted in lexicographic order.
Suppose Thread 1 gets to insert strings "9", "10" and "11" while Thread 2 is waiting on condvar. In this case, "10" will be the smallest string and thus it will be printed first followed by "11" and "9".
|
72,158,223 | 72,162,165 | Variadic template template wrapper: weird compilers errors, possibly bugs | Over years of template metaprogramming practice, I have encountered all sorts of weird compiler bugs and errors. But with this one, I must say that I am somewhat puzzled. I have no idea which compiler is correct: gcc, clang, msvc, and intel all give different results (and as surprising as it may sound, only intel compiles the code without errors). Even more surprising, it does not rely on any new C++ feature as only C++11 is involved.
The code will speak for itself as it is relatively simple. It only consists of a variadic template template wrapper with a variadic inner entity that can be either a struct or an alias template. And for whatever reason, the alias template version returns an error for some compilers when an instance of it is constructed:
#include <type_traits>
template <class T1, class T2, class T3>
struct ternary {};
template <template <class...> class Template, class... Types>
struct template_struct {
template <class... Args>
struct type: Template<Types..., Args...> {};
};
template <template <class...> class Template, class... Types>
struct template_alias {
template <class... Args>
using type = Template<Types..., Args...>;
};
And now the test:
int main(int, char**) {
using ts0 = template_struct<ternary>; // OK
using ts1 = template_struct<ternary, bool>; // OK
using ts2 = template_struct<ternary, bool, char>; // OK
using ts3 = template_struct<ternary, bool, char, int>; // OK
using ts4 = template_struct<ternary, bool, char, int, double>; // OK
ts0 s0; // OK
ts1 s1; // OK
ts2 s2; // OK
ts3 s3; // OK
ts4 s4; // OK
using ta0 = template_alias<ternary>; // OK
using ta1 = template_alias<ternary, bool>; // OK
using ta2 = template_alias<ternary, bool, char>; // OK
using ta3 = template_alias<ternary, bool, char, int>; // OK
using ta4 = template_alias<ternary, bool, char, int, double>; // OK
ta0 a0; // OK
ta1 a1; // OK
ta2 a2; // OK
ta3 a3; // GCC, INTEL => OK | CLANG, MSVC => ERROR: WAIT WHAT ?!?!
ta4 a4; // INTEL => OK | GCC, CLANG, MSVC => ERROR
return 0;
}
The code is available on compiler explorer: https://godbolt.org/z/3ndYMWvfs
QUESTION: What is happening? Which compiler is correct? What does the standard say? Is it a compiler bug?
| All compilers are right, the two failing tests are ill-formed NDR ("No Diagnostic Required").
The > 3 arguments case is ill-formed NDR because of [temp.res.general]/6.1:
The program is ill-formed, no diagnostic required, if:
— no valid specialization can be generated for a template ... and the template is not instantiated, ...
The == 3 arguments case is ill-formed NDR because of [temp.res.general]/6.3:
The program is ill-formed, no diagnostic required, if:
— every valid specialization of a variadic template requires an empty template parameter pack ...
The two template_struct<ternary, ...> tests appear to be legal because you can specialize the struct type into something valid, and I don't immediately see a rule that there must be at least one valid specialization of the primary (unspecialized) template.
|
72,158,300 | 72,158,465 | Is there a way to use (std::cin).get() to accept newlines when asking for input? | (std::cin).get()
I want to use std::cin to collect a string with spaces, like "1/2 oz of flower". When I add a space and then press enter it exits the program instead of collecting the rest of the input.
Found this stdcin-and-why-a-newline-remains and I saw a comment that says you can use .get(), but its not working for me.
How to use (std::cin).get() to accept the spaces when inputing data?
#include <iostream>
#include <vector>
#include <fstream> // std::filebuf
using std::cout, std::cin, std::string, std::endl;
int main(int argc, char const *argv[])
{
string total, quantity, dealer;
cout << "Total($): " << endl; (cin >> total).get();
// If there's a space in total, it doesn't collect the other
// variables
cout << "Quantity: " << endl; cin >> quantity;
cout << "dealer: " << endl; cin >> dealer;
std::filebuf fb;
fb.open ("file.txt",std::ios::out);
std::ostream os(&fb);
os << total << endl << quantity << endl << dealer << endl;
fb.close();
return 0;
}
| I think you should use https://en.cppreference.com/w/cpp/string/basic_string/getline to parse the whole input and then split it on space according to your needs.
|
72,158,325 | 72,158,472 | Why undeclared identifier error occurres while I'm using objet in class's function? | I've been self teaching CPP OOP and this error occurred:
Error C2065 'carObj1': undeclared identifier
And since I'm self teaching I tried to search on Internet but nothing found!
Can anyone help me with this?
#include <iostream>
#include <string>
using namespace std;
class car {
public:
string brand;
string model;
int year;
void enterCar() {
cout << "\nYour car is:" << carObj1.brand << " MODEL:" << carObj1.model << " BUILT-IN:" << carObj1.year;
}
};
int main()
{
car carObj1;
cout << "Enter your car's brand name:\n";
cin >> carObj1.brand;
cout << "Enter your car's Model:\n";
cin >> carObj1.model;
cout << "Enter your car's Built-in year:\n";
cin >> carObj1.year;
carObj1.enterCar();
return 0;
}
| The problem is that you're trying to access the fields brand, model and year on an object named carObj1 which isn't there in the context of the member function car::enterObj.
To solve this you can either remove the name carObj1 so that the implicit this pointer can be used or you can explicitly use the this pointer as shown below:
void enterCar() {
//-------------------------------------------vvvvv-------------->equivalent to writing `this->brand`
std::cout << "\nYour car is:" << brand <<std::endl;
//-----------------------------------vvvvvv------------------->explicitly use this pointer
std::cout<< " MODEL:" << this->model << std::endl;
std::cout<<" BUILT-IN:" << this->year;
}
Also i would recommend learning C++ using a good C++ book.
|
72,158,419 | 72,412,705 | Generate preprocesed file ( .i ) in code blocks | I am following The Cherno C++ series and in this video he is talking about generating .i files. I am an Ubuntu [20.04] user and am making my projects on Code::Blocks. Does any one know how to generate .i files in Code::Blocks?
| actually you can't directly genrate a preprocessor file in Code::Blocks
as far as my knowledge go. Because I am also following the same series and I also had this problem { i am also using C::b }, so what you can do is in ubuntu terminal go to that file location by using cd command and then use
gcc -E FileName.c -o FileName.i
command this will genrate the preprocessor file.
|
72,159,100 | 72,164,050 | how is std::is_function implemented | Per CPP reference, std::is_function can be implemented as follows. Can someone explain why this works as it seemingly does not directly address callables?
template<class T>
struct is_function : std::integral_constant<
bool,
!std::is_const<const T>::value && !std::is_reference<T>::value
> {};
| It exploits this sentence from https://eel.is/c++draft/basic.type.qualifier#1
A function or reference type is always cv-unqualified.
So, given a type T, it tries to make a const T. If the result is not a const-qualified type, then T must be a function or reference type. Then it eliminates reference types, and done.
(not to be confused with member functions that have const in the end: that is, in standardese, "a function type with a cv-qualifier-seq", not the same as a "cv-qualified function type")
|
72,159,106 | 72,161,238 | Undo-Redo functionality using Command-Pattern in Qt for FitInView feature | I have QGraphicsView which contains some QGraphicsItem. This view has some feature like zoom-in, zoom-out, fitIn, Undo-Redo.
My fitIn feature is not working in Undo-Redo functionality.
( To implement Undo-Redo I have used Command-Pattern in Qt. )
myCommand.h
class myCommand: public QUndoCommand
{
public:
myCommand();
myCommand(QTransform t, int hr, int vr, QGraphicsView* v);
void undo();
void redo();
QTransform t;
int hScrollBar;
int vScrollBar;
QGraphicsView* mView;
};
myCommand.cpp
myCommand::myCommand(QTransform t, int hr, int vr, QGraphicsView *v)
{
this->t = t;
this->hScrollBar= hr;
this->vScrollBar= vr;
this->mView = v;
}
void myCommand::undo()
{
mView->setTransform(t);
mView->horizontalScrollBar()->setValue(hScrollBar);
mView->verticalScrollBar()->setValue(vScrollBar);
}
void myCommand::redo()
{
myView mv;
mv.FitInView();
}
myView.cpp
void myView::FitIn()
{
FitInView();
QTransform t = view->transform();
int hrValue = view->horizontalScrollBar()->value();
int vrValue = view->verticalScrollBar()->value();
myCommand* Command1 = new myCommand(t,hrValue,vrValue,view);
undoStack->push(Command1);
}
void myView::DrawDesign()
{
// Logic for inserting all the Rectangles and polylines.
QTimer::singleShot(100, this, [&]() {
FitInView();
});
}
void myView::FitInView()
{
QRectF bounds = scene->sceneRect();
QRectF rect {0,0,200,200};
if (bounds.width() < 200)
{
rect .setWidth(bounds.width());
bounds.setWidth(200);
}
if (bounds.height() < 200)
{
rect.setWidth(bounds.height());
bounds.setHeight(200);
}
view->fitInView(bounds, Qt::KeepAspectRatio);
view->updateGeometry();
}
myView.h
public:
QUndoStack* undoStack;
FitInView fits my design perfectly but it does not work in Undo-Redo feature.
I think I am making a mistake in myCommand::undo() and myCommand::redo() function.
| Based on the many question you posted on the Qt's Undo Framework, it seems to me you are missing an essential part of the Command pattern:
The Command pattern is based on the idea that all editing in an
application is done by creating instances of command objects. Command
objects apply changes to the document and are stored on a command
stack. Furthermore, each command knows how to undo its changes to bring the document back to its previous state. [1]
So all changes, should be implemented inside the QUndoCommand (follow the link to discover a basic usage example), i.e. inside QUndoCommand::redo. Once the command is pushed on the QUndoStack, using QUndoStack::push, the change (i.e. QCommand::redo) is automatically performed:
Pushes cmd on the stack or merges it with the most recently executed command. In either case, executes cmd by calling its redo() function. [4]
Steps to create a new QUndoCommand
Implement the desired changes inside QUndoCommand::redo (and not somewhere else).
Write the inverse of this command inside QUndoCommand::undo. If needed, capture the initial state inside the QUndoCommand constructor, to easily revert QUndoCommand::redo.
Applied to your example
So, the only action that myView::FitIn should perform, is pushing the command on the undo stack:
void myView::FitIn()
{
undoStack->push(new fitCommand(view));
}
Implement your changes inside the redo command:
void fitCommand::redo()
{
mView->FitInView(); // Can be implemented using QGraphicsView::fitInView
}
As the inverse operation of fitting is not uniquely defined, we store the initial state inside the QUndoCommand constructor (to be able to restore the initial state inside QUndoCommand::undo):
fitCommand::fitCommand(myView *view)
{
this->t = view->transform();
this->hScrollBar= view->horizontalScrollBar()->value();
this->vScrollBar= view->verticalScrollBar()->value();
this->mView = view;
}
Now we can implement the undo command to revert the redo command:
void fitCommand::undo()
{
mView->setTransform(t);
mView->horizontalScrollBar()->setValue(hScrollBar);
mView->verticalScrollBar()->setValue(vScrollBar);
}
Usefull reading material:
Overview of Qt's Undo Framework
Detailed description of QUndoCommand, including basic code example
|
72,159,168 | 72,161,798 | Pass and Return 'Reference to a Pointer' for Binary Search Tree Insertion in C++ | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
TreeNode*& node = find(root, val);
node = new TreeNode(val);
return root;
}
TreeNode*& find(TreeNode*& root, int& val) {
if (root == nullptr) return root;
else if (root->val > val) return find(root->left, val);
else return find(root->right, val);
}
};
I am learning C++ and read this code on a lecture slide. The code is about the insertion of a new node into a binary search tree. The idea is to find the target location and then insert a new node to the location. I can understand the reason for the 'find' function returning a 'reference to pointer' type. I think it is because we need to modify the address of the target location after the 'find' function returns. However, I don't know why we need to use the 'reference to pointer' type also when we pass the root node into the 'find' function. If I change TreeNode*& find(TreeNode*& root, int& val) to TreeNode*& find(TreeNode* root, int& val), the program will return the original tree without the target insertion. Can anyone help with this question? Thank you in advance!
| If you change find to TreeNode*& find(TreeNode* root, int& val) then look at the first line of the function:
if (root == nullptr) return root;
This would return a reference to a local variable. Changing it in insertIntoBST is undefined behavior and will not change the root variable inside insertIntoBST.
Go through the code step by step when inserting the first value into an empty tree:
NodeTree *tree = nullptr;
tree = insertIntoBST(tree, 42);
The insertIntoBST function could use the same trick as find and modify the root in place:
void insertIntoBST(TreeNode*& root, int val) {
TreeNode*& node = find(root, val);
node = new TreeNode(val);
}
NodeTree *tree = nullptr;
insertIntoBST(tree, 42);
insertIntoBST(tree, 23);
insertIntoBST(tree, 666);
or even shorter:
void insertIntoBST(TreeNode*& root, int val) {
find(root, val) = new TreeNode(val);
}
|
72,159,175 | 72,159,259 | Proper syntax for defining a unique_ptr array of class objects with a constructor | I want an array of class objects with unique_ptr:
std::unique_ptr<MyClass[]> arr(new MyClass[n]);
MyClass has no default constructor (and in my case is not supposed to have), so I have to put it explicitly here. I cannot find out how to do it so it is syntactically correct. What is the correct way to write a unique_ptr array of class objects with explicit initialisation?
Clarification
I have a non-default constuctor for MyClass, like this:
MyClass instance(arguments);
Apart from member initialisations, there are also some calculations in the constructor. I want to create a unique_ptr array of MyClass instances and call the constructor for each of the instances. I cannot do that later since MyClass has no default constructor. Can I put (arguments) somewhere in std::unique_ptr<MyClass[]> arr(new MyClass[n])?
| The answer below is based on a previous version of the question, in which the array size appeared to be a compile-time constant. If the size of the created array is not a compile-time constant, then it is impossible to pass arguments to the constructors of the elements. In that case std::vector is probably a better choice than array-std::unique_ptr.
It works the same as always for arrays, using aggregate initialization:
std::unique_ptr<MyClass[]> arr(new MyClass[]{
{...},
{...},
{...},
{...},
{...}});
where ... are replaced by the argument lists for the constructors of the five elements.
Or if you cannot use list-initialization for the elements, e.g. because that would unintentionally use a std::initializer_list constructor:
std::unique_ptr<MyClass[]> arr(new MyClass[]{
MyClass(...),
MyClass(...),
MyClass(...),
MyClass(...),
MyClass(...)});
std::make_unique would usually be preferred for creating std::unique_ptrs, but there is at the moment no overload which allows passing arguments to the constructors of the individual array elements.
If you want to pass the same argument list to each element, a simple solution given that the type is copy-constructible would be to declare one instance and then copy-construct the elements from this instance:
MyClass instance(arguments);
std::unique_ptr<MyClass[]> arr(new MyClass[]{instance, instance, instance, instance, instance);
Otherwise you could write a template function that expands these repeated items for you. (Might add example later.)
|
72,159,216 | 72,162,717 | Embed Python in C++ (using CMake) | I'm trying to run a python script in c++. For example:
// main.cpp
#include <python3.10/Python.h>
int main(int argc, char* argv[])
{
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print('Today is',ctime(time()))\n");
Py_Finalize();
return 0;
}
And I have such CMakeLists:
// CMakeLists.txt
cmake_minimum_required(VERSION 3.21)
project(task_01)
SET(CMAKE_CXX_FLAGS "-O0")
SET(CMAKE_C_FLAGS "-O0")
set(CMAKE_CXX_STANDARD 20)
find_package (Python COMPONENTS Interpreter Development)
find_package(PythonLibs 3.10 REQUIRED)
include_directories ( ${PYTHON_INCLUDE_DIRS} )
add_executable(task_01 main.cpp)
But I get compile errors (I use CLion IDE):
undefined reference to `Py_Initialize'
undefined reference to `PyRun_SimpleStringFlags'
undefined reference to `Py_Finalize'
What am I doing wrong to run a python script?
| Prefer imported targets (https://cmake.org/cmake/help/latest/module/FindPython.html#imported-targets):
cmake_minimum_required(VERSION 3.18)
project(task_01)
find_package(Python REQUIRED Development)
add_executable(task_01 main.cpp Utility.cpp Sort.cpp)
target_link_libraries(task_01 PRIVATE Python::Python)
|
72,159,583 | 72,159,652 | Iterate through vector<uchar> and count occurrence of values | How to iterate through a std::vector<uchar> and count the occurrence of each value?
I'm still fairly new to C++ and don't really know the best approaches
My guess would be to iterate through the vector and register each occurrence in a new multidimensional vector
std::vector<uchar<int>> unique;
for(const auto& sample : quantized){
// if unique[sample] does not exists create it and set the value to 1
// if unique[sample] is set increase it by +1
}
And how would the logic look like in the above code? (if this is the best approach?)
I need to find the value with most occurrencies
| We use an unordered_map as a counter by key.
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <unordered_map>
#include <vector>
int main(int argc, char const *argv[]) {
auto samples = // or from user input
std::vector<int>{1, 1, 1, 4, 5, 6, 7, 8, 9, 10,
4, 5, 6, 1, 1, 9, 10, 8, 9, 10};
if (samples.size() == 0) {
printf("No samples\n");
}
// counter, key is sample, value is count
std::unordered_map<int, int> counter;
// count samples
for (auto sample : samples) {
counter[sample]++;
}
// sort
std::vector<std::pair<int, int>> sorted_counter;
std::copy(counter.begin(), counter.end(), std::back_inserter(sorted_counter));
std::sort(sorted_counter.begin(), sorted_counter.end(),
[](const std::pair<int, int> &a, const std::pair<int, int> &b) {
// for asc, use a.second < b.second
return a.second > b.second;
});
// print result
for (auto &pair : sorted_counter) {
printf("%d: %d\n", pair.first, pair.second);
}
printf("max freq sample: %d, count: %d\n", sorted_counter[0].first,
sorted_counter[0].second);
printf("min freq sample: %d, count: %d\n",
sorted_counter[sorted_counter.size() - 1].first,
sorted_counter[sorted_counter.size() - 1].second);
return 0;
}
output:
1: 5
10: 3
9: 3
8: 2
6: 2
5: 2
4: 2
7: 1
max sample: 1, count: 5
min sample: 7, count: 1
The most freq item value is the first item of desc_keys.
|
72,159,909 | 72,160,084 | How to make python faster? | I'm working on a python project which is required to do a lot of tasks in the shortest amount of time.
Done some tests, and a print("Hello World!") takes about 0.7 seconds to run with python.
In c++, cout<<"Hello World!"; takes about 0.003 seconds, a huge difference compared to python.
What approach should I take to minimize python's run time? How should I compile the code?
| This doesn't really answer the question but shows (proves?) that there must be something wrong with OP's Python runtime setup / environment
import time
start = time.perf_counter()
print('Hello world!')
end = time.perf_counter()
print(f'Duration={end-start:6f}s')
Output:
Duration=0.000018s
|
72,160,076 | 72,160,258 | decouple member variables of a struct in variadic function accordingly | I have posted a question before, unpack variadic arguments and pass it's elements accordingly. However, it didn't quite address my problem as I am not asking it precisely. Hence I would like to rephrase and explain my problem in detail. Thanks in advance!
suppose I got a struct Outcome that take a two parameter function Outcome cal_out(int, int) to construct, and can recursively compute by Outcome cal_out(Outcome, int, int) with two additional parameters, i.e. x and y.
struct Outcome {
int valueX;
};
Outcome cal_out(int x,int y) {
int z = some_algo(x, y);
return Outcome{z};
}
Outcome cal_out(Outcome rhs, int x, int y){
int z = some_algo(rhs, x, y);
return Outcome {z};
}
template<class... Ts>
Outcome cal_out(Outcome rhs, int x, int y, Ts... ts){
return cal_out(cal_out(rhs, x, y), ts...);
}
And now my problem is that, I got a struct Coord like this.
template<int X, int Y>
struct Coord {
static const int valueX = X;
static const int valueY = Y;
};
I would like to ask how to call get_out_from_coords() to get the outcome i.e.
Outcome out = get_out_from_coords<Coord<1,2>, Coord<3,4>, Coord<5,6> >();
with my pseudo implementation that doesn't work
template<class COORD>
Outcome get_out_from_coords() {
return cal_out(COORD::valueX, COORD::valueY);
}
template<class COORD1, class COORD2>
Outcome get_out_from_coords() {
return cal_out(get_out_from_coords<COORD1>(), COORD2::valueX, COORD2::valueY);
}
template<class COORD1, class COORD2, class... COORDs>
Outcome get_out_from_coords() {
return cal_out( get_out_from_coords<COORD1, COORD2>(), COORDs::valueX, COORDs::valueY...);
//manipulating the pack expressions to get something like this
}
Noted: Outcome cannot calculate in this way Outcome cal_out(Outcome, Outcome)
So, something like fold expression wouldn't work in this case. i.e.
template<class... COORDs>
Outcome get_out_from_coords() {
return cal_out(cal_out(COORDs::valueX, COORDs::valueY)...);
}
| template<class... COORDs>
Outcome get_out_from_coords() {
return std::apply(
[](int x, int y, auto... args){ return cal_out(cal_out(x, y), args...); },
std::tuple_cat(std::make_tuple(COORDs::valueX, COORDs::valueY)...)
);
}
This just concatenates all of the valueX/valueY pairs and calls cal_out with these arguments. This assumes here that everything is by-value and that copying arguments is cheap. If these conditions are not satisfied std::forward_as_tuple and perfect-forwarding in the lambda should be used.
I also feel that cal_out is defined in a strange way. I think there should be a variadic overload not requiring a Outcome, which could then be called with
[](auto... args){ return cal_out(args...); }
as lambda instead. Otherwise you would need to add special cases if there is only one COORDs.
|
72,160,310 | 72,160,438 | How to generate an string iterating each character from array list c++ | i want to generate an string of 64 characters from my char list but after each string generated it will iterate the first digit of the string to the next one and so on, after that will check wish is the result of the sha256 function for each string, for example i have the following char list char hex_numbers[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a' ,'b','c','d','e','f'};
i want to generate and check the sha256 result of each string containing each character in the list -> [string of 64 digits] from "00000...." until "fffff...."
i already have the sha256 function implemented my question is only about how can i iterate for each digit in the string and go to the next digit after the one that was used, if it makes sense
so i was thinking about looping in each one and going to the next iteration but how can i achieve such a thing?
sorry if my question sounds confusing
for example the first string should be an 64 char strings all of zeros, the second one an '1' char + [63] '0' chars, the third one an '2' char + [63] '0' chars and so on until it reaches 'f[64 times]' by looping through all characters
| This problem is similar to finding the k-th number in X-ary
#include <algorithm>
#include <cstdio>
#include <iterator>
#include <unordered_map>
#include <vector>
int main(int argc, char const *argv[]) {
const char alphabet[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
auto generate_kth_string = [&alphabet](int len, size_t kth) {
char *buf = new char[len + 1];
int size = sizeof(alphabet) / sizeof(alphabet[0]);
for (int i = 0; i < len; i++) {
buf[len - i - 1] = alphabet[kth % size];
kth /= size;
}
buf[len] = '\0';
return buf;
};
int count = 256;
int len = 64;
for (int i = 0; i < count; i++) {
auto kth = generate_kth_string(len, i);
printf("%s\n", kth);
delete[] kth;
}
}
Output:
0000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000001
0000000000000000000000000000000000000000000000000000000000000002
0000000000000000000000000000000000000000000000000000000000000003
0000000000000000000000000000000000000000000000000000000000000004
0000000000000000000000000000000000000000000000000000000000000005
0000000000000000000000000000000000000000000000000000000000000006
0000000000000000000000000000000000000000000000000000000000000007
0000000000000000000000000000000000000000000000000000000000000008
...
00000000000000000000000000000000000000000000000000000000000000fb
00000000000000000000000000000000000000000000000000000000000000fc
00000000000000000000000000000000000000000000000000000000000000fd
00000000000000000000000000000000000000000000000000000000000000fe
00000000000000000000000000000000000000000000000000000000000000ff
For a 64 bit number, it takes 2 ^ 64 calculations, so you can't rely on this algorithm to crack any password in a limited time
|
72,160,446 | 72,160,620 | What is the signature of a function that returns another function of the same type? | With a something like this:
bool exit = false;
int main() {
auto & fun = init_function;
while(!exit) {
fun = fun();
}
}
I know I can make it work by casting void* into the right function pointer, but it would be better to know the actual function type.
I'm searching for the declaration syntax of init_function.
| There is no such signature. But the premise of such a state machine is not an impossible one, if we apply the fundamental theorem of software engineering: everything can be solved with a layer of indirection.
For instance, we can declare functions returning incomplete types. And so can declare a function type for a function returning an incomplete type. When we complete the type, we can have it store a pointer to a function... of the type we just declared.
struct Ret;
using FunType = auto() -> Ret;
struct Ret {
FunType *pFunc;
operator FunType* () { return pFunc; } // Allow implicit conversion back to a function pointer
};
And that's as little as you'd need, really.
Ret init_function() {
return {init_function}; // Infinite recursion, yay!
}
bool exit = false;
int main() {
auto *fun = init_function; // Pointer to a function
while(!exit) {
fun = fun(); // Call it, get a Ret object, implicitly convert it back to a pointer
}
}
|
72,160,663 | 72,161,488 | Minesweeper algorithm in C++[KOI 2020] | I'm preparing KOI 2022, so, I'm solving KOI 2021, 2020 problems. KOI 2020 contest 1 1st period problem 5(See problem 5 in here)
I want to make <vector<vector<int>> minesweeper(vector<vector<int>> &v) function that works on 5*5 minesweeper.
argument
vector<vector<int>> &v
Numbers in minesweeper that converted to vector. -1 if it is blank.
e.g. {{0, 0, 1, -1, 1}, {-1, 3, 3, -1, 1}, {-1, -1, -1, -1, 0}, {2, 5, -1, 3, -1}, {-1, -1, -1, -1, -1}}
return value
A vector. Size is same with argument. Mine is 1, default is 0.
English translation of KOI 2020 contest 1 1st period problem 5
There is a 5*5 minesweeper puzzle.
There are 11 numbers, and the others are blank.
0
0
1
가
1
나
3
3
1
다
0
2
5
3
라
마
Where is the mine?
A. 가
B. 나
C. 다
D. 라
E. 마
How can I make minesweeper function? I want algorithm description, too.
| There two some simple rules to solving Minesweeper:
If a field sees all it's mines then all blank fields don't have mines and can be uncovered.
If a field has as many blank fields as it is missing mines then they all contain mines.
Keep applying those rules over and over till nothing changes.
Now it gets complex because you have to look at combinations of fields. Instead of figuring out lots of special cases for 2, 3, 4 known fields I suggest going straight to a brute force algorithm:
For every blank field next to a know field:
create copies of the map with a mine present and not present
go back to the top to solve each map
if one of the maps results in any known field to not see enough mines then the other case must be the actual solution, apply it and go back to the start
If no progress was made then you have to guess. The above loop can give you probabilities for where mines are and if you know the number of mines total you have a probability for other blank fields. Pick one least likely to have a mine.
|
72,160,678 | 72,160,751 | How to pass member function as a parameter | I'm trying to create a dynamic spell system for a game I'm developing: spells should consist of an archetype, e.g. area of effect and an effect, e.g. heal.
I have following (simplified) code:
class SpellEffect {
public:
virtual void heal(int magnitude);
}
class SpellArchetype {
public:
virtual void applyToArea(int sizeOfArea, void (*func)(int));
}
class Spell {
SpellEffect effect;
SpellArchetype archetype;
int sizeOfArea;
int magnitude;
public:
void cast() {
archetype.applyToArea(sizeOfArea, &effect.heal);
}
}
However, since heal() is a member function this does not work.
I also have trouble passing the argument magnitude to the heal() function.
I found this question and the answer seems helpful. Yet it has been a while since I last used C++ and I can't figure out how to make it work in my case since the this is different.
Can someone please help me out?
| The correct syntax would be as shown below. Note that you can also use std::function.
class SpellEffect {
public:
virtual void heal(int magnitude);
};
class SpellArchetype {
public:
//-------------------------------------------vvvvvvvvvvvvvvvvvvvvvvvvvvvvvv---->func is a pointer to a member function of class SpellEffect that has one int parameter and return type of void
virtual void applyToArea(int sizeOfArea, void (SpellEffect::*func)(int));
};
class Spell {
SpellEffect effect;
SpellArchetype archetype;
int sizeOfArea;
int magnitude;
public:
void cast() {
//----------------------------------------vvvvvvvvvvvvvvvvvv---->correct syntax instead of &effect.heal
archetype.applyToArea(sizeOfArea, &SpellEffect::heal);
}
};
In the above code, instead of having void (*func)(int) we have:
void (SpellEffect::*func)(int)
which means that func is a pointer to a member function of class SpellEffect that takes one int parameter and has the return type of void.
|
72,160,747 | 72,161,017 | How to get the second last element of a list in C++ | i just started programing in C++, and have a little bit of experience in C, but in this program was trying to use the C++ libraries that i am not familiar to at all.
The objective of the program is simple, i have a linked list and i need to get the second to last element of the list. What i did was reversing the list, using the reverse function, and then i was trying to get the new second element of the list, using std::next, because this would be the element i wanted. But i am unable to then print object, since it either print the pointer value or when i deference it says that std:cout is not able to print it because it does not know how to convert the value. Any help would be appreciated. Thanks in advance.
#include <list>
#define LOG(x) std::cout << x << std::endl;
typedef std::list<int> list;
list *getNextXValue(list *Head, int x)
{
return std::next(Head, x);
}
/**
* @brief Find last element of a linked list of ints
*
* @return int Program ended correctly
*/
int main()
{
list listOne;
list *aux = NULL;
// Inserts all the elements in the list
for (int i = 0; i < 100; i++)
{
listOne.insert(listOne.end(), i);
}
listOne.reverse();
aux = getNextXValue(&listOne, 1);
LOG(*aux);
return 0;
}
|
i was trying to get the new second element of the list, using std::next.
You are not getting the new second element of the list, what you are trying to get is the next new address of the list, since what you are passing is the pointer, the address of the list, not the iterator:
list *getNextXValue(list *Head, int x)
{
return std::next(Head, x);
}
Try this instead:
#include <iostream>
#include <list>
#define LOG(x) std::cout << x << std::endl;
typedef std::list<int> list;
std::list<int>::iterator getNextXValue(std::list<int>::iterator Head, int x) {
return std::next(Head, x);
}
/**
* @brief Find last element of a linked list of ints
*
* @return int Program ended correctly
*/
int main() {
list listOne;
list *aux = NULL;
// Inserts all the elements in the list
for (int i = 0; i < 100; i++) {
listOne.insert(listOne.end(), i);
}
listOne.reverse();
auto next = getNextXValue(listOne.begin(), 1);
std::cout << *next << std::endl;
return 0;
}
|
72,160,831 | 72,161,270 | Convert size in bytes to unsigned integral type | I am developing a library that needs to auto deduce the type of size (in bytes).
How to convert size (in bytes) to unsigned integral type?
The type deduced must be big enough to store data in the size, but that does not mean to use uint64_t in every case.
C++20 or below can be used.
To be clearer, I want to deduce a type to store data of the size but without memory waste.
For example:
magic<1> -> uint8_t
magic<2> -> uint16_t
magic<3> -> uint32_t
magic<7> -> uint64_t
| Immediately invoked lambda might help. You can also use std::conditional_t.
template<std::size_t N>
using magic = decltype([] {
if constexpr (N <= 1)
return std::uint8_t{};
else if constexpr (N <= 2)
return std::uint16_t{};
else if constexpr (N <= 4)
return std::uint32_t{};
else {
static_assert(N <= 8);
return std::uint64_t{};
}
}());
|
72,160,937 | 72,161,276 | How can I place multiple QToolButton one after the other, instead of being one below the other | I am working on a QT project that makes it possible to view and edit table views from a given file.
For the buttons in the GUI I'm using QToolButton, but when more than one button is created, they are placed one below the other, whereas I would like them all to be shown one after the other on the same row. Here is the code for the two buttons:
QToolButton* newFileButton = new QToolButton(this);
newFileButton -> setIcon(QIcon(":/images/newFile.svg"));
newFileButton -> setIconSize(QSize(44, 44));
newFileButton -> setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
newFileButton -> setText("New File");
QToolButton* openFileButton = new QToolButton(this);
openFileButton -> setIcon(QIcon(":/images/openFile.svg"));
openFileButton -> setIconSize(QSize(44, 44));
openFileButton -> setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
openFileButton -> setText("Open");
This is what I get:
How can I place them one after the other?
Thanks
| Put them in a horizontal layout or a widget with horizontal layout. You can also use a grid layout for your window and make the table span all columns.
There is also the QButtonBox that has a number of default buttons with default icons that might mesh better with the users theme.
|
72,161,009 | 72,176,190 | spdlog: not configuring the logger correctly using same sink | The following code :
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_color_sinks.h"
int main() {
auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
auto a = std::make_shared<spdlog::logger>("a", stdout_sink);
auto b = std::make_shared<spdlog::logger>("b", stdout_sink);
a->set_pattern("%v");
b->set_pattern("debug %v");
a->info("a");
b->info("b");
}
outputs
debug a
debug b
rather than
a
debug b
It seems as though the spdlogger only remembers the last registered pattern. How do I achieve the intended as in having two loggers with different patterns
|
That would work yes. Problem is when you want to extend this to log files. Then, you end up having two log files
The answer is you can't, directly.
set_formatter is just a wrapper of set_formatter(pattern_formatter{}). In spdlog, a formatter is stored in a sink rather than a logger.
Just thought of a workaround if you really need this feature.
You can implement your own file_sink, and then you can have multiple formatters.
There is a field logger_name in struct log_msg, you can use it to determine which logger the message came from, and use a different formatter. Note that if you did not set a name for a logger, the field is an empty string.
|
72,161,048 | 72,167,870 | MFC Draw Stuff Outside OnPaint in a Dialog-based App | I'm currently trying to draw something outside OnPaint function. I know there are many duplicate questions on the internet, however, I failed to get any of them to work. This is entirely because of my lack of understanding of MFC.
What works inside OnPaint:
CDC* pDC = GetDC();
HDC hDC = pDC->GetSafeHdc();
CRect lDisplayRect;
GetDlgItem(IDC_DISPLAYPOS)->GetClientRect(&lDisplayRect);
GetDlgItem(IDC_DISPLAYPOS)->ClientToScreen(&lDisplayRect);
ScreenToClient(&lDisplayRect);
pDC->FillSolidRect(&lDisplayRect, GetSysColor(COLOR_3DDKSHADOW));
pDC->TextOutW(300, 300, TEXT("test"));
It fills the area of the button control I have with a defined colour.
And it prints out the "test" string without any issue.
But it won't work outside OnPaint.
I've seen numerous suggestions such as using CmemDC,CPaintDC, etc
But none of them worked outside OnPaint.
For example,
CClientDC dc(this);
dc.rectangle( ....);
does not work.
Please note that this is a temporary test code and what I am eventually trying to do is draw incoming frames from a frame grabber within my display thread (a separate thread from the main UI thread) on the DisplayPos area and my dlg object(the dialog) owns an instance of the DisplayThread class. And I'm passing HWND and displayrect upon creating the member mDisplayThread so I can draw stuff within the display thread and that's the reason why I need to be able to draw to DC outside OnPaint (DisplayThread class does not have OnPaint or inherit any class that has it).
I'm in dire need of help...Please help!
Added: I have overridden PreTranslateMessage(MSG* pMsg) and made it return without calling the default function just in case WM_ERASE msg is erasing everything, but this approach didn't work either.
| For example:
void CMFCApplicationDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
HDC hdc = ::GetDC(m_hWnd);
Ellipse(hdc, point.x - 10, point.y - 10, point.x + 10, point.y + 10);
::ReleaseDC(m_hWnd, hdc);
CDialogEx::OnLButtonDown(nFlags, point);
}
|
72,161,247 | 72,161,714 | shared memory c++ cross platform | I'm coding in C++ a program that works as a socket between other programs in different languages (C#, Python till now). This socket reads data from the USB-port, do some stuff and stream it to the other programs.
My Idea: each program asks over a port-massage to be part of the stream. As response this program gets a pointer to a shared memory.
Is this possible? shared memory over different programing-languages? and can I just pass the pointer to the shared memory to the other program? and is there a way to do it cross-platform (Unix and Windows)?
|
Is this possible? shared memory over different programing-languages?
Yes. Memory is memory, so a shared-memory region created by language A can be accessed by a program written in language B.
and can I just passe the pointer to the shared memory to the other program?
It's not quite that simple; the other program won't be able to access the shared-memory region until it has mapped that same region into its own virtual-address space, using shmat() or MapViewOfFile() or similar.
Note that the shared-memory region will likely be mapped to a different range of addresses in each process that is attached to it, so don't rely on the pointer to a piece of shared data in process A being the same as a pointer to that same data in process B.
and is there a way to do it cross-platform ?
It looks like boost has an API for shared memory, if you want to go that route. Alternatively, you could write your own shared-memory API, with different code inside the .cpp file for Windows and POSIX OS's, with appropriate #ifdefs. That's how I did it in my library, and it works okay.
|
72,161,324 | 72,161,370 | replacing new with smart pointers in this example | In the following I would like to replace usage of "new" with smart pointers. However, so far my attempts were not successfully. The commented lines are what I tried to change for smart pointers.
int main(){
int n, val;
cin>>n;
Person* per[n];
// shared_ptr<Person> per[n];
for(int i = 0;i < n;i++){
cin>>val;
if(val == 1){
per[i] = new Professor;//shared_ptr<Professor>();
}
else {
per[i] = new Student;//shared_ptr<Student>();
}
per[i]->getdata();
}
for(int i=0;i<n;i++)
per[i]->putdata();
return 0;
}
The remaining of the code where the classes are defined is as follows:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <memory>
using namespace std;
class Person {
public:
int age;
std::string name;
int cur_id_this;
virtual void getdata() {};
virtual void putdata() {};
~Person(){};
};
class Professor : public Person {
public:
int publications;
static int cur_id;
Professor(){
cout << "init prof " << cur_id << endl;
cur_id += 1;
};
void getdata(){
cin >> name >> age >> publications;
cur_id += 1;
cur_id_this = cur_id;
}
void putdata(){
printf("%s %i %i %i\n", name.c_str(), age, publications, cur_id_this);
}
};
class Student : public Person {
public:
std::vector<int> marks;
static int cur_id;
int cur_id_this;
int marks_sum;
void getdata(){
cin >> name >> age;// >> publications;
int grade;
for (auto i=0; i<6; ++i){
cin >> grade;
marks_sum += grade;
}
std::cout << "---" << marks_sum<< endl;
cur_id += 1;
cur_id_this = cur_id;
}
void putdata(){
printf("%s %i %i %i\n", name.c_str(), age, marks_sum, cur_id_this);
}
};
int Professor::cur_id = 0;
int Student::cur_id = 0;
and the input the above code gets in command line is:
4
1
Walter 56 99
2
Jesse 18 50 48 97 76 34 98
2
Pinkman 22 10 12 0 18 45 50
1
White 58 87
| You're not allocating the actual object, so use std::make_shared :
per[i] = std::make_shared<Student>();
Although make_shared is preferred, you can write:
per[i] = shared_ptr<Professor>(new Professor);
|
72,161,498 | 72,170,323 | time complexity of (A[i]^x)>(A[i]&x) | 'Is it possible to further optimize the time complexity this piece of calculation "(y^x)>(y&x)" in c++?(you are allowed to change the Boolean operation into other forms, for example this can also be written as log2(y)!=log2(x) and this gives the same Boolean output but this has a higher time complexity with c++ compiler)'enter code here
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
int t;cin>>t;
while(t--){
int n;cin>>n;int A[n];
for(int i=0;i<n;i++){cin>>A[i];}
int q;cin>>q;
while(q--){
int l,r,x;
cin>>l>>r>>x;int count=0;
for(int i=l-1;i<r;i++){
if((A[i]^x)>(A[i]&x)){count++;}
}
cout<<count<<endl;
}
}
return 0;
}
'This is the code im trying to optimize.... Please help in any way possible (number of inputs cant be changed)'
| (y^x)>(y&x) is equivalent to nlz(y) != nlz(x) where nlz is a function that returns the number of leading zeroes of its input.
Therefore in order to count how often (A[i]^x)>(A[i]&x) is true for items in the array A, we could make a small array N where N[j] is the number of elements with nlz(A[i]) == j in array A. Then the number of times that (A[i]^x)>(A[i]&x) is true is equivalent to n - N[nlz(x)].
That way there is no loop over A where it really matters. Creating the array N still requires a loop over A, but only once for each iteration of the outer loop, not for each individual x.
C++20 has the nlz function built in under the name std::countl_zero.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.