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 |
|---|---|---|---|---|
69,954,799 | 69,954,809 | c++ using bool in a class with set and get functions | I am trying to create a class with private attributes and change values with set and get functions. However i cant seem to change the bool value
class VideoGames {
private:
bool buy;
public:
bool get_buy(){return buy;}
void set_buy(bool b){b = buy;}
};
main(){
VideoGames g1;
double price;
cin >> price;
if(price <=100){
g1.set_buy(true);
}
else {
g1.set_buy(false);
}
cout<<"Buy= " << g1.get_buy()<<endl;
return 0;
}
this always prints out 0 no matter what the price is. What do i need to change?
| You flip-flopped the assignment; b = buy; reassigns the parameter (which is then thrown away so nothing changes), you wanted buy = b; to reassign the attribute from the parameter.
|
69,955,255 | 69,956,305 | How to determine two implicit conversion sequences preferred than each other for overload resolution? | I want to question about overload resolution accompanying an implicit type conversion. This question refers cppreference 1 and 2.
It seems that an implicit conversion sequence has at most three steps to convert an type T1(argument type) to T2(parameter type):
zero or one standard conversion sequence;
zero or one user-defined conversion; ( I want to ignore this step because it isn't related to this question.)
zero or one standard conversion sequence.
An implicit conversion sequence can be categorized as one of:
a standard conversion sequence (I am interested this fundamental type conversions case only.)
a user-defined conversion sequence
an ellipsis conversion sequence
And, each type of standard conversion sequence is assigned one of three ranks:
Exact match : no conversion required, lvalue-to-rvalue conversion, qualification conversion, function pointer conversion, user-defined conversion of class type to the same class
Promotion : integral promotion, floating-point promotion
Conversion : integral conversion, floating-point conversion, floating-integral conversion, pointer conversion, pointer-to-member conversion, boolean conversion, user-defined conversion of a derived class to its base
And,
The rank of the standard conversion sequence is the worst of the ranks of the standard conversions it holds.
I think there will be a case where two implicit conversion sequences have its constituent standard conversion sequence steps which have different ranks each other. So, IMHO it is hard for me to determine which implicit conversion sequence is preferred than the other.
For example(Unfortunately, i couldn't come up with a concrete example.),
An implicit conversion sequence (A) consists of
standard conversion sequence (A-1) which is rank promotion.
no user-defined conversion sequence
standard conversion sequence (A-2) which is rank conversion.
The other implicit conversion sequence (B) consists of
standard conversion sequence (B-1) which is rank conversion.
no user-defined conversion sequence
standard conversion sequence (B-2) which is rank promotion.
In this case, A-1 is preferred than B-1 but B-2 is preferred than A-2. So, each of A and B have own preferences. -> ambiguous call?
OR... A-1 and B-1 should be compared first than A-2 and B-2. So, should we stop comparing each other here for greedy comparison? -> The A is chosen?
UPDATE: To explain my understanding about these concept...
// [ what is overall rank for standard coversion sequence n ]
// [ standard conversion sequence n(up to 2) ]
// [ each conversion's rank in a std conv sequence n ]
// [ what conversions are performed in a std conv sequence n ]
// [ how source type T1 is converted to target type T2 ]
// [ promotion ][ exact match ]
// [ std conv seq1 ][ std conv seq2 ]
// [ promotion | exact match ][ exact match ]
// [ promotion | const qualification ][ no conversion ]
// [char -> int -> const int -> const int ]
void f(const int){
std::cout << "f(const int)" << std::endl;
}
// [ promotion ][ conversion ]
// [ std conv seq1 ][ std conv seq2 ]
// [ promotion || conversion | exact match ]
// [ promotion || integral conversion, const qualification ]
// [char -> int -> long -> const long ]
void f(const long){
std::cout << "f(const long)" << std::endl;
}
int main() {
// For the first sequence, the two functions have same 2nd rank, 'promotion'.
// So, we couldn't determine which function will be called yet.
// But, for the second sequence, the former has 1st rank 'exact match'
// and the latter has 3rd rank 'conversion'. So the former will be called.
f('c'); // prints "f(const int)"
}
| Cppreference is a useful reference site, but it is not the C++ standard. It has mostly accurate information, but in boiling down the complexities of the standard, some details can be lost around the margins.
I will be citing C++17 (since I don't have a C++11 website I can link to), but the wording has not meaningfully changed.
[over.best.ics]/3 defines an implicit conversion sequence as:
A well-formed implicit conversion sequence is one of the following forms:
a standard conversion sequence,
a user-defined conversion sequence, or
an ellipsis conversion sequence.
This is more-or-less what Cppreference says, but here it is made more explicit that you either have precisely one standard conversion sequence or you have precisely one user-defined conversion. The user-defined conversion itself includes two standard conversion sequences:
A user-defined conversion sequence consists of an initial standard conversion sequence followed by a user-defined conversion ([class.conv]) followed by a second standard conversion sequence.
Cppreference makes it seem like you can have two standard conversion sequences without a user-defined conversion, but you cannot. If there is no user-defined conversion in play, you have only one standard conversion.
Don't try to read Cppreference as the legal definition of C++. Think of it more as "C++ works mostly like this". If you need legalistic detail (and in most cases, you don't. Especially around overload resolution. Knowing too much about this can make you a bad programmer), then you have to go to the standard.
|
69,955,563 | 69,955,667 | How does this binary search works? | I saw this method in a book, to do binary search, but I can't understand how it is working no matter how I try. Can someone explain to me exactly how it is working?
the book's explanation did not help :
The idea is to make jumps and slow the speed when we get closer to the
target element.
The variables k and b contain the position in the array and the jump
length. If the array contains the element x , the position of x will
be in the variable k after the search. The time complexity of the
algorithm is O (log n ), because the code in the while loop is
performed at most twice for each jump length.
what I don't get is that how is k iterating in the array? How can we make sure that it will not jump over the target's index? I tried tracing some runs of this program with sample values but couldn't figure out the pattern that k is following to find whether target x exists in the array or not.
int k = 1;
for (int b = n/2; b >= 1; b /= 2) {
while (k+b <= n && t[k+b] <= x) k += b;
}
if (t[k] == x) {} // x was found at index k
note: I do understand clearly the "common binary search algorithm" (the one that uses start, middle, and end indices )
| b are the length of the jumps of your current position. As you can see, b starts as n/2 and is divided by 2 at each step up until it reaches 1.
Now, For each b, remember that b is divided by 2 at each step in the for loop, we run a while loop where we add b to to our current position, which is k. We add b to k checking for 2 conditions: k+b is less than n (to make sure we don't go out of bounds), and t[k+b] is less than x, which we are searching.
This effectively means that for each b, we add b to k up until where it would go over the value we are seeking. At this point, the while loop breaks and we divide b to approach slower to the target hoping we don't go over it.
The final b is just one, to make sure we don't miss x if it is just the next element after the position of k.
Look at it this way, a car is racing towards a goal. At first the car is going maximum speed, as it nears the target, it gradually decelerates up until it reaches the target.
The difference with traditional binary search, which makes it a little counter intuitive, is that in traditional binary search, we go over the target and then come back and go over again and in each iteration we decrease the steps that we take back and forth. In this algorithm, we only go forwards (never over the target), but we continuously decrease the length of the steps by dividing b.
|
69,955,890 | 69,965,920 | How to make NSOpenPanel accept keyboard and mouse events in objective-c? | I have C++ console application getting written in XCode, and I need to open a file selector dialog. To do this I'm using Cocoa with objective-c. I'm trying to open an NSOpenPanel to use it for this purpose. I'm using the following code currently:
const char* openDialog()
{
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setFloatingPanel:YES];
if ( [openDlg runModal] == NSOKButton )
{
for( NSURL* URL in [openDlg URLs] )
{
NSLog( @"%@", [URL path] );
return [URL.path UTF8String];
}
}
return NULL;
}
This works, however the created file selector doesnt accept mouse and keyboard events properly. It's hard to explain, but for example when I run the code from XCode when hovering above the window the mouse still behaves as if were in XCode, showing the caret symbol. When i run the application from the terminal whenever I type something it sends the input to the terminal, even though the file selector is "in front". Command clicking gives the mouse events properly to the file selector though.
I looked through NSOpenPanel's documentation and googled the problem extensively but I couldn't find an answer to this.
| /*
To run in Terminal: clang openpanel.m -fobjc-arc -framework Cocoa -o openpanel && ./openpanel
*/
#import <Cocoa/Cocoa.h>
int main() {
NSApplication *application = [NSApplication sharedApplication];
[application setActivationPolicy:NSApplicationActivationPolicyAccessory];
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setFloatingPanel:YES];
if ( [openDlg runModal] == NSModalResponseOK ) {
for( NSURL* URL in [openDlg URLs] ) {
NSLog( @"%@", [URL path] );
}
}
return 0;
}
Thanks to @Willeke.
|
69,955,893 | 69,984,038 | Boost polygon union result is differing between windows and linux | I am trying to get a union of all the individual polygons via boost geometry. But oddly the results seem to vary between windows and centOS.
The result is coming out right one (the one i expect) in windows BUT in linux its odd. In linux it shows result as two split polygons.
In Windows i get
MULTIPOLYGON(((0 -0,0 2996,1490 2996,2980 2996,2980 -0,0 -0)))
But in centOS same set of inputs, give result as
MULTIPOLYGON(((1490 2996,2980 2996,2980 -0,1490 -0,1490 2996)),((0 2996,1490 2996,1490 -0,0 -0,0 2996)))
Its baffling for me as the code trying to compute polygons union is same. I don't understand why the linux output is coming out with a split line in between polygons. That's not how a union output should look like.
Can anyone point out what is that i am doing wrong in below code? Or any other pointers which i could try to see whats going wrong.
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometries/multi_polygon.hpp>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <vector>
#include <boost/geometry.hpp>
#include <boost/geometry/io/wkt/wkt.hpp>
namespace boost {
namespace geometry {
typedef model::d2::point_xy<double> Point;
typedef model::polygon<Point> Polygon;
typedef model::segment<Point> Line;
};
};
int main()
{
using multi_polygon = boost::geometry::model::multi_polygon<boost::geometry::Polygon>;
boost::geometry::Polygon one, two,green;
boost::geometry::read_wkt("POLYGON((0 2996, 1490 2996, 1490 -0, 0 -0, 0 2996))", one);
boost::geometry::read_wkt("POLYGON((1490 2996, 2980 2996, 2980 -0, 1490 -0, 1490 2996))", two);
multi_polygon polyUnion;
std::vector<boost::geometry::Polygon> vectorOfPolygons;
vectorOfPolygons.emplace_back(one);
vectorOfPolygons.emplace_back(two);
// Create the union of all the polygons of the datasets
for (const boost::geometry::Polygon& p : vectorOfPolygons) {
multi_polygon tmp;
boost::geometry::union_(polyUnion, p, tmp);
polyUnion = tmp;
boost::geometry::clear(tmp);
}
std::string str;
bool valid = boost::geometry::is_valid(polyUnion, str);
if (!valid)
{
boost::geometry::correct(polyUnion);
}
std::cout << "Result of union" << boost::geometry::wkt(polyUnion) << "\n";
}
| The flag BOOST_GEOMETRY_NO_ROBUSTNESS made the boost API behave differently for same set of inputs in linux. Turning OFF this flag made the output to become same in windows and linux.
|
69,955,915 | 69,955,968 | Template argument deduction in case of designated initializers in C++ | In the following code there is an initialization of A<T> objects with template argument deduction using designated initializers in two slightly distinct forms:
template<typename T>
struct A { T t; };
int main() {
A a{.t=1}; //#1: ok in GCC and MSVC
A b{.t={1}}; //#2: ok in MSVC only
}
The first way is accepted by both GCC and MSVC, while the second one is ok for MSVC only while GCC prints errors:
error: class template argument deduction failed:
error: no matching function for call to 'A(<brace-enclosed initializer list>)'
Demo: https://gcc.godbolt.org/z/PaEaMjM7q
Which compiler is right there?
| GCC is correct. Braced-init-list like {1} has no type, so it makes template argument deduction fail.
Non-deduced contexts
...
The parameter P, whose A is a braced-init-list, but P is not std::initializer_list, a reference to one (possibly cv-qualified), or (since C++17) a reference to an array:
|
69,955,934 | 69,973,534 | CMake build git submodules and its dependencies | I am a novice in CMake,
I would like to use a C++ library A in my CMake project.
This library A is included as a git submodule and I include it in my CMakeFile using
add_subdirectory("extern/A")
which works so far.
However, my library A has two other dependencies B and C. They are included in the CMakeFile of library A using find_package().
Now, I would like CMake to build these dependencies B and C, so that library A can use them. I want to include B and C as git submodules as well.
Simply concatenating
add_subdirectory("extern/B")
add_subdirectory("extern/C")
add_subdirectory("extern/A")
obviously doesn't work. I thought using add_dependencies could help here, but I couldn't find a way to make it work yet...
Is it even possible to do what I want to do here? If yes, could someone give me a hint which commands I might have to use?
| Your mistake adding B as a dependency to RootProject where A needs it.
Solution
In the following directory structure:
RootProject
|__ .git
|__ CMakeLists.txt
|__ src
| |__ main.c
| |__ ...
|
|__ vendor
|__ A
|__ .git
|__ CMakeLists.txt
|__ src
|__ ...
RootProject depends on A.
A is a library that has no dependencies.
If you want to add B as a dependency to A, you would treat A as completely separate project from RootProject and add B directly to A.
The directory structure of A becomes:
A
|__ .git
|__ CMakeLists.txt
|__ src
| |__ ...
|
|__ vendor
|__ B
|__ .git
|__ CMakeLists.txt
|__ src
|__ ...
Using git submodules to "manage" the dependencies:
# Adding `B` as a dependency to `A`
cd vendor/A
mkdir -p vendor
cd vendor
git submodule add https://github.com/username/B.git
This will add B as a dependency to A, and not to RootProject.
Now simply add the following to vendor/A/CMakeLists.txt:
add_subdirectory("vendor/B")
# ......
target_link_libraries(A PUBLIC B)
Also note that each of A, B and RootProject must have a top level CMakeLists.txt in order for add_subdirectory to work.
See also:
add_subdirectory
find_package
Git submodules
|
69,956,080 | 69,956,754 | No type named 'type' in 'struct std::common_reference<Ref&&, const Val&>' | I'm trying to write a proxy iterator using Boost.STLInterfaces.
It fails to compile because the lvalue reference of the value and the rvalue reference of the reference are different, see a simplified version on Compiler Explorer https://godbolt.org/z/aE3bq7en4.
How do I make two types have common reference?
I tried overloading the addressof operator to return the reference type, but compiling a distilled example
#include <type_traits>
class Ref {};
class Val {};
// overload addressof operator
constexpr Ref operator&(Val) noexcept;
constexpr Ref operator&(Ref) noexcept;
int main()
{
std::common_reference<Ref&&, const Val&>::type t;
return 0;
}
fails with
error: no type named 'type' in 'std::common_reference<Ref &&, const Val &>'
| In this case, you need to partial specialize std::basic_common_reference to define the common reference of the two, similar to this:
template<template<class> class TQual, template<class> class UQual>
struct std::basic_common_reference<Ref, Val, TQual, UQual> {
using type = Val;
};
template<template<class> class TQual, template<class> class UQual>
struct std::basic_common_reference<Val, Ref, TQual, UQual> {
using type = Val;
};
Demo.
Some issues worth noting:
Val's member functions need to be public.
Val's constructor should not be explicit to satisfy indirectly_readable.
Val's operator=(Ref ref) needs to return Val& to meet sortable.
Ref needs to add operator=(Val) const overload to satisfy indirectly_writable.
|
69,956,284 | 69,964,339 | "opencv_world454.dll was not found" | hello I had imported OpenCV into my C++ project but for some reason my code gives me this error.
CODE:
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
int main()
{
std::string path = "Resources/test.png";
cv::Mat img = cv::imread(path);
imshow("Image", img);
cv::waitKey(0);
return 0;
}
error:
I think it might be because of my paths but I'm not sure I think I got them right.
enter image description here
Edit: I reinstalled the setup and installed openCV in a new path and now I do have .dll files but it keeps giving me an error here are new screenshots
enter image description here
| The solution was to install a new setup and install OpenCV into another path thank you to everyone who helped.
|
69,957,483 | 70,141,928 | How can I write a shortcut to compile and run a program in a separate terminal window in Vim? | I have this as a Sublime Text build system right now: It compiles a C++ program, then opens a new window in Terminal.app and runs it there upon pressing ctrl+b.
{
"shell_cmd": "g++-11 -std=c++20 '${file}' -o '${file_base_name}' && echo 'cd \"${file_path}/\"' > '/tmp/${file_base_name}' && echo './\"${file_base_name}\"' >> '/tmp/${file_base_name}' && echo read >> '/tmp/${file_base_name}' && chmod +x '/tmp/${file_base_name}' && open -a Terminal.app '/tmp/${file_base_name}'"
}
However, I'm not sure how I could get something in (Mac)Vim. I've read some similar questions, but none of the ones I've seen mention opening in a separate terminal.
I've tried writing some shortcuts/commands to compile and run within Vim which mostly worked, but I would still rather my programs run in a separate window (edited).
noremap <C-b> :!g++-11 %:p && ./a.out<CR>
| You actually have a few options, so use whatever suits your needs the most.
You can use vim's built in terminal :terminal (or :term; see :help :terminal), which is probably the easier way:
:term g++-11 %:p && ./a.out<CR>
Or you can use :compiler with :make (see :help :compile and :help 'makeprg'):
:compiler gcc
:let $CXXFLAGS='-std=c++20 -Wall -Werror'
:make
|
69,957,534 | 69,958,492 | Is it possible to use Makefile "define" to define a target plus its recipes? | I have a C/C++ project that contains different directories, each containing a set of objects executables to build from C/C++ source code.
To enable automatic dependency tracking (generating .d dependency files whenever my #include header files change), I have defined the following variables in a common Makefile:
# automatic prerequisite generation
# source: http://web.archive.org/web/20210820223028/http://make.mad-scientist.net/papers/advanced-auto-dependency-generation/
DEPFLAGS = -MT "$@" -MMD -MP -MF "$(@:.o=.d)"
CC_WRITE_DEP = $(CC) $(CFLAGS) -c "$<" -o "$@" $(DEPFLAGS)
CXX_WRITE_DEP = $(CXX) $(CXXFLAGS) -c "$<" -o "$@" $(DEPFLAGS)
So that when I write directory-specific Makefiles I can write:
# common compile options
common := common/Makefile
-include $(common)
# automatic dependency tracking
deps = $(objs:.o=.d)
-include $(deps)
# compile all .cpp source code files into .o object files
%.o: %.cpp
$(CXX_WRITE_DEP)
# compile all .c source code files into .o object files
%.o: %.c
$(CC_WRITE_DEP)
Where objs refers to the object files needed to build each executable.
But I found that the block of lines I have presented above must be repeated for every Makefile that I use to build executables in each directory, which could be a hassle if there are many of them.
I then have tried to write this in the common Makefile:
define CC_OBJ_COMPILE =
%.o: %.c
$(CC_WRITE_DEP)
endef
define CXX_OBJ_COMPILE =
%.o: %.cpp
$(CXX_WRITE_DEP)
endef
and to include them in building executables:
common := common/Makefile
-include $(common)
$(CC_OBJ_COMPILE)
$(CXX_OBJ_COMPILE)
But this does not work. When I ran make -p --dry-run in one directory for executables to see how those variables expanded, I saw these lines:
# ...
# makefile (from 'common/Makefile', line 16)
define CC_OBJ_COMPILE
%.o: %.c
$(CC_WRITE_DEP)
endef
# ...
# makefile (from 'common/Makefile', line 21)
define CXX_OBJ_COMPILE
%.o: %.cpp
$(CXX_WRITE_DEP)
endef
# ...
This means that the text variables are properly included into my executable-specific Makefiles.
However the implicit rules are expanded as:
# Implicit Rules
%.o: %.c
cc -Wall -Werror -c "" -o "" -MT "" -MMD -MP -MF ""
%.o: %.cpp
g++ -Wall -Werror -c "" -o "" -MT "" -MMD -MP -MF ""
Which means that they fail to include the automatic $< and $@ variables for targets.
So is it possible to create reusable rules that can be defined as variables and -included in other Makefiles using variable references? Did I miss something here?
| Make is an old grandpa - it is 45 years old. Consider moving to something newer - CMake, Scons, Meson, etc. Such tools will take care of dependencies automatically, will be portable, will come with a lot more features and will save you from endless (and pointless) hours of reinventing the wheel.
Is it possible to use Makefile "define" to define a target plus its recipes?
You have to eval the call.
define CXX_OBJ_COMPILE =
%.o: %.cpp
$(CXX_WRITE_DEP)
endef
$(eval $(CXX_OBJ_COMPILE))
Which means that they fail to include the automatic $< and $@ variables for targets.
Sure it does - $@ is like "expanded first", they need to be left for expansion.
CC_WRITE_DEP = $(CC) $(CFLAGS) -c "$$<" -o "$$@" $(DEPFLAGS)
|
69,957,677 | 69,957,710 | c++ Call subclass method in vector of base class type | I have the abstract class Currency and several subclasses like FiatMoney or Crypto. I want to store all of objects of subclasses in one vector and in the same time have access to methods, which are only in those subclasses.
My Currency.h file looks like this:
class Currency
{
public:
virtual void to_String() = 0;
float GetAmount();
string GetShortname();
void AddAmount(float);
void RemoveAmount(float);
virtual void UpdateRatio() =0;
virtual float trade(bool, float, float, float, string) = 0;
protected:
string *name, *shortname;
float *amount, *exchange_ratio;
};
and my FiatMoney.h file:
class FiatMoney : public Currency
{
public:
FiatMoney(string, string, float, float);
~FiatMoney();
void to_String();
void UpdateRatio();
float trade(bool, float, float, float, string);
void com();
private:
};
In that class I want to have additional method of this class called com(). Finally my main function looks like this:
vector<Currency*> Wallet;
Wallet.push_back(new FiatMoney("name", "shortname", 1.0, 1.0));
Wallet[0]->com();
At this point I of course have an error, that class Currency has not member call com(). How can I avoid this?
How can I get access to the function com() which is only in object of subclass FiatMoney?
Can I have method in class FiatMoney without previously declarate it as virtual function of Currency class?
Is this proper way of storing objects of different subclasses?
|
How can I get access to the function com() which is only in object of subclass FiatMoney?
You would have to type-cast a Currency* pointer into a FiatMoney* pointer, but you can only do that when the pointer is actually pointing at a valid FiatMoney object.
When you know the Currency* pointer is pointing at a FiatMoney object, you can use static_cast at compile-time, eg:
static_cast<FiatMoney*>(Wallet[0])->com();
Otherwise, use dynamic_cast at runtime to test the type of object being pointed at:
FiatMoney *fm = dynamic_cast<FiatMoney*>(Wallet[0]);
if (fm) fm->com();
Can I have method in class FiatMoney without previously declarate it as virtual function of Currency class?
Technically yes, though some people would argue that is not a good design choice when dealing with polymorphic classes.
Is this proper way of storing objects of different subclasses?
Technically yes, although Currency should have a virtual destructor. You have to delete the objects you new, and a virtual destructor will allow you to call delete on a Currency* pointer to invoke derived class destructors without type-casting the pointer. And as such, you should consider storing smart pointers, like std::unique_ptr, instead of raw pointers, so that delete is called automatically for you.
|
69,957,881 | 70,008,122 | How I can paint a text background with spdlog? | I did a test with the {fmt} and was super easy to change background color, but I can't get the same with spdlog.
I can get the same result with spdlog, but is a weird code
fmt::print( bg( fmt::terminal_color::yellow ) | fg( fmt::terminal_color::black ), " {1:<{0}}\n", 120, "message" );
spdlog::set_pattern( "%v" );
spdlog::info( "\033[43m\033[30m {1:<{0}} \033[m", 120, "message" );
| If I understand your question correctly, you want to format your spdlog output using fmt, rather than having to specify the escape sequences yourself. For this, you can use the fmt::format function and use its output as a variable for spdlog:
#include <spdlog/spdlog.h>
#include <spdlog/fmt/bundled/color.h>
int main(){
spdlog::info( "Printing a string formatted with fmt: {}",
fmt::format(
fmt::bg( fmt::terminal_color::yellow ) |
fmt::fg( fmt::terminal_color::black ) |
fmt::emphasis::bold,
"message"
)
);
return 0;
}
|
69,958,282 | 69,958,423 | How do I store a list in a dictionary when it is being created then cleared and then used for the next key with different values? | What I really want is to have the values to each key be an arbitrary list that is accessible for later use. The code given is just a sample of what is being attempted.
#include <string>
#include <list>
#include <map>
int main(){
std::map<std::string, std::list<std::string>> myMap;
std::list<std::string> myList;
int j = 0;
while(j<4){
for(int = 0; i < 6; i++){
myList.push_back("value");
}
myMap.insert(std::pair<std::string, std::list<std::string>("Key", myList));
myList.clear();
j++;
}
return 0;
}
| If you just want to reuse myList: 1) move the list declaration inside the while loop, so that a new empty list is created in every iteration, and then 2) use the map subscript operator with an rvalue reference so that the list is moved into the map.
#include <iostream> // cout
#include <string>
#include <list>
#include <map>
int main() {
std::map<std::string, std::list<std::string>> myMap{};
int j = 0;
while (j < 4) {
std::list<std::string> myList{};
for(int i = 0; i < 6; i++) {
myList.push_back(std::string{"value"} + std::to_string(j) + std::to_string(i));
}
myMap[std::string{"Key"} + std::to_string(j)] = std::move(myList);
j++;
}
for (auto&& [key, list_value] : myMap)
{
std::cout << key << ": ";
for (auto&& str : list_value)
{
std::cout << str << " ";
}
std::cout << "\n";
}
return 0;
}
Demo
|
69,958,593 | 69,958,676 | Passing a pointer to an int array to a member function, error: invalid types 'int[int]' for array subscript | Ok, I'm fairly new to programming, and c++ so please take it easy on me. I am trying to write a program that takes in the dimensions of a metal plate for a 2-D finite element method analysis (thickness neglected). So, I created a class for my part (the plate), the elements for the mesh, and the nodes for the elements. The mesh will consist of square elements and will be applied over the front face of the plate. Right now, I'm working on getting the mesh sorted out before I move on to the element and node classes.
I'm using (or wanting to use) dynamic allocation to create a 2-D array (my mesh) containing the elements of the mesh. I'm trying to write a function, "meshingPart", to create the 2-D array with the number of rows being the height of the plate, and the columns being the length of the plate.
When I run the program, I get these errors and I'm not sure how to fix them:
In member function 'void PartClass::meshingPart(int&, int, int)':
error: invalid types 'int[int]' for array subscript
At global scope:
error: expected constructor, destructor, or type conversion before '(' token
Also, when I use my printPart() function, will it print the pointer's address, or the values of the array? I'm not completely sure about this, I'm also new to pointers.
Any help would be much appreciated! Thanks in advance.
class PartClass
{
private:
const int HEIGHT; // mm
const int LENGTH; // mm
const int WIDTH; // mm
const int SEED; // mm
const int MESHROW;
const int MESHCOL;
int *partMesh; // Mesh array - an int pointer
// Creates the mesh for the part by generating elements to fill the width and length
// of the part. The elements are stored in a 2-D array.
void meshingPart(const int &partMesh, int inRow, int inCol);
public:
// Constructs a part with the given parameters, seeds the part for the mesh,
// then creates the mesh by generating square elements with length = height = SEED.
PartClass(int inHeight, int inLength, int inWidth, int inSeed);
void printPart()
{
cout << "Part mesh:" << *partMesh << endl;
}
};
class ElementClass
{
private:
int elemID;
static int numElems;
// Shape functions:
int N1;
int N2;
int N3;
int N4;
public:
// Default constructor
ElementClass()
{
elemID = numElems;
numElems++;
};
};
PartClass :: PartClass(inHeight, inLength, inWidth, inSeed)
{
HEIGHT = inHeight;
LENGTH = inLength;
WIDTH = inWidth;
SEED = inSeed;
MESHROW = HEIGHT/SEED;
MESHCOL = LENGTH/SEED;
// Dynamically declares an array, gets memory, assigns address to partMesh.
partMesh = new int[MESHROW][MESHCOL];
meshingPart(&partMesh, MESHROW, MESHCOL);
}
void PartClass :: meshingPart(int &partMesh, int inRow, int inCol)
{
for( int i; i < inRow; i++)
{
for( int j; j < inCol; j++)
{
partMesh[i][j] = ElementClass();
}
}
}
| There are multiple problems with the shown code, not a single problem. All of the problems must be fixed in order to resolve all compilation errors.
void PartClass :: meshingPart(int &partMesh, int inRow, int inCol)
The first parameter to this class method is declared as a reference to a single, lonely int. It is not an array, hence the code in this class method that treats it as an array will make your C++ compiler very, very sad.
int *partMesh; //
partMesh = new int[MESHROW][MESHCOL];
partMesh is declared as a pointer to an int. The new expression produces, effectively, a pointer to an array of MESHCOL ints. In C++ you cannot convert a pointer to an array into a different kind of a pointer.
Furthermore, nothing shown here requires the use of new in the first place. partMesh could simply be a std::vector<vector<int>>, and the new replaced by a strategic resize(). As an extra bonus your C++ program will automatically delete all this memory when it is no longer needed, not leak it, and also implement correct copy/move semantics where needed!
meshingPart(&partMesh, MESHROW, MESHCOL);
As we've concluded, the first parameter to the function is a reference to an array. Passing to it an address of a pointer to int will also not work.
Furthermore, since partMesh is a member of the same class, having one function in the class pass, in some form, a member of the same class to another class method accomplishes absolutely useful, whatsoever. Since it's a member of the same class it doesn't need passing, the class method can access it directly. This is what, after all, classes are all about.
In conclusion:
There are several problems regarding the C++ type system that are causing these compilation errors.
It is not necessary to even use new here, to initialize the pointer, and either its type needs to be adjusted to reflect that it's a pointer to a 2D array, or the new statement itself needs to be adjusted to allocate a one-dimensional array, since that's the only thing C++ allows you to convert to a plain pointer. And even that is overnegineered, since a std::vector will take care of all these pesky details by itself.
It is not necessary to even pass the member of the same class to the same class's method, as a parameter, just have the class method access it directly.
It's apparent that the likely process that produced the shown code was to write it in its entirety, and only try to compile after the whole thing was written. An avalanche of compilation errors is almost guaranteed any time this approach is used. It is far more productive to write a large program by writing only a few lines at a time, testing them, make sure they work correctly, and only then write a few more. This way, the number of errors that need to be fixed will remain quite small, and manageable.
|
69,958,694 | 69,977,547 | Can I set a value using a function in a class? | If I have a friend function can I somehow use set() to assign a value to a private variable inside the function? Or some other method?
Example : Here I have 3 private variables. I tried to make the sum of 2 of them and store the result in the 3rd one. I tried to do it with a setter but the result is 0. In main it works, but I don't know if I can make it work in the class function.
#include <iostream>
using namespace std;
class Function{
private:
int a;
int b;
int sum;
public:
Function() = default;
Function(int _a, int _b);
friend int sumNumber(Function f);
//Setter and getter
int getA() const;
void setA(int a);
int getB() const;
void setB(int b);
int getSum() const;
void setSum(int sum);
};
Function::Function(int _a, int _b) {
this->a = _a;
this->b = _b;
}
int Function::getA() const {
return a;
}
void Function::setA(int a) {
Function::a = a;
}
int Function::getB() const {
return b;
}
void Function::setB(int b) {
Function::b = b;
}
int Function::getSum() const {
return sum;
}
void Function::setSum(int sum) {
Function::sum = sum;
}
int sumNumber(Function f) {
int a = f.getA();
int b = f.getB();
int sum = a + b;
f.setSum(sum);
return sum;
};
int main() {
Function AA(1,2);
cout << sumNumber(AA);
cout << " " << AA.getSum();
AA.setSum(sumNumber(AA));
cout << "\n" << AA.getSum();
return 0;
}
Output :
3 0
3
| As alluded to in the comments, the issue is with this function:
int sumNumber(Function f) {
int a = f.getA();
int b = f.getB();
int sum = a + b;
f.setSum(sum);
return sum;
};
Let us walk through your code:
Function AA(1,2);
You create a object of type Function, called AA and you allocate each member variable of that object via the constructor (1 and 2).
cout << sumNumber(AA);
You call your method (sumNumber) and pass to it a copy of your variable AA. That function adds the two numbers together and internally calls setSum.
cout << " " << AA.getSum();
You now try to display the sum value by calling the getSum method. But the issue was that you passed a copy of your variable into the sumNumber function. The original AA variable was left alone.
To fix this you need to adjust your function by adding an ampersand &. Like this:
int sumNumber(Function& f) {
int a = f.getA();
int b = f.getB();
int sum = a + b;
f.setSum(sum);
return sum;
};
Now your variable AA is being passed by reference and not by value. There are lots of tutorials about this concept.
|
69,958,896 | 69,960,027 | How to binary serialize in a buffer with Boost | How to binary serialize in a buffer?
I didn't find answer on official documentation and on stackoverflow it absent too.
The most part of examples show how to binary serialize in some file.
Other part show how to binary serialize in the string. (I think this is wrong way because binary could have a lot of null-s, but sting - don't)
But how to binary serialize in some buffer - there are no information.
Could someone show how to do it?
|
(I think this is wrong way because binary could have a lot of null-s, but sting - don't)
C++ strings contain NUL characters just fine
But how to binary serialize in some buffer - there are no information. Could someone show how to do it?
Strings are also "some buffer". So using std::stringstream (which you likely saw) is already an answer to your question.
However, if you think a buffer is only when you have a naked array of char or something, you can "mount" a stream onto that. Now this is supposedly not too much work with std::streambuf, but the little I know about it is that it gets tricky around char_traits.
So, let's do the easy thing and use the Boost Iostreams types that already do this:
Live On Coliru
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/string.hpp>
#include <iostream>
#include <iomanip>
namespace bio = boost::iostreams;
using Map = std::map<int, std::string>;
int main()
{
char buf[1024*10];
{
bio::stream<bio::array_sink> os(buf);
boost::archive::binary_oarchive oa(os);
oa << Map{
{1, "one"}, {2, "two"}, {3, "three"},
{4, "four"}, {5, "five"}, {6, "six"},
};
}
{
bio::stream<bio::array_source> is(buf);
boost::archive::binary_iarchive ia(is);
Map m;
ia >> m;
for (auto& [k,v] : m)
std::cout << " - " << k << " -> " << std::quoted(v) << "\n";
}
}
Printing
- 1 -> "one"
- 2 -> "two"
- 3 -> "three"
- 4 -> "four"
- 5 -> "five"
- 6 -> "six"
|
69,958,948 | 69,960,559 | Linux make: Need to rebuild a text file when makefile changes | I've inherited a Linux C++ app and makefile. In the existing makefile, it had code such as the following:
APPVER=5.01
REL=B
$(APP): $(OBJS) $(MAKEFILE)
echo $APPVER > .sw_ver.txt
echo " " >> .sw_ver.txt
echo $REL >> .sw_ver.txt
$(LD) $(OBJS) $(LDFLAGS) -o $(APP)
At runtime, the app would open this text file and display its version.
In the spirit of Make, rebuilding that .sw_ver.txt every time file just felt wrong. So I broke it up like the following:
APPVER=5.01
REL=B
$(APP): $(OBJS) $(MAKEFILE) .sw_ver.txt
$(LD) $(OBJS) $(LDFLAGS) -o $(APP)
.sw_ver.txt: $(MAKEFILE)
echo $APPVER > .sw_ver.txt
echo " " >> .sw_ver.txt
echo $REL >> .sw_ver.txt
Steps:
make -B: it performs the steps, creating the text file and updating the app.
do some update the Makefile
make: here it says there's no need to update the text file and prunes the rule.
I expected it to see the Makefile has changed, and therefore go update the text file. But it doesn't.
I tried adding a dummy file, but it says seems to get pruned.
What I'm trying to do is if only if the Makefile has changed (thinking that perhaps APPVER or REL have changed), then rebuild the .sw_ver.txt file.
Do you have any advice?
thanks
===== edit #1
hi, so I tried an alternative, to move the version info out to a file instead of trying to create the file during a make run. Since I inherited this stuff, I was trying to change as little as possible.
Just for trivia's sake, it would be interesting to know if there is an answer to the original question.
thanks again
file .sw_ver.txt
5.01 B
Makefile:
$(APP): $(OBJS) $(MAKEFILE) .sw_ver.txt
$(LD) $(OBJS) $(LDFLAGS) -o $(APP)
.sw_ver.txt: $(MAKEFILE)
===== edit #2
I spoke too soon. This setup works if any of the OBJS are changed, but it does not work if Makefile itself is changed.
So, kind strangers... any thoughts? Thanks
| Two things to clarify:
MAKEFILE is not an implicit built-in variable. So if you don't set its value it contains nothing. (You can run make -p in a directory without a Makefile to see what variables are there. See https://www.gnu.org/software/make/manual/html_node/Implicit-Variables.html)
Based on the reason above, since your $(MAKEFILE) is empty, when it expands, the .sw_ver.txt becomes a rule without prerequisites. Hence if .sw_ver.txt already exists, nothing will be done to regenerate it. What you get is actually this (note that your syntax $APPVER and $REL are actually wrong as well):
.sw_ver.txt: # $(MAKEFILE) is empty
echo PPVER > .sw_ver.txt # $(A) is empty
echo " " >> .sw_ver.txt
echo EL >> .sw_ver.txt # $(R) is empty
So what you need to do is:
Give your MAKEFILE variable a value.
MAKEFILE := Makefile
Fix your syntax:
.sw_ver.txt: $(MAKEFILE)
echo $(APPVER) > $@
echo " " >> $@
echo $(REL) >> $@
After you do this you should be able to regenerate .sw_ver.txt whenever you update your Makefile.
|
69,959,087 | 69,959,272 | WinInet Access Violation in HttpOpenRequest() | I am trying to upload a file to a PHP page using WinInet. I'm getting an Access Violation on one of the functions, but can't see why. I've built the code from an example page.
Here is the code:
HINTERNET aInternet=InternetOpen("My-Custom-Agent/1.0",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
HINTERNET aConnect=InternetConnect(aInternet,"www.myserver.com",INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if (aConnect)
{
HINTERNET aRequest=HttpOpenRequest(aConnect, (const char*)"POST","myphppage.php", NULL, NULL, (const char**)"*/*\0",0,1);
// ^^
// Exception happens on this line
// Exception thrown at 0x70C85B7C (ininet.dll) in TestApp.exe:
// 0xC00000005: Access violation reading location 0x002A2F2A
//
}
When I download from the server with InternetOpenURL(), everything seems fine. It just doesn't like what I'm doing somewhere here. Any clue what I'm doing wrong?
| Per the HttpOpenRequest() documentation:
[in] lplpszAcceptTypes
A pointer to a null-terminated array of strings that indicates media types accepted by the client. Here is an example.
PCTSTR rgpszAcceptTypes[] = {_T("text/*"), NULL};
Failing to properly terminate the array with a NULL pointer will cause a crash.
You are passing in a pointer to a single null-terminated string, incorrectly type-casted to const char**:
lplpszAcceptTypes -> "*/*"
But the function requires a pointer to an array of pointers to null-terminated strings, where the last element in the array must be NULL to terminate the array (since there is no function parameter to specify the number of elements in the array):
-----
lplpszAcceptTypes -> | 0 | -> "*/*"
|---|
| 1 | -> NULL
-----
See the difference?
The function is misinterpreting the content of your string literal as if it were a pointer, which it is not, hence the AV crash. The address where the AV is occurring, 0x002A2F2A, is literally the same bytes as the content of your string literal ("*/*“ = 0x2A 0x2F 0x2A 0x00).
You need to use this instead:
LPCSTR rgpszAcceptTypes[] = {"*/*", NULL};
HINTERNET aRequest = HttpOpenRequest(aConnect, "POST", "myphppage.php", NULL, NULL, rgpszAcceptTypes, 0, 1);
|
69,959,091 | 69,959,132 | How do I input 2 variables in one line and count them in output? | Out of all activity I've been tasked with, this was by far one of the most challenging one.
I am an IT student, ie a beginner in the C++ language, and so far I've only been taught how to make use of while loops and if conditions. By this, we have to use these two in the following activity:
Count how many of a certain digit is present on a given number.
Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result (see sample input and output for example).
In short, a program that reads the first value and checks how many of this first value is present in the second value.
Supposed Input: 2 1242182
Expected Output: 3
As you can see, it counts how many 2s are present in the second value (1242182). The result is 3 since there are three 2s present in it.
I find it impossible to create a program that can read 2 values in one line just using if conditions and a while loop, but this was given by us from an official programming website.
It should look like this.
#include <iostream>
using namespace std;
int main() {
int v1;
cin >> v1;
if (...) {
....
}
while (...) {
...
}
return 0;
}
Also, no using arrays.
| #include <iostream>
using namespace std;
int main() {
int v1, v2;
cin >> v1 >> v2;
}
|
69,959,421 | 69,959,911 | Strange error while expanding parameter pack containing lambda types | I have a function which looks like foo in the following example:
template <typename... Parameters>
void foo(std::function<void (Parameters &)>... functions) {
// does interesting things with these functions
}
Now I want to call this function with some lambdas, e.g. like this:
foo([](const std::string & string) {});
Unfortunately that doesn't work, because I get the following error:
error: no matching function for call to 'foo'
note: candidate template ignored: could not match 'function<void (type-parameter-0-0 &)>' against '(lambda at file.cpp:50:23)'
AFAIK, that is, because lambdas cannot be implicitly converted to std::functions like that.
One way to solve this problem is to manually wrap the lambdas in std::function like so:
foo(std::function<void (const std::string &)>([](const auto & string) {}));
But for multiple lambdas this would get very tedious.
To get around this problem, I tried to create a wrapper function which detects the parameter type of the lambdas it gets passed using a helper type, and then wraps the lambda in the correct std::function type. Here is this wrapper function for only a single parameter (i.e. not variadic):
template <typename Function>
void fooWrapped(Function && function) {
foo(std::function<void (typename FunctionTypeTraits<Function>::ParameterType &)>(function));
}
The helper type FunctionTypeTraits is implemented like this:
template <typename Function>
class FunctionTypeTraits:
public FunctionTypeTraits<decltype(&std::remove_reference<Function>::type::operator())> {};
template <typename Param>
class FunctionTypeTraits<void (&)(Param &)> {
typedef Param ParameterType;
};
Now I can call the wrapper function with my lambda and the compiler is perfectly happy:
fooWrapped([](const std::string & string) {});
In principle, I should now be able to make fooWrapper variadic like so:
template <typename... Functions>
void fooWrapped(Functions &&... functions) {
foo((std::function<void (typename FunctionTypeTraits<Functions>::ParameterType &)>(functions))...);
}
That doesn't work however. If I call this new function with the exact same code, I get the following error:
error: 'std::remove_reference<void ((lambda at file.cpp:50:23)::*)(const std::string &) const>::type' (aka 'void ((lambda at file.cpp:50:23)::*)(const std::string &) const') is not a class, namespace, or enumeration
I don't quite understand this error. Why does the same approach work for a single template type, but not for an expanded parameter pack? Is this maybe just a compiler bug?
Is there another way, I could achieve my goal of calling foo using lambdas, without manually wrapping each of them in a std::function?
| The type of address of lambda's operator() is void (Lambda::*)(Param&) const not void (&)(Param &), you need to define the base case of your FunctionTypeTraits as:
template <typename Function>
struct FunctionTypeTraits:
public FunctionTypeTraits<decltype(&std::remove_reference<Function>::type::operator())> {};
template <typename Lambda, typename Param>
struct FunctionTypeTraits<void (Lambda::*)(Param) const> {
typedef Param ParameterType;
};
Another point is that in your fooWrapped, the type of specify for std::function should be void (typename FunctionTypeTraits<Function>::ParameterType) instead of just ParameterType since the latter is not a function type:
template <typename... Function>
void fooWrapped(Function&&... function) {
foo(std::function<void (typename FunctionTypeTraits<Function>::ParameterType)>(function)...);
}
Demo.
|
69,959,634 | 69,959,793 | Function template specialization in C++, no Instance of overloaded function | I'm learning about function template specialization in C++ and am tasked with writing a template function called plus that returns the sum of it's two arguments which maybe of different types. One version that accepts by value and another by pointer. As an added challenge, I'm asked to overload this function so that it concatenates two strings.
template <typename T1, typename T2> decltype(auto) plus(const T1& a, const T2& b) {
return a + b;
}
template <typename T1, typename T2> decltype(auto) plus(const T1* a, const T2* b) {
return *a + *b;
}
// concatenate two strings
template <>
std::string_view plus<std::string_view, std::string_view> (std::string_view a, std::string_view b) {
return std::string { a } + std::string{ b };
}
The problem is that I'm getting an error on the specialization overload of the function to concatenate two strings. The reason I decided to choose std::string_view over std::string is so that when calling the function with string literals (const char*) it wouldn't resolve to the second definition that accepts a const * which I'm guessing would be resolved over std::string.
So I can't really figure out what's going on. Just a wild guess but maybe this has something to do with me having two different template functions called plus and it can't figure out which one I'm trying to specialize / overload?
UPDATE:
The issue seems to be with template resolution. The definition that accepts const T* is always preferred for any string literals. Just trying to find a fix.
| This would be my suggestion:
template <typename T1, typename T2, typename T3> T3 plus(const T1& a, const T2& b) {
return a + b;
}
template <typename T1, typename T2, typename T3> T3 plus(const T1* a, const T2* b) {
return *a + *b;
}
template <typename T1, typename T2, typename T3> T3 plus(T1 a, T2 b) {
return a + b;
}
// concatenate two strings
template <>
std::string plus<std::string_view, std::string_view> (std::string_view a, std::string_view b) {
return std::string(a).append(b);
}
Since string views needs to refer to the content of another string you need to return a string since the newly created string_view would point to a temporary object.
Also there is no way to concatenate 2 string_view's together since concatenating two strings together would require that string_view's are able to hold references to other string views (since they don't hold string content themselves).
Furthermore, a third typename is required since this implementation would return another type (std::string) since you don't want to return a string_view of a temporary
|
69,959,795 | 69,959,833 | How to obtain smoothed normals when extruding a 2d curve (with parametric normals) into 3d? | I'm extruding a sine-wave curve into 3d but when rendering, I can see that the normals are not smoothed.
The sine-wave is generated with parametric normals, as follows:
vector<CurvePoint> sineWave(int n, float x0, float y0, float step, float period)
{
vector<CurvePoint> curve;
for (int i = 0; i < n; i++) {
float a = TWO_PI / period;
float x = x0 + i * step;
float y = y0 - sinf(x * a);
float c = cosf(x * a);
auto normal = glm::vec2(a * c, 1) / sqrtf(a * a * c * c + 1);
curve.emplace_back(glm::vec2(x, y), normal);
}
return curve;
}
The extruding method:
void extrude(IndexedVertexBatch<XYZ.N> &batch, const Matrix &matrix, const vector<CurvePoint> &curve, GLenum frontFace, float distance)
{
auto size = curve.size();
if (size > 1 && distance != 0) {
bool cw = ((frontFace == CW) && (distance > 0)) || ((frontFace == CCW) && (distance < 0));
for (auto i = 0; i < size - 1; i++) {
auto &p0 = curve[i].position;
auto &p1 = curve[i + 1].position;
auto normal = matrix.transformNormal(glm::vec3(curve[i].normal, 0));
batch
.addVertex(matrix.transformPoint(p0), normal)
.addVertex(matrix.transformPoint(p1), normal)
.addVertex(matrix.transformPoint(glm::vec3(p1, distance)), normal)
.addVertex(matrix.transformPoint(glm::vec3(p0, distance)), normal);
if (cw) {
batch.addIndices(0, 3, 2, 2, 1, 0);
} else {
batch.addIndices(0, 1, 2, 2, 3, 0);
}
batch.incrementIndices(4);
}
}
}
The rendering (phong-like shading):
How can I obtain smoothed normals?
| Stupid me. It was a small bug in the extruding method, which should be like:
void extrude(IndexedVertexBatch<XYZ.N> &batch, const Matrix &matrix, const vector<CurvePoint> &curve, GLenum frontFace, float distance)
{
auto size = curve.size();
if (size > 1 && distance != 0) {
bool cw = ((frontFace == CW) && (distance > 0)) || ((frontFace == CCW) && (distance < 0));
for (auto i = 0; i < size - 1; i++) {
auto &p0 = curve[i].position;
auto &p1 = curve[i + 1].position;
auto normal0 = matrix.transformNormal(glm::vec3(curve[i].normal, 0));
auto normal1 = matrix.transformNormal(glm::vec3(curve[i + 1].normal, 0));
batch
.addVertex(matrix.transformPoint(p0), normal0)
.addVertex(matrix.transformPoint(p1), normal1)
.addVertex(matrix.transformPoint(glm::vec3(p1, distance)), normal1)
.addVertex(matrix.transformPoint(glm::vec3(p0, distance)), normal0);
if (cw) {
batch.addIndices(0, 3, 2, 2, 1, 0);
} else {
batch.addIndices(0, 1, 2, 2, 3, 0);
}
batch.incrementIndices(4);
}
}
}
|
69,959,957 | 69,962,602 | Use cplex with c++: add conditional constraint | I'm new in cplex, I found in python the function: add_indicator_constraint, but in c++ I can't find anything like that. Can someone show me, please?
| in the example ilofixnet.cpp in CPLEX_Studio201\cplex\examples\src\cpp you can see a good example of indicator constraint in C++
// Add logical constraints that require x[i]==0 if f[i] is 0.
for (IloInt i = 0; i < x.getSize(); ++i)
model.add(IloIfThen(env, f[i] == 0, x[i] == 0));
|
69,960,187 | 69,960,214 | How do I successfully implement my .h file to my main .cpp file to make it run without errors | The code is supposed to take the class from the .h file and use it in the main to create a custom pet synopsis that can be stored later in another text file. I haven't made the modular extraction to a text file yet because I need to get it at least working and able to actually compile and return the different arrays that make up the custom pet synopsis.
/usr/bin/ld: /tmp/: in function `__static_initialization_and_destruction_0(int, int)':
program3.cpp:(.text+0x411): undefined reference to `dog_list::dog_list()'
/usr/bin/ld: program3.cpp:(.text+0x426): undefined reference to `dog_list::~dog_list()'
collect2: error: ld returned 1 exit status
My .h file
#include<iostream>
#include<cstring>
#include<cctype>
#include<fstream>
using namespace std;
const int SIZE = 20;
const int END = 11;
class dog_list
{
public:
dog_list();
~dog_list();
void record_pets();
private:
char name[SIZE];
char breed[SIZE];
char species[SIZE];
char service[SIZE];
char special[SIZE];
};
dog_list op;
void record_pets();
my main .cpp file
#include "program3.h"
int main()
{
op.record_pets();
return 0;
}
void dog_list::record_pets()
{
char personal_list[SIZE];
int i = 0;
char again;
do
{
cout << "Enter in pets name: ";
cin.get(op.name,25,'\n');
cin.ignore(100,'\n');
cout << endl << "Enter breed of pet: ";
cin.get(op.breed, 25, '\n');
cin.ignore(100,'\n');
cout << endl << "Enter species: ";
cin.get(op.species,25,'\n');
cin.ignore(100,'\n');
cout << endl << "Enter in service qualifications: ";
cin.get(op.service,25,'\n');
cin.ignore(100,'\n');
cout << endl << "Enter in special notes: ";
cin.get(op.special,25,'\n');
cin.ignore(100,'\n');
cout << endl;
cout << "Name: " << op.name << endl;
cout <<"Breed: " << op.breed << endl;
cout << "Species: " << op.species << endl;
cout << "Service Qualifications: " << op.service << endl;
cout << "Special Notes: " << op.special << endl;
cout << "Pet saved! Would you like to enter another pet? Y/N: " << endl;
cin >> again;
cin.ignore(100,'\n');
cout << endl;
if(again == 'y')
{
again = toupper(again);
}
}while(again == 'Y' && i <= END);
{
++i;
}
}
| You never implement the constructor and destructor, you just declare it:
dog_list();
~dog_list();
You have to implement it, for example, in main.cpp:
dog_list::dog_list() = default;
dog_list::~dog_list() = default;
|
69,960,342 | 69,961,523 | How to properly store lambda functions in a tuple and call them? | I'm trying to create a class that can store functions in a member tuple. But when trying to put lambdas inside of an object's tuple (through function pointers) I'm getting a error. Please explain, what I'm doing wrong and what is the proper way of releasing this idea. I think there should be an elegant and stylistically correct general solution (in terms of functional programming patterns) to avoid boilerplate code in class description, objects creation and filling them with functions.
#include <functional>
#include <string>
#include <iostream>
template<typename... ArgTypes>
class MyClass {
public:
//boolean function of some argument
template<typename Type> using Func = bool(Type const &);
//type for a tuple of pointers to templated boolean functions
template<typename... Types> using TupleOfFunctions = typename std::tuple<Func<Types>*...>;
//the tuple
TupleOfFunctions<ArgTypes...> _tuple;
//constructor
MyClass(TupleOfFunctions<ArgTypes...> t) : _tuple(t) {
}
};
int main(int argc, char** argv) {
MyClass<int, std::string> M({
[](int &arg) { return arg > 0; },
[](std::string &arg) { return arg == "abc"; }
});
std::cout << (*std::get<0>(M._tuple))(1);
std::cout << (*std::get<1>(M._tuple))("xyz");
return 0;
}
The error I get is
./test.cpp:26:3: error: no matching function for call to 'MyClass<int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::MyClass(<brace-enclosed initializer list>)'
26 | });
| template<typename Type> using Func = bool(Type const &);
This line suggested functions taking in const type arguments. However:
[](int &arg) { return arg > 0; },
[](std::string &arg) { return arg == "abc"; }
These two lines suggested non-const arguments.
Either remove the const from the first line, or add const to the second two should solve it.
Could you, however, suggest some ideas of redesigning the class so that the boilerplate code of repeated explicit declaration of these types (in class template specification and lambda function arguments) can be avoided?
Part of the point of having lambda is anonymous function type. Actually trying to deduce a type of them, like what you did, was kind of going backward.
One way I would suggest to do this would be:
template<typename ... Lambdas>
class MyClass {
public:
std::tuple<Lambdas...> _tuple;
MyClass(Lambdas ... args) : _tuple(std::make_tuple(args ...)) {
}
};
Now you can use it like:
MyClass M(
[](const int &arg) { return arg > 0; },
[](const std::string &arg) { return arg == "abc"; }
);
Alternatively, you might be interested in a variant/visit pattern: https://godbolt.org/z/5Pdn1Ynqe
|
69,960,605 | 69,961,223 | How to make this upper lower case c++ program work? | I am trying to make this app which converts upper case characters of a string to lower case
and vice versa.
But when i run the code it displays a really weird output
The code i wrote:
#include <iostream>
#include <string.h>
std::string toggle(std::string str)
{
#define maxsize 100
if (sizeof(str)>maxsize)
{
std::cout << "Size of string is too big!" << std::endl;
exit(1);
}
else
{
for (int i = 0 ; i<=sizeof(str) ; i++)
{
if (isupper(str[i]))
{
std::cout << "UPPER CASE CONVERTED TO LOWER CASE "<< tolower(str[i]) <<"" << std::endl;
}
else
{
std::cout << "LOWER CASE CONVERTED TO UPPER CASE "<< toupper(str[i]) <<"" << std::endl;
}
}
}
}
int main()
{
toggle("Hello This Is A Test");
}
The output
UPPER CASE CONVERTED TO LOWER CASE 104
LOWER CASE CONVERTED TO UPPER CASE 69
LOWER CASE CONVERTED TO UPPER CASE 76
LOWER CASE CONVERTED TO UPPER CASE 76
LOWER CASE CONVERTED TO UPPER CASE 79
LOWER CASE CONVERTED TO UPPER CASE 32
UPPER CASE CONVERTED TO LOWER CASE 116
LOWER CASE CONVERTED TO UPPER CASE 72
LOWER CASE CONVERTED TO UPPER CASE 73
LOWER CASE CONVERTED TO UPPER CASE 83
LOWER CASE CONVERTED TO UPPER CASE 32
UPPER CASE CONVERTED TO LOWER CASE 105
LOWER CASE CONVERTED TO UPPER CASE 83
LOWER CASE CONVERTED TO UPPER CASE 32
UPPER CASE CONVERTED TO LOWER CASE 97
LOWER CASE CONVERTED TO UPPER CASE 32
UPPER CASE CONVERTED TO LOWER CASE 116
LOWER CASE CONVERTED TO UPPER CASE 69
LOWER CASE CONVERTED TO UPPER CASE 83
LOWER CASE CONVERTED TO UPPER CASE 84
LOWER CASE CONVERTED TO UPPER CASE 0
LOWER CASE CONVERTED TO UPPER CASE 0
LOWER CASE CONVERTED TO UPPER CASE 0
LOWER CASE CONVERTED TO UPPER CASE 0
LOWER CASE CONVERTED TO UPPER CASE -73
LOWER CASE CONVERTED TO UPPER CASE -125
LOWER CASE CONVERTED TO UPPER CASE -97
LOWER CASE CONVERTED TO UPPER CASE 34
UPPER CASE CONVERTED TO LOWER CASE 119
UPPER CASE CONVERTED TO LOWER CASE 98
LOWER CASE CONVERTED TO UPPER CASE 0
LOWER CASE CONVERTED TO UPPER CASE 0
LOWER CASE CONVERTED TO UPPER CASE -48
Why is it displaying integers instead of a string?
Am i doing something wrong?
I can see it is converting the upper case characters to lower case and back but why is it not displaying strings?
| First i have added a return inside the toggle function. Second, you can find out the length/size of a std::string using the size() member function. Using these two modifications your program would look like:
#include <iostream>
#include <string.h>
#define maxsize 100
std::string toggle(std::string str)
{
if ( str.size() > maxsize)
{
std::cout << "Size of string is too big!" << std::endl;
}
else
{
for (int i = 0 ; i < str.size() ; i++) //note here i have removed <= and instead used <
{
if (isupper(str.at(i)))
{
str.at(i) = tolower(str.at(i));
std::cout << "UPPER CASE CONVERTED TO LOWER CASE "<< str.at(i) <<" " << std::endl;
}
else
{
str.at(i) = toupper(str.at(i));
std::cout << "LOWER CASE CONVERTED TO UPPER CASE "<< str.at(i) <<" " << std::endl;
}
}
}
return str; //added this return
}
int main()
{
toggle("Hello This Is A Test");
}
The output of the above program is:
UPPER CASE CONVERTED TO LOWER CASE h
LOWER CASE CONVERTED TO UPPER CASE E
LOWER CASE CONVERTED TO UPPER CASE L
LOWER CASE CONVERTED TO UPPER CASE L
LOWER CASE CONVERTED TO UPPER CASE O
LOWER CASE CONVERTED TO UPPER CASE
UPPER CASE CONVERTED TO LOWER CASE t
LOWER CASE CONVERTED TO UPPER CASE H
LOWER CASE CONVERTED TO UPPER CASE I
LOWER CASE CONVERTED TO UPPER CASE S
LOWER CASE CONVERTED TO UPPER CASE
UPPER CASE CONVERTED TO LOWER CASE i
LOWER CASE CONVERTED TO UPPER CASE S
LOWER CASE CONVERTED TO UPPER CASE
UPPER CASE CONVERTED TO LOWER CASE a
LOWER CASE CONVERTED TO UPPER CASE
UPPER CASE CONVERTED TO LOWER CASE t
LOWER CASE CONVERTED TO UPPER CASE E
LOWER CASE CONVERTED TO UPPER CASE S
LOWER CASE CONVERTED TO UPPER CASE T
as can be seen here.
|
69,960,826 | 69,960,901 | What is the Faster way to fill vector from float pointer? | Is there a faster way than what I have below to append a number of floats to a vector, where the source floats come from const float buffers? The example below, which is what I currently have, gets called in a loop to append somewhere between 1-16 floats at a time. At any one time, that function can be called 1000's of times within a loop to fill the dst buffer. The ptr object may be different each time. This is dealing with 3D geometry.
void appendFloats(std::vector<float>& dst, const float* ptr, uint32_t count) {
for (uint32_t i = 0; i < count; ++i) {
dst.push_back(ptr[i]);
}
}
| The fastest linear way is
dst.insert(dst.end(), ptr, ptr + count);
Even a faster way is using the parallel algorithm or OMP.
|
69,960,995 | 69,961,072 | Tried appending multiple nodes in LinkedList c++ but it's just printing 1 node | I tried appending multiple nodes in LinkedList c++ but it is just printing 1 node as I run it. Kindly review it, and help me fix it.
#include <iostream>
using namespace std;
//here is the node
struct Node {
int data;
struct Node* next;
};
// ------------here is linkedlist-----------
class LinkedList {
private:
Node* head;
public:
LinkedList()
{
head = NULL;
}
//----------- append function ------------
void appendNode(int d)
{
Node* newNode = new Node;
Node* nodePtr;
newNode->data = d;
newNode->next = NULL;
if (!head)
{
head = newNode;
}
else
{
nodePtr = head;
while (nodePtr->next)
{
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
}
}
//--------------- display function--------------
void display()
{
Node* nodePtr;
nodePtr = head;
while (nodePtr != NULL)
{
cout << nodePtr->data << endl;
nodePtr = nodePtr->next;
}
}
};
//-------------- main function -------------
int main()
{
LinkedList ll;
ll.appendNode(2);
ll.appendNode(21);
ll.appendNode(11);
ll.display();
}
| Change your while loop from:
while (nodePtr->next)
{
nodePtr = nodePtr->next;
nodePtr->next = newNode;
...
}
to
while (nodePtr->next)
{
nodePtr = nodePtr->next;
...
}
nodePtr->next = newNode;
Also, in C++ use nullptr instead of NULL.
|
69,961,252 | 69,961,390 | Attempting to save vector<int> in bin file and reading it gave random data | I wrote two functions to save and read data in a bin file:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// save data in file with name p_file
template <typename T>
void save(string p_file, T data) {
ofstream output(p_file, ios::binary | ios::out);
output.write((char*) &data, sizeof(data));
output.close();
}
// read and return data in file with name p_file
template <typename T>
T read(string p_file) {
ifstream input(p_file, ios::binary | ios::in);
T data;
input.seekg(0, input.end);
int length = input.tellg();
input.seekg(0, input.beg);
input.read((char*) &data, length);
input.close();
return data;
}
int main() {
vector<int> vint;
vint.push_back(1);
save< vector<int> >("test.bin", vint);
vector<int> load_vint = read< vector<int> >("test.bin");
cout << vint[0] << endl;
cout << load_vint[0] << endl;
cout << "done" << endl;
}
expected output:
1
1
done
actual output:
1
1990048
done
Things got even worse when I put most of the code in main into test and didn't change anything in save and read:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
// save data in file with name p_file
template <typename T>
void save(string p_file, T data) {
ofstream output(p_file, ios::binary | ios::out);
output.write((char*) &data, sizeof(data));
output.close();
}
// read and return data in file with name p_file
template <typename T>
T read(string p_file) {
ifstream input(p_file, ios::binary | ios::in);
T data;
input.seekg(0, input.end);
int length = input.tellg();
input.seekg(0, input.beg);
input.read((char*) &data, length);
input.close();
return data;
}
// exact same code, just in a function
void testing() {
vector<int> vint;
vint.push_back(1);
save< vector<int> >("test.bin", vint);
vector<int> load_vint = read< vector<int> >("test.bin");
cout << vint[0] << endl;
cout << load_vint[0] << endl;
}
int main() {
testing();
cout << "done" << endl;
}
expected output:
1
1
done
actual output:
1
1924512
What is going on and how do I fix this error?
| You are passing the address of the vector object to the save function (which lives on the stack) and not the underlying dynamic array (lives on the heap memory) which holds the ints. Also have a look at how std::vector works: https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdvector/
Here is my full solution with lots of refactoring and cleanup:
main.cpp
#include <iostream>
#include <fstream>
#include <vector>
// save data in file with name p_file
void save( const std::string& p_file, const std::vector<int>& data )
{
std::ofstream output( p_file, std::ofstream::binary );
if ( !output.is_open( ) )
{
throw std::ios_base::failure( "Error while opening the file " + p_file );
}
for ( auto it = data.begin(); it != data.end(); ++it )
{
output.write( reinterpret_cast< const char* >( &(*it) ), sizeof( int ) );
}
/*
if ( !data.empty() ) // Or use this instead of the for loop
{
size_t numOfBytes { data.size( ) * sizeof( int ) };
output.write( reinterpret_cast< const char* >( &(data[0]) ), numOfBytes );
}
*/
output.close();
}
// read and return data in file with name p_file
std::vector<int> read( const std::string& p_file )
{
std::ifstream input( p_file, std::ifstream::binary );
if ( !input.is_open( ) )
{
throw std::ios_base::failure( "Error while opening the file " + p_file );
}
input.seekg( 0, input.end );
size_t length = input.tellg();
input.seekg( 0, input.beg );
size_t numOfIntsInFile { length / sizeof( int ) };
std::vector<int> data( numOfIntsInFile );
for ( auto it = data.begin(); it != data.end(); ++it )
{
input.read( reinterpret_cast< char* >( &(*it) ), sizeof( int ) );
}
/*
if ( !data.empty() ) // Or use this instead of the for loop
{
input.read( reinterpret_cast< char* >( &(data[0]) ), length );
}
*/
input.close();
return data;
}
// exact same code, just in a function
void test()
{
std::vector<int> vint;
vint.push_back( 1 );
vint.push_back( 2235 );
vint.push_back( 3 ); // push back as many ints as you want, it won't break.
std::vector<int> load_vint;
try
{
save( "test.bin", vint );
load_vint = read( "test.bin" );
}
catch ( const std::ios_base::failure& e )
{
std::cerr << "Caught an std::ios_base::failure.\n"
<< e.what() << '\n'
<< "Error code: " << e.code() << '\n';
}
std::cout << '\n';
std::cout << "Printing the elements of vint: " << '\n';
for ( const auto& element : vint )
{
std::cout << element << '\n';
}
std::cout << '\n';
std::cout << "Printing the elements of load_vint: " << '\n';
for ( const auto& element : load_vint )
{
std::cout << element << '\n';
}
}
int main()
{
test();
std::cout << "\nDone." << std::endl;
}
Summary of the changes:
I removed the templates since they were annoying me! You can add them to my code if you really need template functions and then use them.
Use lvalue references (like const std::vector<int>&) where possible to avoid unnecessary copies.
Use C++ casts (like reinterpret_cast) instead of C-style casts as much as possible.
Avoid polluting the whole source file by writing using namespace std; at the top. Use it in limited scopes.
Use std::ofstream::binary or std::ifstream::binary instead of std::ios::binary where dealing with fstream objects.
Also added exception handling mechanisms in case a file can not be opened.
Extra note: Cleaning the code and making it a bit more readable ensures that other people can easily read and understand your problem.
|
69,961,275 | 69,961,321 | cannot access private member in the same class | I tried to declare a public member function with a private struct, but it didn't work. Can someone help me with this? Here's the header file
class LinkedList
{
public:
LinkedList();
~LinkedList();
...
//I tried to add LinkedList also not working
//void deleteNode(const LinkedList::Node* n);
void deleteNode(const Node* n);
private:
struct Node
{
std::string value;
Node *next;
};
| class LinkedList
{
public:
LinkedList();
~LinkedList();
void deleteNode(const Node* n);
private:
struct Node
{
std::string value;
Node *next;
};
};
Node is declared after void deleteNode(const Node* n);, so the compiler won't know what Node is.
You should do this instead:
class LinkedList
{
private:
struct Node
{
std::string value;
Node *next;
};
public:
LinkedList();
~LinkedList();
void deleteNode(const Node* n);
};
|
69,961,473 | 69,975,236 | Template argument deduction for parenthesized initialization of aggregates in C++ | In the following code there is an initialization of A<T> objects with template argument deduction using two forms distinct by the type of braces:
template<typename T>
struct A{ T x; };
int main() {
static_assert( A{1}.x == 1 ); //#1: ok in GCC and MSVC
static_assert( A(1).x == 1 ); //#2: ok in GCC only
}
The first way is accepted by both GCC and MSVC, while the second one is ok for GCC only while MSVC prints errors:
error C2641: cannot deduce template arguments for 'A'
error C2780: 'A<T> A(void)': expects 0 arguments - 1 provided
error C2784: 'A<T> A(A<T>)': could not deduce template argument for 'A<T>' from 'int'
Demo: https://gcc.godbolt.org/z/97G1acqPr
Is it a bug in MSVC?
| This is a bug in MSVC.
The following papers were all introduced in C++20:
P0960R3: Allow initializing aggregates from a parenthesized list of values
P1975R0: Fixing the wording of parenthesized aggregate-initialization
P2131R0: Fixing CTAD for aggregates
Whilst MSVC lists them all as implemented in their Microsoft C/C++ language conformance by Visual Studio version pages, it seems whilst they have correctly implemented them in isolation
// OK (P0960R3, P1975R0)
struct A { int x; };
A a(1);
// OK (P2131R0)
template<typename T>
struct B { T x; };
B b{1};
// rejects-invalid (allowed by the union of the papers)
template<typename T>
struct C { T x; };
C c(1);
MSVC seems to have missed implementing the union of the papers. I have not, however, been able to find an open bug report.
|
69,961,672 | 69,961,800 | Function which outputs several std::collections to CSV / row first iteration | I want to write a function with the following signature (or similar):
template <typename... Ts>
void collection_to_csv(const std::string filepath, const Ts& ... containers);
The function should write a csv file to a file located at filepath, where containers can be any number of iteratable containers from the STD and would define the columns of the outputted CSV file. E.g. I could use it like this:
std::vector<int> column1{1, 2, 3, 4};
std::list<float> column2{1.5, 2.5, 3.5, 4.5};
collections_to_csv(someFilePath, c1, c2);
Is this possible? So far I've been trying to use variadic templates like so:
template <typename... Ts>
void collection_to_csv(const std::string filepath, std::initializer_list<std::string> headers, const Ts& ... containers)
{
std::ofstream file;
file.open(filepath, std::ofstream::out | std::ofstream::trunc);
for (std::size_t irow=0; irow < size; ++irow)
{
for (const auto& container : containers) //But how to iterate through the variadic arguments when they could be different types?
{
file << container[i] << ",";
}
}
file.flush();
file.close();
}
Everything I've seen about variadic templates suggests they're 'iterated' using recursion but this would force a 'column first' iteration order. I need a 'row first' order, making me think variadic templates might be the wrong tool here. Is there a better approach?
| You can use std::tuple to store the iterator of each containers and then use std::apply to increment them one by one to do this.
#include <iostream>
#include <string>
#include <tuple>
#include <vector>
#include <list>
template <typename... Ts>
void collection_to_csv(const Ts&... containers) {
const auto ncol = [](const auto& first, const auto&...) {
return first.size();
}(containers...);
auto iters = std::make_tuple(containers.begin()...);
for (std::size_t icol = 0; icol < ncol; ++icol) {
std::apply(
[&](auto&... iter) {
((std::cout << *iter++ << ","), ...);
}, iters);
std::cout << "\n";
}
}
int main() {
std::vector column1{1, 2, 3, 4};
std::list column2{1.5, 2.5, 3.5, 4.5};
collection_to_csv(column1, column2);
}
Demo.
Thanks to the introduction of C++23 views::zip, collection_to_csv can be implemented more simply just using views::zip, that is, zip all containers and iterate their elements one by one.
#include <ranges>
#include <tuple>
template <typename... Ts>
void collection_to_csv(const Ts&... containers) {
for (const auto& values : std::ranges::zip_view(containers...)) {
std::apply(
[](const auto&... value) { ((std::cout << value << ","), ...); }, values);
std::cout << "\n";
}
}
Demo.
|
69,961,849 | 69,965,052 | OpenGL : Mesh turns black when adding specular lighting | I have implemented specular lighting in my C++ openGL program but when i add the final specular value into my existing diffuse lit equation, it turns black. Just displaying the specular on the mesh also doesnt work and the mesh remains back and removing the specular form the final equation for the Pixel restores the Non specular lighting.
How do i Fix this
These are the shaders.
#version 330 core
layout (location = 0) in vec3 pos;
layout (location = 1) in vec2 coords;
layout (location = 2) in vec3 normals;
out vec2 Texture_Coords;
out vec3 normal;
out vec3 toLightVector;
out vec3 toCameraVector;
uniform mat4 p;
uniform mat4 m;
uniform mat4 v;
uniform vec3 light_position;
void main(){
vec4 world_position = m * vec4(pos,1.0);
//unrelated working stuff
toCameraVector = (inverse(v) * vec4(0,0,0,1)).xyz - world_position.xyz;
}
#version 330 core
out vec4 Pixel;
in vec2 Texture_Coords;
in vec3 normal;
in vec3 toLightVector;
in vec3 toCameraVector;
uniform vec4 color;
uniform sampler2D Texture;
uniform float ambient;
uniform vec3 light_color;
uniform float reflective;
uniform float specular;
void main(){
vec3 unitToCameraVector = normalize(toCameraVector);
//unrelated working stuff
vec3 light_direction = -unitToLightVector;
vec3 reflection = reflect(light_direction, unitNormal);
float specular_factor = dot(reflection, unitToCameraVector);
specular_factor = max(specular, 0.0);
float damped_specular = pow(specular_factor, specular);
vec3 final_specular = damped_specular * light_color;
Pixel = vec4(diffuse,1.0) * texture(Texture, Texture_Coords) + vec4(final_specular, 1.0);
}
| Maybe there's a typo ? The statement
specular_factor = max(specular, 0.0);
looks like it should be :
specular_factor = max(specular_factor, 0.0);
|
69,961,956 | 69,962,033 | So, why do I have to define virtual function in a base class? | I'm trying to create a simple base abstract class with a virtual function and a child class that defines that virtual function. Running the following produces an error during compilation:
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak();
};
class Cat : public Animal{
public:
void speak() override {
cout << "Meow!";
}
};
int main() {
Cat cat;
Animal* base = &cat;
base->speak();
}
// error LNK2001: unresolved external symbol "public: virtual void __thiscall Base::speak(void)" (?speak@Base@@UAEXXZ)
My IDE suggests adding a useless definition for speak() in Animal, and it works:
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak();
};
void Animal::speak() {
}
class Cat : public Animal{
public:
void speak() override {
cout << "Meow!";
}
};
int main() {
Cat cat;
Animal* base = &cat;
base->speak();
}
So, why do I have to define virtual function in a base class?
By comparison, in Java there is no such need and even possibility (which makes more sense):
abstract class Animal {
abstract void speak();
}
class Cat extends Animal {
void speak() {
System.out.println("Meow!");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Cat();
animal.speak();
}
}
| Yes, non-pure virtual function should be defined.
[class.virtual]/12:
A virtual function declared in a class shall be defined, or declared pure ([class.abstract]) in that class, or both; no diagnostic is required ([basic.def.odr]).
You might provide a definition, or mark it as pure virtual.
class Animal {
public:
virtual void speak() = 0;
};
|
69,962,150 | 69,962,321 | Can't modify the value of a reference in Range based loop | I'm working on a school project of boolean minimization, and here I want to delete some elements of a set of my user defined class.
This is where the error occurs:
(dc and PI are both sets of my class Term, passed to this function by reference. std::set<Term>& dc, PI)
for (const auto& n : dc) {
for (const auto& i : n.getMinterm()) {
m[i] = 0;
for (auto &x : PI) {
x.delMinterm(i);
}
}
}
The error message is:
Error (active) E1086 the object has type qualifiers that are not compatible with the member function "Term::delMinterm"
Error C2662 'void Term::delMinterm(int)': cannot convert 'this' pointer from 'const Term' to 'Term &'
This is the content of my class:
class Term {
private:
int group = 0;
int literal = 0;
std::string term;
std::set<int>minterm;
bool isDontCare;
bool merged;
};
Function delMintern(int) just erases the selected element from the set minterm.
Though I didn't use "const auto&" but "auto&", it still shown as a const object.
I've tried taking off the '&' but it just create a local duplicate, however, I want to directly modify the original one.
I also tried something like:
for (auto x : PI) {
PI.erase(x);
x.delMinterm(i);
PI.insert(x);
}
but it caused a "read access violation" error.
| You can't modify a reference to x because it is const. It is const because iterating a std::set through loop gives only const values.
See solution with const_cast example code at the end of my answer.
It is known that std::set stores all entries in a sorted tree.
Now imagine if you can modify a variable when iterating a loop, it means that after modification sorted order of std::set might be changed. But std::set should always keep invariant of its tree, hence it can't allow to make any modifications thus gives only const values when iterating.
If you need to really modify set entry then you have to take it from set, delete from set and that add again to set. Even if sorted order is not changed after your modification, still you need to reinsert into set.
But there is a hacky workaround - you can make your method delMinentry as having const modifier. Then all fields that it modifies should be marked as mutable. Mutable fields allow modifications from const methods. And std::set allows to call const methods when iterating.
There is one more workaround - you make delMinterm() as const method, but inside this method do const_cast<Term &>(*this).delMintermNonConst(), in other words from const method you can call non-const method if you do const_cast. Also you can do const cast directly on loop variable if you're sure what you do, in other words if you modify Term in such a way that std::set sorted order is not changed:
for (auto &x : PI) {
const_cast<Term &>(x).delMinterm(i);
}
If delMinterm() results in such modification of a Term after which order of std::set may change then you can't do const_cast in code above. In other words if after delMinterm your operator < may give a different result between terms, then you can't do this const cast and you have to reinsert into set (delete Term and add again).
Also don't forget that after reinserting into set you have to redo set iteration loop again from start, because after change to inner structure you can't keep iterating loop running further, iterators are invalidated.
If set's order changes (hence you can't do const_cast) then you have to re-insert values of set, do this by copying values to vector, modifying them through delMinterm(), copying back to set, like this:
std::vector<Term> scopy(PI.cbegin(), PI.cend());
for (auto & x: scopy)
x.delMinterm(i);
PI = std::set<Term>(scopy.cbegin(), scopy.cend());
|
69,962,684 | 69,962,765 | what is the language code for Turkish in SAPI | I'm working on a desktop application on Windows using Windows API. Application sends notifications and notifications must be spoken in Turkish language. What's the code for Turkish language that required on Language parameter in ISpVoice::Speak function?
if(FAILED(voice->Speak((L"<sapi><voice required=\"Language=409\">"+alertBody+L"</voice></sapi>").c_str(), SPF_DEFAULT, NULL))) {
throw Error::Exception(L"Hatırlatma seslendirmesi yapılamadı!", L"Randevu Hatırlatma Hatası");
}
Thanks in advance.
| It's 41f.
if(FAILED(voice->Speak((L"<sapi><voice required=\"Language=41f\">"+alertBody+L"</voice></sapi>").c_str(), SPF_DEFAULT, NULL))) {
// ...
}
You can find it in the documentation: Windows Language Code Identifier (LCID) Reference
|
69,962,700 | 69,962,803 | Print 2D Array as a Method in C++ | I want to write a method in C++ which prints a 2D array. This method is void and it has these parameters as inputs: 2D array, number of rows, number of columns. I want to use the 2D matrix as a double pointer to call the function. I want to print the elements in a 2D shape. I get the following error:
error: cannot convert ‘int (*)[2]’ to ‘int**’
EDIT : changing int** list to int (*list)[2] works but is there a way which I don't have to write the column number manually, because I want this method to work for different sizes of array.
#include <iostream>
using namespace std;
void printArray2D(int** list, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << list[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int list1[2][2] = { {1,2},{3,4} };
int row1 = sizeof(list1) / sizeof(list1[0]);
int col1 = sizeof(list1[0]) / sizeof(list1[0][0]);
printArray2D(list1, row1, col1);
return 0;
}
| Your array is actually flat, meaning that you have to cast its type to int*, not to int**. int** refers to array of pointers to int arrays, but you have no pointers inside array.
In other words you have actually 1-dimensional array of ints (flat). Any C multi-dimensional array like int a[3][5] or int a[3][5][7] are all flat array, 1-dimensional in nature. [3][5] array points to contiguous region in memory containing 3 * 5 = 15 ints, and [3][5][7] array points to 3 * 5 * 7 = 105 ints in contiguous region of memory.
Also after casting to int* information about dimensions is lost, hence you have to do indexing arithmetics manually through using [i * col + j]:
Try it online!
#include <iostream>
using namespace std;
void printArray2D(int* list, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << list[i * col + j] << " ";
}
cout << endl;
}
}
int main()
{
int list1[2][2] = { {1,2},{3,4} };
int row1 = sizeof(list1) / sizeof(list1[0]);
int col1 = sizeof(list1[0]) / sizeof(list1[0][0]);
printArray2D((int*)list1, row1, col1);
return 0;
}
Output:
1 2
3 4
Actually there is a C++ specific solution using templates that can be used to keep information about dimensions and forward this information to function, then you don't have to use manual indexing arithmetics:
Try it online!
#include <iostream>
using namespace std;
template <int Rows, int Cols>
void printArray2D(int const (&list)[Rows][Cols]) {
for (int i = 0; i < Rows; i++) {
for (int j = 0; j < Cols; j++) {
cout << list[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int list1[2][2] = { {1,2},{3,4} };
int row1 = sizeof(list1) / sizeof(list1[0]);
int col1 = sizeof(list1[0]) / sizeof(list1[0][0]);
printArray2D(list1);
return 0;
}
Output:
1 2
3 4
Another nice solution in case if you have fixed multi-dimensional array is by using std::array. Then you don't need to forward any dimensions information, just use .size() method of std::array:
Try it online!
#include <iostream>
#include <array>
template <typename ArrT>
void printArray2D(ArrT const & list) {
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list[i].size(); j++) {
std::cout << list[i][j] << " ";
}
std::cout << std::endl;
}
}
int main()
{
std::array<std::array<int, 2>, 2> list1 =
{ std::array{1,2}, std::array{3,4} };
printArray2D(list1);
return 0;
}
Output:
1 2
3 4
|
69,962,916 | 69,962,984 | Find the maximum and minimum element in an array | In this question i can't find the error everything seems correct to me, i am sorting the array using Quick Sort but the sorting algorithm is not working , so that i can find the max and min
#include <iostream>
#include <vector>
using namespace std;
void swap(int *a, int *b){
int t = *a;
*a = *b;
*b = t;
}
int partition(vector<int> arr ,int low, int high){
int pivot = arr[high];
int i = low-1;
for (int j=low; j<=high; j++){
if(arr[j]<pivot){
i++;
swap(&arr[i],&arr[j]);
}
}
swap(&arr[i+1],&arr[high]);
return (i+1);
}
void quickSort(vector<int> arr, int low, int high){
if(low<high){
int pi = partition(arr,low,high);
quickSort(arr,low,pi-1);
quickSort(arr,pi+1,high);
}
}
int main()
{
vector<int> arr = {5,2,3,4,1};
int arr_size = arr.size();
quickSort(arr,0,arr_size-1);
cout<<"The minimum and maximum array is \n";
cout<<arr[0]<<" "<<arr[arr_size-1];
return 0;
}
| In quicksort() and partition():
int partition(vector<int> arr ,int low, int high){
int pivot = arr[high];
int i = low-1;
for (int j=low; j<=high; j++){
if(arr[j]<pivot){
i++;
swap(&arr[i],&arr[j]);
}
}
swap(&arr[i+1],&arr[high]);
return (i+1);
}
void quickSort(vector<int> arr, int low, int high){
if(low<high){
int pi = partition(arr,low,high);
quickSort(arr,low,pi-1);
quickSort(arr,pi+1,high);
}
}
You pass vector<int> arr by value, which means the compiler will make a copy of arr, not changing the actual value of arr.
You have to pass by reference instead:
int partition(vector<int> &arr ,int low, int high){
int pivot = arr[high];
int i = low-1;
for (int j=low; j<=high; j++){
if(arr[j]<pivot){
i++;
swap(&arr[i],&arr[j]);
}
}
swap(&arr[i+1],&arr[high]);
return (i+1);
}
void quickSort(vector<int> &arr, int low, int high){
if(low<high){
int pi = partition(arr,low,high);
quickSort(arr,low,pi-1);
quickSort(arr,pi+1,high);
}
}
But, you can also use std::sort instead. In main():
int main()
{
std::vector<int> arr = {5,2,3,4,1};
int arr_size = (int)arr.size();
std::sort(arr.begin(), arr.end());
std::cout<<"The minimum and maximum array is \n";
std::cout<<arr[0]<<" "<<arr[arr_size-1];
return 0;
}
But the "sorting" solution, in general, is inefficient. You should use std::minmax_element instead:
int main()
{
std::vector<int> arr = {5,2,3,4,1};
auto result = std::minmax_element(arr.begin(), arr.end());
std::cout<<"The minimum and maximum array is \n";
std::cout<< *result.first <<' '<< *result.second;
return 0;
}
|
69,963,212 | 69,966,062 | Is there any practical difference between an inline function having internal and external linkage, with compiler optimization? | If a function is static inline, inline here works only as a suggestion. With either static or static inline the function has internal linkage, and the compiler knows this function cannot be called outside of the translation unit. Thus possibly no symbol is emitted for this function with compiler optimization.
In case of inline functions with external linkage, the C++ standard document at 7.1.2.4 states,
An inline function shall be defined in every translation unit in which
it is odr-used and shall have exactly the same definition in every
case. If the definition of a function appears in a translation unit
before its first declaration as inline, the program is ill-formed. If
a function with external linkage is declared inline in one translation
unit, it shall be declared inline in all translation units in which it
appears; no diagnostic is required. An inline function with external
linkage shall have the same address in all translation units. ...
which is different from C where, when an inline function "has external linkage and is referenced, an external definition has to appear in another translation unit; the inline definition and the external definition are distinct and either may be used for the call (6.7.4.8)".
On the other hand an inline function in a C++ program must be inline in every translation unit and have the same definition. When the compiler sees an extern inline function, it knows that when this function is called in another translation unit, there will be an identical definition provided in that same translation unit, so the compiler can possibly "inline" it with no symbol output.
So to my understanding, in case of C++, there should be no difference in object code output between static inline and extern inline under optimization. Is this correct?
| The important distinction here is that functions with internal linkage in various translation units are different functions, while inline function definitions with external linkage in various translation units all define the same function. This can certainly affect generated code, if only in that if a symbol is emitted (because, for instance, a pointer to the function is stored), external linkage it makes it a weak rather than local symbol.
However, the more significant difference is the possibility for ODR violations if “a” static inline function f is defined in a header file: any multiply-defined entity (e.g., a function template in a header file that is included more than once) that uses f is invalid because each definition uses a different f.
|
69,963,329 | 69,963,362 | C++ 20 Concepts/Requires clauses | I would be really grateful if somebody could explain how C++ 20+ compilers (MSVC 2022 in my case) are able to compile the following, why does the Simple concept have no effect?
template <typename T>
concept Simple = requires(T t)
{
std::is_trivial_v<T> == true;
};
void foo(Simple auto s) {
std::cout << "bar";
}
int main(int argc, char** argv)
{
using Bytes = std::span<std::byte>;
Bytes b;
static_assert(false == std::is_trivial_v<Bytes>);
foo(b); //compiles and prints "bar"
}
| template <typename T>
concept Simple = requires(T t)
{
std::is_trivial_v<T> == true;
};
This checks if expression std::is_trivial_v<T> == true is well-formed, ignoring its value.
To check if the expression is truthy, add a nested requires:
template <typename T>
concept Simple = requires(T t)
{
requires std::is_trivial_v<T>/* == true*/;
};
Or just put it outside of requires:
template <typename T>
concept Simple = std::is_trivial_v<T>;
|
69,963,353 | 69,963,608 | difference between using a template function type and std::function | I am curious as to why a2 is fine, but b2 won't compile:
#include <functional>
#include <iostream>
class A {
public:
A(std::function<void(int)>&& func) : f(std::move(func)) {}
std::function<void(int)> f;
};
template <class F>
class B {
public:
B(F&& func) : f(std::move(func)) {}
F f;
};
int main() {
int a = 1;
auto f = [a](int b){std::cout << a+b << '\n';};
A a1([a](int b){std::cout << a+b << '\n';});
A a2(f);
B b1([a](int b){std::cout << a+b << '\n';});
// B b2(f);
a1.f(2);
a2.f(2);
b1.f(2);
// b2.f(2);
f(2);
}
| A(std::function<void(int)>&& func)
A can be initialized with std::function rvalue. Now, f (in main) is not a std::function, seeing as each lambda has its own distinct type. But we can create a temporary std::function out of it, and bind the rvalue reference func to that.
B(F&& func)
Don't let appearances fool you. This may look like a forwarding reference, but it isn't. Forwarding references are syntactically rvalue reference to a template parameter, but it must be a template parameter of the function we are forwarding into.
The constructor of B is not a template, and so func is not a forwarding reference.
The deduction guide that gets generated from that constructor accepts only rvalues, and deduces F from that. Because f (the local lambda in main) is an lvalue, it cannot bind to an rvalue reference and so CTAD cannot succeed. Indeed std::move(f) will make b2 well-formed.
If you want to accept lvalues for arguments as well, you may add another constructor
B(F const& func) : f(func) {}
Now there are two deduction guides being generated, one for each value category.
|
69,963,443 | 69,963,558 | Why does this c++ template need reference? | I try to print the type using specilization, but this doesn't work.
template<typename T>
struct print_type {
static constexpr char const value[] = "unknown";
};
template<>
struct print_type<void> {
static constexpr char const value[] = "void";
};
template<>
struct print_type<int> {
static constexpr char const value[] = "int";
};
int main() {
cout << print_type<void>::value << endl;
}
The compiler shows:
Undefined symbols for architecture x86_64:
"print_type<void>::value", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
| Short answer: You need to activate C++17 or upgrade your compiler
Long answer: Even constexpr variables need a defenition. When you ODR-use a constexpr variable, you need to add the definition for it.
In C++17, constexpr variables part of a class-type definition are inline by default. Inline variable generate their definition like an inline function.
If you cannot have C++14, you need an out of line definition.
|
69,963,445 | 70,183,422 | Safe Memory allocation during a c++ parallel algorithms invocation (with Intel TBB)? | I would like to understand whether a memory allocation inside a function which a thread executes is safe for the c++ parallel algorithms. Consider the following situation:
std::for_each(std::execution::par, first, last, func),
with func being the function object. During a call to func (CPU and GPU) memory is allocated. When too many threads execute and allocate memory, the system would run out of memory and throw an exception. So far, this has not happened. I wonder if I was merely lucky or whether the execution policy considers such memory constraints or catches memory-related exceptions? The parallel algorithm is implemented through Intel TBB.
| You can use tasks instead of threads as Intel oneTBB works on tasks instead of low-level threads that is, it creates tasks instead of thread and it will map these tasks onto hardware at runtime.
The Task scheduler takes care of mapping the tasks onto threads.
You should explicitly free the memory space when we use for_each in the source code as suggested by Jerome Richard.
|
69,963,665 | 69,965,546 | Writing and Reading boost Property Tree From/To File? | I want to write a boost::property_tree::ptree binary to a file, and read it out again into a ptree.
Since i´m not very comfort with the ptree and binary writing/reading them.. I thought you guys can lead me into the right direction.
Writing strings, int/float/double isn´t that great problem, but how to store a whole ptree (with unknown keys and values, so it is generic) to a file and read it back in cpp using if-/ofstream?
The Filer Extention will be "*.tgasset" and the File will contain more than the ptree as data.
To make things easier to me.. these are my dummy functions to write/read the data:
void TGS_File::PTreeToFile(std::ofstream &_file, boost::property_tree::ptree _data) {
}
boost::property_tree::ptree TGS_File::PTreeFromFile(std::ifstream &_file) {
boost::property_tree::ptree _data;
return _data;
}
(done that with strings, ints, floats and doubles the same way)
| You will have to select a format: INI, Json, XML or INFO. Each has their own set of limitations: https://www.boost.org/doc/libs/1_77_0/doc/html/property_tree/parsers.html
E.g. if you choose JSON:
#include <boost/property_tree/json_parser.hpp>
void TGS_File::PTreeToFile(std::ofstream &_file, boost::property_tree::ptree _data) {
write_json(_file, _data);
}
boost::property_tree::ptree TGS_File::PTreeFromFile(std::ifstream &_file) {
boost::property_tree::ptree _data;
read_json(_file, _data);
return _data;
}
The procedure is 99% the same for other formats. Roughly speaking (from memory) I suppose the INFO format loses the least amount of information over a roundtrip.
|
69,963,867 | 69,966,587 | Expand FindModule.cmake logic with a wrapper file | There are a lot of libraries' packages which do not provide a CMake config file, and in order to find and use them with cmake, one would have to resort to using a FindPackage.cmake script. Some scripts (i.e. SDL) are available within the cmake itself, so finding a package is relatively easy.
Though in my case, SDL-searching scripts (SDL, SDL_image, SDL_mixer) are available almost since the dawn of modern cmake (at least 3.1), they do not provide the means for the modern approach - they do not define imported cmake Targets. SDL as a target is available only since 3.19, and it does not define IMPORTED_LOCATION property.
So, the logical thing is to define those targets and properties.
A naive approach would possibly be to just copy the contents of FindSDL.cmake from a newer cmake bundle and paste it with modifications.
But I would like to keep those files from a cmake bundle (or another good enough script from external source) intact and just wrap them.
So, the main CMakeLists.txt would be like:
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/modules")
find_package(SDL REQUIRED)
find_package(SDL_mixer REQUIRED)
find_package(SDL_image REQUIRED)
cmake/modules/FindSDL.cmake:
find_package(SDL REQUIRED)
if (NOT TARGET SDL::SDL)
# add target and properties here
endif()
However, the way I wrote it will not work because of the endless recursion.
How could I resolve the endless recursion with find_package when writing a wrapper FindPackage.cmake that uses the original FindPackage.cmake file?
This looks promising:
How to execute CMake's default find module from my own find module with the same name?
| The first thing that comes to mind is to delete the current path from CMAKE_MODULE_PATH before calling find_package(), and then restore it.
list(REMOVE_ITEM CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
find_package(SDL)
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})
if (NOT TARGET SDL::SDL)
# add target and properties here
endif()
|
69,964,575 | 69,964,740 | What is the type of a vector that stores a vector of one function and one vector of std::string | I am trying to figure a thing out right now and I can't, I need to find a type for this
(python)
def fn1(hello: list[str]) -> None:
pass
mv = [(fn1, ("1", "hello", "12", "no")), (fn1, ("w", "ufewef", "1ee", "no"))] # any size
what is a C++ type for mv? (doesn't matter if it's mutable or not)
I tried std::vector<std::vector<std::string, std::function>> but it kelp throwing an error, is there a way to do it or will have to use two vectors?
| These types get complicated, so to make them shorter I'll first define a couple of type alias:
using StringVec = std::vector<std::string>;
using StringVecFunc = std::function<void(const StringVec&)>;
Now the type of your data container could be any of these:
using T1 = std::vector<std::tuple<StringVecFunc, StringVec>>;
using T2 = std::vector<std::pair<StringVecFunc, StringVec>>;
struct StringVecFuncAndArgs {
StringVecFunc func;
StringVec args;
};
using T3 = std::vector<StringVecFuncAndArgs>;
The big difference is how you access elements of the thing holding one function and one string-container (like the python tuples). For std::tuple you use std::get<0>(t) and std::get<1>(t) or std::get<StringVecFunc>(t) and std::get<StringVec>(t). For std::pair you use p.first and p.second. For the custom struct you use data.func and data.args.
The tuple solution is maybe the most direct translation from the idea of a Python tuple. The pair is quick and easy if it doesn't need to be used from a lot of code. The custom struct solution takes the most work, but lets you give helpful names to the members.
|
69,964,741 | 69,964,816 | How to get same lines in c++ | I have a text file with IP addresses in it. For example,
I used vector but I confused, i can't. I tried for loop but it was not work because of i am used while in first.
192.168.4.163
192.168.4.163
192.168.4.163
192.168.6.163
192.168.6.163
In output I would like to write
192.168.4.163 => 3 times 192.168.6.163 => 2 times
How can I do that?
#include<stdlib.h>
#include<iostream>
#include<cstring>
#include<fstream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
ifstream listfile;
listfile.open("log.txt");
ofstream codefile;
codefile.open("Code.txt");
ifstream readIp;
string ipLine;
readIp.open("Code.txt");
string temp;
while(listfile>>temp) //get just ips
{
codefile<<temp<<endl;
listfile>>temp;
getline(listfile, temp);
}
listfile.close(); //closed list
codefile.close(); //closed just ip list file
vector <string> currentSet;
while(getline(readIp, ipLine))
{
ipLine.erase(std::remove(ipLine.begin(), ipLine.end(), '"'), ipLine.end()); //removed "
currentSet.push_back(ipLine);
cout << ipLine + " Number of logged on : x" << endl;
}
readIp.close();
return 0;
}
| You can simplify your program by using std::map as shown below:
#include <iostream>
#include <map>
#include <sstream>
#include <fstream>
int main() {
//this map maps each word in the file to their respective count
std::map<std::string, int> stringCount;
std::string word, line;
int count = 0;//this count the total number of words
std::ifstream inputFile("log.txt");
if(inputFile)
{
while(std::getline(inputFile, line))//go line by line
{
std::istringstream ss(line);
//increment the count
stringCount[line]++;
}
}
else
{
std::cout<<"File cannot be opened"<<std::endl;
}
inputFile.close();
std::cout<<"Total number of unique ip's are:"<<stringCount.size()<<std::endl;
//lets create a output file and write into it the unique ips
std::ofstream outputFile("code.txt");
for(std::pair<std::string, int> pairElement: stringCount)
{
std::cout<<pairElement.first<<" => "<<pairElement.second<<" times "<<std::endl;
outputFile<<pairElement.first<<" => "<<pairElement.second<<" times \n";
}
outputFile.close();
return 0;
}
The program can be executed and checked here.
|
69,964,985 | 69,966,713 | 2D Matrix Multiplication in C++ | I want to write a function which allows us to do multiplication of 2 2D matrices. This function has the following parameters as inputs: list1 and list2 are 2D arrays. They are transferred to the function as pointers. Row1, col1, row2, col2 are int values for the size of list1 and list2.
When I have square matrices for the inputs I get correct results. For example; list1[2][2] = {1,2,3,4} and list2[2][2] = {1,2,3,4} gives the result {7,10,15,22}.
When I don't use square matrices I don't get correct results. For example; list1[2][1] = {1,2} and list2[1][2] = {1,2} gives the result {1,4,4,0} which is wrong and list1[2][1] = {1,2} and list2[1][2] = {1,2} gives a garbage value instead of a scalar number.
EDIT : Fixed the returning pointer problem but I still don't get the correct result
#include <iostream>
using namespace std;
void printArray2D(int* list, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
cout << list[i * col + j] << " ";
}
cout << "" << endl;
}
}
int* matrixMultiplication(int* list1, int* list2, int row1, int col1, int row2, int col2) {
if (col1 != row2) {
cout << "Array sizes don't match";
return NULL;
}
else {
int* newList = new int[5];
newList[0] = 0;
newList[1] = 0;
newList[2] = 0;
newList[3] = 0;
newList[4] = 0;
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
for (int k = 0; k < col1; k++) {
newList[i * col1 + j] = newList[i * col1 + j] + list1[i * col1 + k] * list2[k * col1 + j];
}
}
}
return newList;
}
}
int main()
{
int list1[2][1] = {1,2};
int list2[1][2] = {1,2};
int row1 = sizeof(list1) / sizeof(list1[0]);
int col1 = sizeof(list1[0]) / sizeof(list1[0][0]);
int row2 = sizeof(list2) / sizeof(list2[0]);
int col2 = sizeof(list2[0]) / sizeof(list2[0][0]);
int* result = matrixMultiplication((int*)list1, (int*)list2, row1, col1, row2, col2);
printArray2D((int*)result, row1, col2);
return 0;
}
| I wouldn't mix in one function two entirely different matters, a memory allocation and a matrix-matrix multiplication!
I would do C = A * B like this:
bool matrixMultiplication(int* C, int* A, int * B, int rowA, int colA, int rowB, int colB) {
if (colA != rowB) return true;
for (int i = 0; i < rowA; i++)
for (int j = 0; j < colB; j++)
for (int k = 0; k < colA; k++)
C[i*colB + j] += A[i*colA + k] * B[k*colB + j];
return false;
}
so, in the main script have something like this:
bool error = matrixMultiplication( /* parameters */ );
if ( error ) {
std::cout << "invalid matrix dimensions" << std::endl;
return 0;
}
It is generally a VERY BAD idea to hide memory allocations under routines in this way! Design the code better by separation of concerns. The scope of the routine is to multiply two matrices A and B, and store results to C.
Note:
Make sure that all values under C are set to zero, in advance!
We have a disagreement in our choices about this line: C[i*colB + j] += A[i*colA + k] * B[k*colB + j];
|
69,965,301 | 70,159,293 | C++ modules filesystem and iostream crashes g++ | I have the following program:
import <iostream>;
import <filesystem>;
namespace fs = std::filesystem;
int main(int argc, char* argv[]){
fs::path input = "./";
std::cout << input;
return 0;
}
I compile it with (g++ version 11.1.0):
g++ -c -std=c++20 -fmodules-ts -x c++-system-header filesystem iostream
g++ -std=c++20 -fmodules-ts -o test test.cpp
And I receive a very cryptic message:
during RTL pass: expand
In file included from /usr/include/c++/11.1.0/string:55,
from /usr/include/c++/11.1.0/stdexcept:39,
from /usr/include/c++/11.1.0/system_error:41,
from /usr/include/c++/11.1.0/bits/fs_fwd.h:35,
from /usr/include/c++/11.1.0/filesystem:44,
of module /usr/include/c++/11.1.0/filesystem, imported at test.cpp:2:
/usr/include/c++/11.1.0/bits/basic_string.h: In static member function ‘static std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::_S_to_string_view(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::__sv_type) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’:
/usr/include/c++/11.1.0/bits/basic_string.h:126:16: internal compiler error: in make_decl_rtl, at varasm.c:1418
126 | { return __svt; }
| ^~~~~
0x1797368 internal_error(char const*, ...)
???:0
0x67f8f9 fancy_abort(char const*, int, char const*)
???:0
0xa1cdef expand_expr_real_1(tree_node*, rtx_def*, machine_mode, expand_modifier, rtx_def**, bool)
???:0
0xa26f9f store_expr(tree_node*, rtx_def*, int, bool, bool)
???:0
Please submit a full bug report,
with preprocessed source if appropriate.
Please include the complete backtrace with any bug report.
See <https://bugs.archlinux.org/> for instructions.
What puzzles me is, that upon removing iostream and the std::cout line, the program compiles just fine.
Also if I switch from import to the old-fashioned #include the program works just fine.
Am I importing the modules wrong?
Is this a compiler bug?
| Compiler support for modules is still in its early days. But if a header fails compiling as a header unit, then you can still include it instead:
import <iostream>;
#include <filesystem>
namespace fs = std::filesystem;
int main(int argc, char* argv[]){
fs::path input = "./";
std::cout << input;
return 0;
}
This is probably the best we can do for now. You might also try out precompiled headers in the meantime if your dependency list grows out of hand.
|
69,965,599 | 69,965,662 | How to add a static library permanently to the Ubuntu system? | Hi everybody I recently created a C++ project in which I put my code into header.h and header.cpp files and successfully create a static library called header.a. Now I put my header.h file into /usr/local/include position of my system and header.a into /usr/local/lib in order to "install" my library into the machine. Now, if I want to use this library, I have to do the following steps:
Suppose I am using a main.cpp program, I include this line at the top of the program:
include <header.h>
Then, I compile with this command:
g++ main.cpp /usr/local/lib/header.a
And all it's ok. But I want to find a way to "store" permanently the header.a library into the system in order to use it like a normal standard C++ header, simplifing the compilation in this way:
g++ main.cpp
Is there a way to do this? Many thanks to all.
| You can't, and no system library will be linked automatically without being told to do so.
You can however add the path /usr/local/lib to the default paths for the linker to look for libraries (IIRC it's not in there by default for Ubuntu), which means you only need to add the -l (lower-case L) option to link with the library.
But do note that the library should be having a lib prefix. Like in libheader.a.
Then link with -lheader:
g++ main.cpp -lheader
There also the -L option to add a path to the list of paths that the linker searches, if you have other non-standard paths, of if you can't edit the system configuration to use /usr/local/lib:
g++ main.cpp -L/usr/local/lib -lheader
The library file still needs the lib prefix.
|
69,965,664 | 69,965,683 | How can I desc order in vectors C++ | I have C++ code like below.
It works well but my output like this :
192.168.1.163 => 4 times
192.168.1.165 => 7 times
192.168.1.20 => 62 times
How can I make desc order like :
192.168.1.20 => 62 times
192.168.1.165 => 7 times
192.168.1.163 => 4 times
std::map<std::string, int> stringCount; //str is ip and int is logged count
while(std::getline(readIp, ipLine))//go line by line
{
std::istringstream ss(ipLine);
ipLine.erase(std::remove(ipLine.begin(), ipLine.end(), '"'), ipLine.end()); //removed "
stringCount[ipLine]++; //increment the count
}
readIp.close();
std::cout<<"Total number of ip's are logged on the system :"<<stringCount.size()<<std::endl;
std::ofstream outputFile("times.txt");
for(std::pair<std::string, int> pairElement: stringCount)
{
std::cout<<pairElement.first<<" => "<<pairElement.second<<" times "<<std::endl;
outputFile<<pairElement.first<<" => "<<pairElement.second<<" times \n";
}
| Since it is not possible to sort a std::map by its values you can use something like a std::vector as shown below. The program below writes the ip addresses in decreasing order of count values as you want.
#include <iostream>
#include <map>
#include <sstream>
#include <fstream>
#include <vector>
#include <algorithm>
//create a function that will be used as comparator
bool sortInDecreasingOrder(std::pair<std::string, int> const &a, std::pair<std::string, int> const &b)
{
return a.second > b.second;
}
int main() {
//this map maps each word in the file to their respective count
std::map<std::string, int> stringCount;
std::string word, line;
int count = 0;//this count the total number of words
std::ifstream inputFile("log.txt");
if(inputFile)
{
while(std::getline(inputFile, line))//go line by line
{
std::istringstream ss(line);
//increment the count
stringCount[line]++;
}
}
else
{
std::cout<<"File cannot be opened"<<std::endl;
}
inputFile.close();
std::cout<<"Total number of unique ip's are:"<<stringCount.size()<<std::endl;
//since we cannot sort a std::map by its second value we can create a vector and sort that vector
std::vector<std::pair<std::string, int>> vec(stringCount.begin(), stringCount.end());
//now you can sort this vector
std::sort(vec.begin(), vec.end(), sortInDecreasingOrder);
//lets create a output file and write into it the unique ips
std::ofstream outputFile("code.txt");
for(std::pair<std::string, int> pairElement: vec)//note this time we go through vector vec instead of map
{
std::cout<<pairElement.first<<" => "<<pairElement.second<<" times "<<std::endl;
outputFile<<pairElement.first<<" => "<<pairElement.second<<" times \n";
}
outputFile.close();
return 0;
}
The output of the program can be seen here.
|
69,965,676 | 69,965,764 | Why am I getting error while using the Boost Library in C++? | I am using the c++ boost library in one code to get large numbers in output.
My code is:
#include <iostream>
#include<cmath>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int main()
{
int a;
cout<<"Enter the value for a:";
cin>>a;
for(int x =1;x<=a;x++)
{
int128_t ans = pow(a,2*x)-pow(a,x)+1;
cout<<ans<<endl ;
}
return 0;
}
But after running this, I am getting following error:
prog.cc: In function 'int main()':
prog.cc:14:43: error: conversion from '__gnu_cxx::__promote_2<int, int, double, double>::__type' {aka 'double'} to non-scalar type 'boost::multiprecision::int128_t' {aka 'boost::multiprecision::number<boost::multiprecision::backends::cpp_int_backend<128, 128, boost::multiprecision::signed_magnitude, boost::multiprecision::unchecked, void> >'} requested
14 | int128_t ans = pow(a,2*x)-pow(a,x)+1;
| ~~~~~~~~~~~~~~~~~~~^~
What is the reason for such an error?
| The reason is that ans type is not int128_t.
After changing ans type to auto compilation works fine:
cat boost_error.cpp
#include <iostream>
#include<cmath>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int main()
{
int a;
cout<<"Enter the value for a:";
cin>>a;
for(int x =1;x<=a;x++)
{
auto ans = pow(a,2*x)-pow(a,x)+1;
cout<<ans<<endl ;
}
return 0;
}
g++ boost_error.cpp
a.out
Enter the value for a:3
7
73
703
g++ --version
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
69,965,989 | 69,966,393 | Function template accepting only non integral types (specifially bidirectional iterators) | I need a function template that only accepts non-integral types, if the arguments are iterators i made (i made my own class and using enable_if and a tag i manage to deduce whether or not the params are the iterators I created or not)
template <typename InputIterator>
foo (InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type(),
typename ft::enable_if<InputIterator::InputIter, InputIterator>::type = NULL)
{
insert(begin(), first, last);
}
I want to make sure the parameters passed to the function are either my own iterator or a bidirectional iterator, however i thought this would be much easier if i could just check if the "InputIterator" is simply non integral but i dont know what is needed precisely to implement it, and am not sure if its a good idea since at the end of the day, what i really need is to make sure its an iterator that fits my criterias.
How should i proceed ? what functions are worth looking into ?
am using -std=c++98, so am sticking to the c++98 libraries, so no c++11 or any functionality that came out after 98.
| Since you are limited to C++98 it is best to try animate SFINAE tools available in later versions c++03. This way code will be more familiar for future maintainer.
For example C++98 do not have following tools: std::enable_if, std::iterator_traits std::is_integral.
Your case is quite simple, so it is not hard, but lots of boiler plate is needed:
#include <numeric>
template <typename T>
struct is_integer {
static const bool value = false;
};
template <>
struct is_integer<int> {
static const bool value = true;
};
template <>
struct is_integer<char> {
static const bool value = true;
};
template <>
struct is_integer<long int> {
static const bool value = true;
};
template <>
struct is_integer<unsigned int> {
static const bool value = true;
};
template <>
struct is_integer<unsigned char> {
static const bool value = true;
};
template <>
struct is_integer<unsigned long int> {
static const bool value = true;
};
template <bool codition, typename T = void>
struct enable_if {};
template <typename T>
struct enable_if<true, T> {
typedef T type;
};
template <typename T>
struct iterator_traits {
typedef typename T::value_type value_type;
};
template <typename T>
struct iterator_traits<T*> {
typedef T value_type;
};
template <typename InputIterator>
typename enable_if<
is_integer<
typename iterator_traits<InputIterator>::value_type
>::value,
typename iterator_traits<InputIterator>::value_type
>::type
foo(InputIterator first, InputIterator last) {
typedef typename iterator_traits<InputIterator>::value_type type;
return std::accumulate(first, last, type(0));
}
void test() {
int arr[3] = {1, 3, 4};
foo(arr, arr + 3);
}
#ifdef TEST_FAILURE
void test_faiure() {
double arr[3] = {1, 3, 4};
foo(arr, arr + 3);
}
#endif
live demo small improvment
I didn't check what was the status of boost for C++98 (especially that you didn't specified compiler), but you should check if this is already done there and if it could be used by your compiler.
|
69,966,073 | 69,966,193 | C++ Struct/Class Question - How to create static instances of a struct/class | One of those basic C++ question, my bad.
I'm wondering about you format structs in C++ such that, in this case, I could get math::Vector2::zero to return a Vector2 where both values are 0.f.
namespace math
{
struct Vector2
{
Vector2() { x = 0.f; y = 0.f; }
Vector2(float x_, float y_) { x = x_; y = y_; }
float x, y;
static math::Vector2 zero = math::Vector2(0.f, 0.f); // Error is here
};
};
The error is: error C2027: use of undefined type 'math::Vector2'
and: a member with an in-class initializer must be const
Thanks.
| The message tells you there are 2 distinct errors:
use of undefined type math::Vector2
A member with an in-class initializer must be const.
Fixes:
for 1.: Move definition (assignment) of zero AFTER the declaration of Vector2 is complete. By the way... You MUST define the static variable in a .cpp file, or in the .h file, adding the keyword inline. The value is assigned
for 2.: Make sure you indicate that zero is a constant. Which is fortunately what you want...
This gives:
namespace math
{
struct Vector2
{
Vector2() { x = 0.f; y = 0.f; }
Vector2(float x_, float y_) { x = x_; y = y_; }
float x, y;
static const Vector2 zero; // declaration
};
inline const Vector2 Vector2::zero{}; // definition
}
Have you considered using this simpler (to read) notation instead ?
namespace math
{
struct Vector2
{
Vector2() = default;
Vector2(float x, float y) : x(x), y(y) {}
float x = 0;
float y = 0;
static const Vector2 zero; // declaration
};
inline const Vector2 Vector2::zero{}; // definition
}
constexpr'dness is quite obvious in this case? And here is one correct way to declare/define using constexpr.
namespace math
{
struct Vector2
{
constexpr Vector2() = default;
constexpr Vector2(float x, float y) : x(x), y(y) {}
float x = 0;
float y = 0;
static const Vector2 zero; // declaration, still cannot define
// as constexpr, because Vector2
// is not yet fully declared.
};
inline constexpr const Vector2 Vector2::zero; // definition
}
|
69,966,230 | 69,966,930 | Different result for function resolution on MinGW64 and MSVC | template <typename T>
int get_num(const T&)
{
return 42;
}
struct Foo
{
int i = get_num(*this);
};
int get_num(const Foo&)
{
return 23;
}
int main()
{
std::cout << Foo().i << std::endl; // MinGW64 - 42, MSVC - 23
return 0;
}
MSVC chooses non-template get_num "overload". It will successfully link even if the template is only forward-declared.
MinGW64 will choose the default template implementation. Will fail to link if there is no definition for the template.
Who is right and who is wrong? Whad does the standard say?
However this version yields the same results for both compilers... Why does it not go to infinite recursion?
template <typename T>
int get_num(const T& t)
{
std::cout << "Template version called" << std::endl;
return get_num(t);
}
struct Foo
{
int i = get_num(*this);
};
int get_num(const Foo&)
{
std::cout << "Non-Template version called" << std::endl;
return 23;
}
MSVC output:
Non-Template version called
23
MinGW64 Output:
Template version called
Non-Template version called
23
I think ADL is involved when using MSVC.
| For the first sample, MinGW is correct and MSVC is incorrect: the get_num call can only consider the function template.
This is a question of overload resolution, so I'll start in clause [over]. get_num(*this) is a plain function call expression, so [over.call.func] applies:
In unqualified function calls, the name is not qualified by an -> or . operator and has the more general form of a primary-expression. The name is looked up in the context of the function call following the normal rules for name lookup in function calls. The function declarations found by that lookup constitute the set of candidate functions.
"Name lookup" is discussed in section [basic.lookup]. Paragraph 2:
A name "looked up in the context of an expression" is looked up as an unqualified name in the scope where the expression is found.
One complication here is that the get_num(*this) default member initializer expression doesn't get used by anything until the default constructor of Foo is implicitly defined by its odr-use in main. But the lookup is determined from the code location of the expression itself, no matter that it's used in the process of that implicit definition.
For the second code sample, MinGW is again correct: the apparently recursive call inside the template definition actually calls the non-template function.
This is a result of "two phase lookup" for dependent function calls, described in section [temp.dep.res]. Briefly, since the type of t depends on a template parameter, the name get_num in the expression get_num(t) is considered a dependent name. So for each instantiation of the function template, it gets two ways of finding candidates for overload resolution: the ordinary immediate way which finds the get_num function template, plus another lookup from the point of instantiation. The specialization get_num<Foo> has point of instantiation right after the main() definition, so overload resolution is able to find the non-template from the instantiation context, and the non-template wins overload resolution.
(Argument-dependent lookup is a related tangent issue to this second point. ADL applies to declarations from the instantiation context but not declarations from the definition context. But it's not directly a reason for the behaviors in either example program.)
None of this has changed significantly between C++14 and the latest draft, as far as I can see.
|
69,966,408 | 69,967,773 | I didn't know why my array is displaying wrong numbers. Just want to know why is that so? | Didn't know why my odd array is displaying some large number. I want to print only the odd numbers from the array in a sorted manner.
Like if the array is 1 4 6 8 0 9
Print only 1 9
selectionSort() is just the function that sorts the array.
int main()
{
int T, n, p, size,sum=0,si=0;
cin >> T;
for (int i = 0; i < T; i++)
{
cin >> n;
int a[n];
int odd[n];
for (int j = 0; j < n; j++)
{
cin >> a[j];
}
for (int j = 0; j < n; j++)
{
p = 0;
if (a[j] % 2 != 0){
odd[p++] = a[j];
si++;
}
}
selectionSort(odd, si);
What is wrong here in for loop?
for (int k = 0; k < si; k++)
{
cout << odd[k] << endl;
// sum += odd[j];
}
// cout << sum << endl;
sum = 0;
si=0;
}
return 0;
}
Output is :
1
4
1 5 7 9
9
16
4200276
6422112
Expecting
1
4
1 5 7 9
1
5
7
9
| p=0 is not necessary in the for loop. odd[p++] = a[j] equation always mean odd[0]=a[j]. Put p=0 out of the for loop.
|
69,966,428 | 69,966,496 | How to extract requires clause with two parameter packs into a concept? | I have this (supposedly not so useful) class template with templated constructor which is a candidate for perfect forwarding. I, however, wanted to make sure that the types passed to the constructor are the exact same as the ones specified for the whole class (without cvref qualifiers):
template <typename... Ts>
struct foo {
template <typename... CTs>
requires (std::same_as<std::remove_cvref_t<Ts>, std::remove_cvref_t<CTs>> && ...)
foo(CTs&& ...) {
std::cout << "called with " << (sizeof...(CTs)) << " args\n";
}
};
Now I can make:
auto f = foo<int, int>(1, 1);
and I can't make:
auto f = foo<float, int>(1, 1);
which is good.
But I wanted to extract the requires ... body to a concept:
template <typename... T1s, typename... T2s>
concept same_unqualified_types = (
std::same_as<
std::remove_cvref_t<T1s>,
std::remove_cvref_t<T2s>
> && ...
);
template <typename... Ts>
struct foo {
template <typename... CTs>
requires same_unqualified_types<Ts..., CTs...>
foo(CTs&& ...) { // 16
std::cout << "called with " << (sizeof...(CTs)) << " args\n";
}
};
int main() {
auto f = foo<int, int>(1, 1); // 22
}
But this gives me this error:
main.cpp: In function 'int main()':
main.cpp:22:32: error: no matching function for call to 'foo<int, int>::foo(int, int)'
22 | auto f = foo<int, int>(1, 1);
|
main.cpp:16:5: note: candidate: 'template<class ... CTs> requires same_unqualified_types<Ts ..., CTs ...> foo<Ts>::foo(CTs&& ...) [with CTs = {CTs ...}; Ts = {int, int}]'
16 | foo(CTs&& ...) {
| ^~~
main.cpp:16:5: note: template argument deduction/substitution failed:
main.cpp:16:5: note: constraints not satisfied
main.cpp: In substitution of 'template<class ... CTs> requires same_unqualified_types<Ts ..., CTs ...> foo<int, int>::foo(CTs&& ...) [with CTs = {int, int}]':
main.cpp:22:32: required from here
main.cpp:5:9: required for the satisfaction of 'same_unqualified_types<Ts ..., CTs ...>' [with CTs = {int, int}; Ts = {int, int}]
main.cpp:22:32: error: mismatched argument pack lengths while expanding 'same_as<typename std::remove_cvref<T1s>::type, typename std::remove_cvref<T2s>::type>'
22 | auto f = foo<int, int>(1, 1);
|
I suppose I might be doing something wrong with the concept same_unqualified_types where I'm trying to have two parameter packs. I've tried to test it manually, but it doesn't seem to work, even if I do same_unqualified_types<int, int> or same_unqualified_types<int, int, Pack...>, where Pack... is a parameter pack of two ints.
Where is my logic flawed? Can I extract that requires clause to a concept?
Disclaimer: I know I can achieve something similar with CTAD and deduction guides - without even needing any concepts. I just wish to know where my understanding is flawed.
| Concepts don't get special privileges with regard to template parameter packs. You can't have two packs in a set of template parameters unless there's something to distinguish them in terms of the arguments passed to them (one could be a series of types while the other is a series of values, or you have access to template argument deduction to differentiate them, or something like that).
The best you're going to be able to do is to create an unqualified equivalent of same_as and just use that with pack expansion as needed:
template<typename T, typename U>
concept same_as_unqual = std::same_as<<std::remove_cvref_t<T>, <std::remove_cvref_t<U>>;
template <typename... Ts>
struct foo {
template <typename... CTs>
requires (same_as_unqual<Ts, CTs> && ...)
...
A single concept that does the pair-wise comparison between the parameters just isn't possible. Well, it's possible, but it'd be a lot more verbose, as you would likely need to bundle them in some kind of type-list. I don't think same_as_all<type_list<Ts...>, type_list<Us...>> is better than doing an explicit expansion.
|
69,966,501 | 69,967,239 | Match all GNU C SIMD vector extension types in clang/gcc | The objective is to write a type trait with the following signature:
template<typename T>
struct is_vector : std::true_type / std::false_type
such that you can use is_vector<T>::value in SFINAE signatures. How do I properly detect whether a type is __attribute__((__vector_size(<some_vector_width>)) <some_built-in_type> in GCC/clang?
I looked through the LLVM documentation but couldn't see any built-ins to detect this. The GNU C documentation similarly only documents it as a C extension, not mentioning C++.
The backup plan is to specialize the template for each permutation but that really doesn't sound nice.
| You could create a type trait to check if it's one of these vector types. It was a bit tricky finding a way to do it, but using one of the built-in functions that operates on the vectors seems to work.
In this gcc example, I use __builtin_convertvector to try to convert the vector type to the same vector type. If it's not a vector type, SFINAE will select the test() function that returns false_type. If it is one of the vector types, it'll select the test() function that returns true_type.
#include <type_traits>
template<class T>
struct is_vector {
static std::false_type test(...);
template<class B>
static auto test(B) ->
decltype(__builtin_convertvector(std::declval<B>(), B), std::true_type{});
static constexpr bool value = decltype(test(std::declval<T>()))::value;
};
template<class T>
static constexpr bool is_vector_v = is_vector<T>::value;
Demo
|
69,966,903 | 69,966,971 | How is the inline specifier used in C++ to preserve the one definition rule? | I've been trying to figure out how the inline specifier preserves ODR. So far, with everything I've written it seems unnecessary because include guards ensure that definitions are only included once.
Suppose I have the following definition in a file called constants.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace constants {
inline const double pi { 3.14159255358979323846 };
inline const double e { 2.71828182845904523536 };
}
#endif
From my understanding of inline in relation to the ODR, the inline specifier is written to ensure that the definition of these constants are only initialized once across multiple translation units. So if I include this file in a.cpp and b.cpp everything should be good.
Now, let's remove the inline keyword.
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace constants {
const double pi { 3.14159255358979323846 };
const double e { 2.71828182845904523536 };
}
#endif
Now if I include this in a.cpp and b.cpp no issues. I guess this is because of the include guards which ensure multiple definitions of the same thing don't occur twice.
Next, let's remove the include guards
namespace constants {
const double pi { 3.14159255358979323846 };
const double e { 2.71828182845904523536 };
}
Still no problem. Maybe because const qualified variable definitions have internal linkage by default. As a result, including constants.h in a.cpp and b.cpp makes each of these definitions internal by default to their respective translation units.
Having a hard time breaking ODR across multiple translation units. Let's remove const now.
namespace constants {
double pi { 3.14159255358979323846 };
double e { 2.71828182845904523536 };
}
NOW! ODR is broken across multiple translation units. Let's try fixing this with inline so that the compiler knows to only define these variables once.
namespace constants {
inline double pi { 3.14159255358979323846 };
inline double e { 2.71828182845904523536 };
}
Ok, no more errors, this file can once again be included in multiple translation units. So why is considered "best practice" to declare constants in header files as inline? It seems to take a lot of effort to break ODR and inline is redundant in the presence of include guards.
| Constants that are not declared with the specifier extern have internal linkage.
So all compilation units that include these declarations
namespace constants {
const double pi { 3.14159255358979323846 };
const double e { 2.71828182845904523536 };
}
have their own constants pi and e.
From the C++ 14 Standard (3.5 Program and linkage)
3 A name having namespace scope (3.3.6) has internal linkage if it is
the name of
(3.2) — a variable of non-volatile const-qualified type that is
neither explicitly declared extern nor previously declared to have
external linkage; or
Opposite to the above declarations these declarations
namespace constants {
double pi { 3.14159255358979323846 };
double e { 2.71828182845904523536 };
}
have external linkage. So the compiler issues an error if these declarations (that are also definitions) are included in more than one compilation unit because the one definition rule is broken.
You could make the above variables to have the internal linkage if you declare them in an unnamed namespace as for example
namespace constants {
namespace {
double pi { 3.14159255358979323846 };
double e { 2.71828182845904523536 };
}
}
As for these declarations
namespace constants {
inline double pi { 3.14159255358979323846 };
inline double e { 2.71828182845904523536 };
}
then inline variables with external linkage may be defined in more than one compilation unit. Moreover an inline variable shall be defined in each compilation unit where it is ODR-used.
|
69,967,084 | 69,967,945 | How to set the severity level of Boost log library | I have been successfully using the Boost Log library in my project. In other words, I am emitting log messages via BOOST_LOG_TRIVIAL(info) << "My message";
Now I want to control the severity of logging, and I followed the example from the Boost Log library documentation:
#include <boost/log/trivial.hpp>
#include <boost/log/core.hpp>
namespace logging = boost::log;
void init()
{
logging::core::get()->set_filter
(
logging::trivial::severity >= logging::trivial::info
);
}
However, I am getting this compilation error:
main.cpp:22:25: error: ‘severity’ is not a member of ‘boost::log::v2s_mt_posix::trivial’
22 | logging::trivial::severity >= logging::trivial::info
Here is the relevant section of my CMakeLists.txt:
SET(Boost_USE_STATIC_LIBS ON)
find_package(Boost 1.71 COMPONENTS log graph REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})
add_executable(ls_router main.cpp)
target_link_libraries(ls_router PUBLIC ${Boost_LIBRARIES} pthread)
I am on Ubuntu and installed Boost via sudo apt install libboost-all-dev.
dpkg -l | grep libboost-log
ii libboost-log-dev 1.71.0.0ubuntu2 amd64 C++ logging library (default version)
ii libboost-log1.71-dev 1.71.0-6ubuntu6 amd64 C++ logging library
ii libboost-log1.71.0 1.71.0-6ubuntu6 amd64 C++ logging library
According to this SO question, this might be a CMake configuration issue.
Boost.Log with CMake causing undefined reference error. However, none of the suggestions in the question solved my issue.
| The severity keyword is defined in boost/log/detail/trivial_keyword.hpp. Apparently it's not being included.
The minimal set of includes I could find:
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
namespace logging = boost::log;
void init()
{
logging::core::get()->set_filter(logging::trivial::severity >=
logging::trivial::info);
}
int main() { init(); }
According to this SO question, this might be a CMake configuration issue
That's about linker errors, which this isn't.
|
69,967,116 | 69,967,783 | Decimal to Binary Converting Years in C++ | I wrote a program that converts decimal numbers (date of birth) to binary. Converting the day and month works smoothly, but when it comes to converting the year a problem occurs, for example 2001 is converted to 2521075409 instead of 11111010001. Could you tell me where the problem is?
{
int i;
long long temp, bin;
i = 1;
bin = 0;
printf("Number %d in binary: \n", year);
while (year > 0) {
temp = year % 2;
year /= 2;
bin += temp * i;
i *= 10;
}
printf("%lld\n\n",bin);
}
| With int i;, i *= 10 quickly reaches the max limit for 32-bit integer 0x7fff'ffff. So i will also need to be 64-bit, it can be unsigned so the ceiling is a bit higher at 0xffff'ffff'ffff'ffff. Example
unsigned long long i = 1;
unsigned long long bin = 0;
int year = 2001;
while (year > 0)
{
int temp = year % 2;
year /= 2;
bin += temp * i;
i *= 10;
printf("check i: %llu\n", i);
}
printf("%016llu\n\n", bin);
To print larger numbers use a character buffer to save temp in each iteration.
|
69,967,145 | 69,967,691 | Why does my code say that it has an incomplete type even after I tried declaring it? | I am writing a program that displays a number of students test scores in the form of a table and then calculates and displays the average. Upon running the code, I get the following errors(also pictured below):
variable has incomplete type
'struct students'
struct students st[50];
^
note: forward declaration of 'students'
struct students st[50];
I have declared students and have tried declaring st and I am just not sure what the problem is. Below is a typed version and a screenshot of my code:
#include <iostream>
using namespace std;
int Main()
{
int students;
struct students st[50];
return 0;
}
Code errors
Picture of typed code
| You have to define it first. You can also use this style.
struct student{
...
};
int main{
student* st[50];
for(int i=0; i<50;i++)
st[i]=new student;
return 0;
}
|
69,967,228 | 69,967,297 | Read access violation when trying to create copy constructor for linked list | I am having an issue in regards with my linkedlist implementation, where I am trying to create a copy constructor.
// Copy Constructor
List342(const List342& source)
{
*this = source;
}
List342& operator=(const List342& source)
{
Node<T>* s_node = nullptr; // Source node
Node<T>* d_node = nullptr; // Destination node
if (this == &source)
{
return *this;
}
// Empty memory on destination
DeleteList();
// If the source is empty, return the current object.
if (source.head_ == nullptr)
{
return *this;
}
// Copy source node to destination node, then make destination node the head.
d_node = new Node<T>;
d_node->data = (source.head_)->data;
head_ = d_node;
s_node = (source.head_)->next;
// Loop and copy the nodes from source
while (s_node != nullptr)
{
d_node->next = new Node<T>;
d_node = d_node-> next;
d_node->data = s_node->data;
s_node = s_node->next;
}
return *this;
}
For some reason, VS Studio throws a read access violation at me on the line d_node->data = s_node->data despite the while loop trying to prevent this.
The culprit may be lying in DeleteList, but for some reason my other methods, like printing the linkedlist, have no issues after calling DeleteList, as it prints nothing. I'm just wondering if there's any flaws in this DeleteList method.
// Delete all elements in the linked list
// Not only do you need to delete your nodes,
// But because the Node data is a pointer, this must be deleted too
void DeleteList()
{
// Similar to the linkedlist stack pop method except you're running a while
// loop until you the is empty.
Node<T>* temp;
while (head_ != nullptr)
{
temp = head_;
head_ = head_->next;
// For some reason if I try to delete temp->data, I keep getting symbols not loaded or debug
// assertion errors
// delete temp->data;
// What I can do here is set it to null
// Then delete it. This may have to do how uninitialized variables have random memory assigned
temp->data = nullptr;
delete temp->data;
delete temp;
}
}
Here is the Node definition:
template <class T>
struct Node
{
T* data;
//string* data;
Node* next;
}
| By having Node::data be declared as a pointer, your code is responsible for following the Rule of 3/5/0 to manage the data pointers properly. But it is not doing so. Your copy assignment operator is shallow-copying the pointers themselves, not deep-copying the objects they point at.
Thus, DeleteList() crashes on the delete temp->data; statement, because you end up with multiple Nodes pointing at the same objects in memory, breaking unique ownership semantics. When one Node is destroyed, deleting its data object, any other Node that was copied from it is now left with a dangling pointer to invalid memory.
If you must use a pointer for Node::data, then you need to copy-construct every data object individually using new so DeleteList() can later delete them individually, eg:
d_node = new Node<T>;
d_node->data = new T(*(source.head_->data)); // <--
...
d_node->next = new Node<T>;
d_node = d_node->next;
d_node->data = new T(*(s_node->data)); // <--
...
However, this is no longer needed if you simply make Node::data not be a pointer in the first place:
template <class T>
struct Node
{
T data; //string data;
Node* next;
}
That being said, your copy constructor is calling your copy assignment operator, but the head_ member has not been initialized yet (unless it is and you simply didn't show that). Calling DeleteList() on an invalid list is undefined behavior. It would be safer to implement the assignment operator using the copy constructor (the so-called copy-swap idiom) , not the other way around, eg:
// Copy Constructor
List342(const List342& source)
: head_(nullptr)
{
Node<T>* s_node = source.head_;
Node<T>** d_node = &head_;
while (s_node)
{
*d_node = new Node<T>;
(*d_node)->data = new T(*(s_node->data));
// or: (*d_node)->data = s_node->data;
// if data is not a pointer anymore...
s_node = s_node->next;
d_node = &((*d_node)->next);
}
}
List342& operator=(const List342& source)
{
if (this != &source)
{
List342 temp(source);
std::swap(head_, temp.head_);
}
return *this;
}
However, the copy constructor you have shown can be made to work safely if you make sure to initialize head_ to nullptr before calling operator=, eg:
// Copy Constructor
List342(const List342& source)
: head_(nullptr) // <--
{
*this = source;
}
Or:
// Default Constructor
List342()
: head_(nullptr) // <--
{
}
// Copy Constructor
List342(const List342& source)
: List342() // <--
{
*this = source;
}
Or, initialize head_ directly in the class declaration, not in the constructor at all:
template<typename T>
class List342
{
...
private:
Node<T> *head_ = nullptr; // <--
...
};
|
69,968,309 | 69,968,388 | Searching an array of strings, getting weird return | I am doing a school project to search through an array of strings, where the user enters some characters to search through the array, and is displayed the full name and number that includes those characters. This is working, but when I ask if user wants to search again, the program returns the entire contents of the array. Here is my code:
#include <string>
#include <iostream>
using namespace std;
void findPerson(string, string[], int);
int main(){
const int SIZE = 12;
string searchIn;
string names[SIZE]
{
"Matthew McConaughey, 867-5309",
"Renee Javens, 678-1223",
"Joe Looney, 586-0097",
"Geri Palmer, 223-8787",
"Lynn Presnell, 887-1212",
"Bill Wolfe, 223-8878",
"Sam Wiggins, 486-0998",
"Bob Kain, 586-8712"
"Tim Haynes, 586-7676"
"John Johnson, 223-9037",
"Jean James, 678-4939",
"Ron Palmer, 486-2783"
};
char again = 'Y';
while (toupper(again) == 'Y')
{
cout << "Please enter all or part of a name or number to search: " << endl;
getline(cin, searchIn);
findPerson(searchIn, names, SIZE);
cin >> again;
cout << endl;
}
return 0;
}
void findPerson(string finder, string myArray[], int size) {
bool found = false;
for (int index = 0; index < size; index++) {
if (myArray[index].find(finder) != -1)
{
cout << myArray[index] << endl;
found = true;
}
}
if (!found)
cout << "Nothing matched your search." << endl;
cout << "Would you like to search again? (Y/N): " << endl;
}
I cannot figure out why this is happening, please help.
| Adding
cin.ignore();
Between line 43 and 44 fixes the bug. See the reason why here.
You should try to fix your program without adding this line.
|
69,968,476 | 69,972,494 | Is it possible to concatenate parameters of variadic macro to form a variable name? | I am trying to achieve something like the following:
#define def_name(delim, ...) ??? // how will this variadic macro concatenate its parameters to define a new variable?
// Calling `def_name` as follows should define a new variable.
def_name("_", "abc", "def", "ghi");
// The following code should be generated after invoking the above macro.
inline constexpr char const abc_def_ghi_name[]{"abc_def_ghi"};
// Invoking the macro as:
def_name("", "abc", "def", "ghi");
// should produce the following code:
inline constexpr char const abcdefghi_name[]{"abcdefghi"};
What should the def_name macro be to support the above use-case? Also, can something similar be achieved at compile-time using C++ templates/constexpr?
| With little syntax change (MACRO can stringify, but cannot unstringify), your usage might be:
def_name(, a, b)
def_name(_, a, b, c)
You might do, with some upper bound limit:
#define def_name1(sep, p1) \
inline constexpr char const p1##_name[]{#p1};
#define def_name2(sep, p1, p2) \
inline constexpr char const p1##sep##p2##_name[]{#p1 #sep #p2};
#define def_name3(sep, p1, p2, p3) \
inline constexpr char const p1##sep##p2##sep##p3##_name[]{#p1 #sep #p2 #sep #p3};
// ...
and to dispatch to the correct one, some utilities:
#define COUNT_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define COUNT(...) COUNT_N(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
// Warning: COUNT() return 1 (as COUNT(A)) :-/
#define IDENTITY(N) N
#define APPLY(macro, ...) IDENTITY(macro(__VA_ARGS__))
and finally
#define DISPATCH(N) def_name ## N
#define def_name(sep, ...) IDENTITY(APPLY(DISPATCH, COUNT(__VA_ARGS__)))(sep, __VA_ARGS__)
Demo
|
69,968,882 | 69,968,972 | How to pass only mutex to lock_guard constructor parameter | When declare locker like,
lock_guard Locker(mLocker);
I want the compiler to detect if an mLocker is a mutex.
To implement this, I used concept requires and defined as below.
template <typename T>
concept is_mutex = requires
{
std::is_same_v<T, std::recursive_mutex>;
};
template <class T> requires is_mutex<T> using expLock = std::lock_guard<T>;
As above, the mutex was verified for type T, and std::lock_guard for type T was aliased through using keyword.
But when declaring a locker with that alias(expLock).
std::recursive_mutex mutex_Lock;
expLock Locker(mutex_Lock); // error : No argument list for alias template expLock.
Above code causes a compile error.
It seems that the explicit keyword of the std::lock_guard constructor was ignored because the code below forced type T to std::lock_guard.
template <class T> requires is_mutex<T> using expLock = std::lock_guard<T>;
// CLASS TEMPLATE lock_guard
template <class _Mutex>
class _NODISCARD lock_guard { // class with destructor that unlocks a mutex
public:
using mutex_type = _Mutex;
explicit lock_guard(_Mutex& _Mtx) : _MyMutex(_Mtx) { // construct and lock
_MyMutex.lock();
}
...
private:
_Mutex& _MyMutex;
};
Of course, if type T is specified in the alias(expLock) as shown below, no compilation error occurs.
std::recursive_mutex mutex_Lock;
expLock<std::recursive_mutex> Locker(mutex_Lock);
But I want the code below to work without compile errors.
template <typename T>
concept is_mutex = requires
{
std::is_same_v<T, std::recursive_mutex>;
};
template <class T> requires is_mutex<T> using expLock = std::lock_guard<T>;
std::recursive_mutex mutex_Lock;
expLock Locker(mutex_Lock); // error : No argument list for alias template expLock.
How to pass only mutex to lock_guard constructor parameter?
Should I define a new Locker class like std::lock_guard?
or
Do I need to fix the alias?
Is that too or is there a new solution?
This question has been answered in the comments below.
According to cppreference, MSVC implemented P1814 after 19.27*, so if your MSVC version is newer than 19.27*, your code will compile when use the /std:c++latest flag. –
康桓瑋
If the MSVC of the current project is version 19.27 or later, you can omit the template argument list for the using keyword.
However, if you are using Visual Studio's Intellisense, Intellisense may display an error message.
If a template argument list error message for the using keyword is popped up in MSVC 19.27 or later,
This error message may be caused by the Intellisense patch not based on the MSVC version.
Apart from the error message that Intellisense pops up, the build works without any problem. - 정명준
| First, Your concept of is_mutex is incorrectly defined. It will only check the validity of is_same_v in the requires clause without evaluating it. You need to define it as:
template <typename T>
concept is_mutex = requires { requires std::is_same_v<T, std::recursive_mutex>; };
Or just:
template <typename T>
concept is_mutex = std::is_same_v<T, std::recursive_mutex>;
Above code causes a compile error.
In fact, the above code is well-formed in C++20. I guess you are using Clang, which currently does not implement Class Template Argument Deduction for Alias Templates.
|
69,969,101 | 69,970,745 | CEIL in objective function CPLEX C++ | As per my knowledge, there's a tutorial that shows that ILOG can use ceil function (here). However, when I tried to implement it to calculate my objective function in CPLEX C++ (concert), it was failed. What I am looking for is as per below:
for (i=0; i<I; i++){
for (j=0; j<J; j++){
TO += ceil(DecisionVariable[i][j]/parameter[j]);
}
}
Any advises would be appreciated. Thank you so much.
Best regards,
| In OPL we have ceil but in concert C++ the equivalent function is IloCeil.
But we need to remember that this function is not linear.
In How to with OPL ? we can read How to use ceil of a decision variable in a CPLEX constraint ?
range r=1..4;
float x[r]=[1.5,4.0,2.0001,5.9999];
dvar int y[r];
dvar float f[r] in 0..0.9999999;
subject to
{
forall(i in r) y[i]==x[i]+f[i];
}
execute
{
writeln(x," ==> ",y);
}
assert forall(i in r) y[i]==ceil(x[i]);
|
69,969,166 | 69,969,292 | Using >= or value - 1? | Say I'm checking for if a value is greater than or equal to a certain value and the current values I'm comparing are integers. In C++, would it be more optimal to do something like:
if(value > threshold - 1)
...
or this
if(value >= threshold)
...
My thinking is that the call to >= adds an extra stack frame, but then again a call is made when using - for the subtraction operation. While I know the performance difference is likely negligible, which is technically more optimal?
| The first has undefined behavior if threshold is signed and is the most negative value of its type. That might disqualify it immediately, but if you know that case is impossible, it is therefore at least as fast as the >= version since the compiler is obliged to produce the same answer but in only a subset of cases. In practice, however, equivalent assembly is produced: any sensible architecture has enough comparison instructions such that some combination of swapping the inputs and switching between strict and non-strict inequalities can implement either without actually subtracting 1.
If threshold is unsigned, the first is well-defined for all input values but is inequivalent to the >= version. Again, that inequivalence might compel the choice; otherwise, the first is slower on typical architectures because it actually has to perform the subtraction to achieve that difference in behavior.
|
69,969,390 | 69,969,583 | What is the space complexity of my code? (Linked List) | I was solving a problem related to linked lists I wrote some code which works perfectly fine but I am not able to analyse the space complexity of my code. This is the problem, You have been given a singly linked list of integers along with two integers, 'M,' and 'N.' Traverse the linked list such that you retain the 'M' nodes, then delete the next 'N' nodes. Continue the same until the end of the linked list.
I wrote this code to solve this problem.
Node *skipMdeleteN(Node *head, int M, int N) {
if (head == NULL) return head;
if (M == 0) return NULL;
if (N == 0) return head;
Node *current = head;
Node *dummy1 = new Node(-1);
Node *dummy2 = new Node(-1);
Node *FinalHead;
Node *dummy2Head;
Node *prev;
int i = 0;
int j = 0;
int Head = 0;
while (current != NULL) {
if (i <= M - 1) {
dummy1->next = current;
dummy1 = dummy1->next;
if (Head == 0) {
FinalHead = dummy1;
Head++;
}
}
if (i >= M && i <= ((M + N) - 1)) {
dummy2->next = current;
dummy2 = dummy2->next;
if (j == 0) {
dummy2Head = dummy2;
j++;
}
}
if (i == ((M + N) - 1)) {
i = 0;
} else {
i++;
}
current = current->next;
}
dummy1->next = NULL;
dummy2->next = NULL;
dummy1 = dummy1->next;
dummy2 = dummy2->next;
while (dummy2Head != NULL) {
prev = dummy2Head;
dummy2Head = dummy2Head->next;
delete (prev);
}
return FinalHead;
}
This code works perfectly fine and the logic behind the code is following:
I create 2 dummy nodes(dummy1 and dummy2) and then I start traversing the linked list, for the first M nodes I keep on attaching those nodes at the end of dummy1 node. Once M nodes are done then I start attaching the next N nodes at the end of dummy2 node which I will delete in the end. So this attaches all the M nodes which I want to retain at the end of the dummy1 list, whose head I return.
The time complexity of my code is O(N) because I am traversing the list. I am not sure what the space complexity will be, will using 2 dummy nodes make it a linear space complexity because they are acting like a linked list. Please explain!
| There are two space complexity metrics: total space complexity and auxiliary (extra) space complexity.
Total includes input, while auxiliary doesn't.
In your case, input size is O(n) and you're modifying it, using O(1) extra space. After modifications, input is still O(n). Here n denotes the size of the list.
Which translates to O(n) total space complexity and O(1) auxiliary space complexity.
|
69,969,421 | 69,971,299 | one strange problem when I generate random numbers by OMP(C++) | The code is as follows:
#include<omp.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned int seed = 1;
int n =4;
int i = 0;
#pragma omp parallel for num_threads(4) private(seed)
for(i=0;i<n;i++)
{
int temp1 = rand_r(&seed);
printf("\nRandom number: %d by thread %d\n", temp1, omp_get_thread_num());
}
return 0;
}
The code output is:
Random number: 1905891579 by thread 0
Random number: 1012484 by thread 1
Random number: 1012484 by thread 2
Random number: 1012484 by thread 3
This is strange for me: why thread 0 has different number?
But when I change n with a const number 4:
#include<omp.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned int seed = 1;
const int n =4;
int i = 0;
#pragma omp parallel for num_threads(4) private(seed)
for(i=0;i<n;i++)
{
int temp1 = rand_r(&seed);
printf("\nRandom number: %d by thread %d\n", temp1, omp_get_thread_num());
}
return 0;
}
The code output is:
Random number: 1012484 by thread 2
Random number: 1012484 by thread 3
Random number: 1012484 by thread 0
Random number: 1012484 by thread 1
All threads have the same random numbers.
I don't understand the reason that thread 0 has different number when n is not a const variable.
Is there any one know this thing? Thanks a lot.
| The problem is that the variable declared private is not initialized.
If you add this line
printf("thread %d seed %u \n", omp_get_thread_num(), seed);
before int temp1 = rand_r(&seed) you will get an output like this:
thread 3 seed 0
Random number: 1012484 by thread 3 seed 2802067423
thread 0 seed 21850
Random number: 2082025184 by thread 0 seed 2464192641
thread 2 seed 0
Random number: 1012484 by thread 2 seed 2802067423
thread 1 seed 0
Random number: 1012484 by thread 1 seed 2802067423
Repeating the runs, on my machine I see that the thread 0 gets always a different seed value, whereas the other threads have seed=0. In any case, this is UB due to an uninitialized variable.
|
69,969,827 | 69,969,910 | overloading assignment operator and header file in c++ | i want to add a overloaded assignment operator to my object class in c++ but when I do this
Cabinet& Cabinet::operator=( const Cabinet& right ) {
if(&right != this){
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
this->chemicals[i][j] = right.chemicals[i][j];
}
}
}
return *this;
}
and with a header file like this
using namespace std;
#include <stdlib.h>
#include <string>
#include <iostream>
#include "Chemical.h"
class Cabinet{
private:
int rows;
int id_cabinet;
int columns;
Chemical*** chemicals;
string alphabet [9];
public:
Cabinet(int id = 0, int rows = 0, int columns = 0);
~Cabinet();
int getRow();
int getColumn();
int plusCount();
};
when compiling I get a compile error that says:
Cabinet.cpp:146:19: error: definition of implicitly declared copy assignment operator
| You need to declare the function in your header file so you can define it later on.
using namespace std;
#include <stdlib.h>
#include <string>
#include <iostream>
#include "Chemical.h"
class Cabinet{
private:
int rows;
int id_cabinet;
int columns;
Chemical*** chemicals;
string alphabet [9];
public:
Cabinet(int id = 0, int rows = 0, int columns = 0);
Cabinet& operator=( const Cabinet& right );
~Cabinet();
int getRow();
int getColumn();
int plusCount();
};
|
69,969,960 | 69,970,021 | Duplicate Definitions? | I have the following code:
#include <iostream>
/*
template <class A, std::enable_if_t<!std::is_same_v<A, double>, bool> = true>
void test() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
template <class A, std::enable_if_t<std::is_same_v<A, double>, bool> = true>
void test() {
std::cout << "SFINAE" << std::endl;
}
*/
template <class A, typename = std::enable_if_t<!std::is_same_v<A, double>>>
void test() {
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
template <class A, typename = std::enable_if_t<std::is_same_v<A, double>>>
void test() {
std::cout << "SFINAE" << std::endl;
}
int main() {
test<int>();
test<double>();
}
Compiler complains
test_function_templ.cpp:21:6: error: redefinition of ‘template<class A, class> void test()’
21 | void test() {
| ^~~~
test_function_templ.cpp:16:6: note: ‘template<class A, class> void test()’ previously declared here
16 | void test() {
| ^~~~
test_function_templ.cpp: In function ‘int main()’:
test_function_templ.cpp:27:15: error: no matching function for call to ‘test<double>()’
27 | test<double>();
| ^
test_function_templ.cpp:16:6: note: candidate: ‘template<class A, class> void test()’
16 | void test() {
| ^~~~
test_function_templ.cpp:16:6: note: template argument deduction/substitution failed:
In file included from /opt/rh/devtoolset-10/root/usr/include/c++/10/bits/move.h:57,
from /opt/rh/devtoolset-10/root/usr/include/c++/10/bits/nested_exception.h:40,
from /opt/rh/devtoolset-10/root/usr/include/c++/10/exception:148,
from /opt/rh/devtoolset-10/root/usr/include/c++/10/ios:39,
from /opt/rh/devtoolset-10/root/usr/include/c++/10/ostream:38,
from /opt/rh/devtoolset-10/root/usr/include/c++/10/iostream:39,
from test_function_templ.cpp:1:
/opt/rh/devtoolset-10/root/usr/include/c++/10/type_traits: In substitution of ‘template<bool _Cond, class _Tp> using enable_if_t = typename std::enable_if::type [with bool _Cond = false; _Tp = void]’:
test_function_templ.cpp:15:20: required from here
/opt/rh/devtoolset-10/root/usr/include/c++/10/type_traits:2554:11: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
2554 | using enable_if_t = typename enable_if<_Cond, _Tp>::type;
| ^~~~~~~~~~~
If I use the first set of function templates (commented in the code) test(), it compiles and runs as expected.
Questions
I thought for the 2nd set of function templates, calling test<int>() would instantiate test<int, void>() and calling test<double>() would instantiate test<double, void>(). But compiler seems like seeing two duplicate template functions?
Why the first set of function templates doesn't have any issue while second set does?
| The problem of the first snippet is described here (see how /* WRONG */ vs /* RIGHT */ snippets of code map to your commented and uncommented code respectively).
A common mistake is to declare two function templates that differ only in their default template arguments. This does not work because the declarations are treated as redeclarations of the same function template (default template arguments are not accounted for in function template equivalence).
Here's my understanding of why that's the case.
When the compiler sees this (the correct version)
template <class A, std::enable_if_t<!std::is_same_v<A, double>, bool> = true>
void test() {}
template <class A, std::enable_if_t<std::is_same_v<A, double>, bool> = true>
void test() {}
it doesn't see a redeclaration, because it doesn't know if the two std::enable_if_t will resolve to the same type. If it knew, then it'd be a hard compile time error, just like this is an error:
template <class A, bool = true>
void test() {}
template <class A, bool = false> // no matter the value; signature is the same
void test() {}
This doesn't exclude that the ambiguity can happen at the substitution level. For instance, there's no problem with these overload declarations, in principle
template <class A, std::enable_if_t<std::is_convertible_v<A, double>, bool> = true>
void test() {}
template <class A, std::enable_if_t<std::is_convertible_v<A, int>, bool> = true>
void test() {}
but as soon as you call test<int>(), the ambiguity will pop up, because the compiler will be able to "successfully" instantiate each of the overloads, which both result in template<int, bool = whatever>, which makes them ambiguous.
As regards the wrong version:
template <class A, typename = std::enable_if_t<!std::is_same_v<A, double>>>
void test() {}
template <class A, typename = std::enable_if_t<std::is_same_v<A, double>>>
void test() {}
the problem is that before even seeing how it's used, the compiler complains already, because default template arguments are not accounted for in function template equivalence. Indeed, a much simpler example shows the problem of the previous snippet:
template <class A, typename = typename A::foo>
void test() {}
template <class A, typename = typename A::bar>
void test() {}
Notice that, exactly like in the previous snippet, in this last snippet each of the overloads is correct by itself, until you try using it with a specific A for which the expression of the default argument doesn't make sense, thus causing a hard error.
But if you put the two overloads together, that creates an ambiguity, because default template arguments are not accounted for in function template equivalence.
|
69,970,150 | 69,970,897 | std::cin string to int array with variable length input | I have a task where i need to revert a list of variable length numbers. This could be "1 2 3" or "5 6 7 8 9 10".
The sorting itself works fine.
But I can't figure out how to read the user input (with variable length) and then only execute the reverseSort once.
How can I read the user input into an array where each index is based on the space between the numbers?
Here is my code:
#include <iostream>
#include <string>
using namespace std;
bool sorted = true;
int temp;
int * arr;
int arrLength = 5;
int arrs;
// int arr = {1,2,3,4,5};
void reverseSort(int arr[], int n){
sorted = true;
for (int i = 0; i < n-1; i++){
if (arr[(i + 1)] > arr[i]){
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
sorted = false;
}
}
if (!sorted){
reverseSort(arr,n);
}
}
int main(void){
// get user input !?!?!?!?!
cin >> arrs;
cout << arrs;
reverseSort(arr,arrLength);
for (int i = 0; i < arrLength; i++){
std::cout << arr[i] << " ";
}
return 0;
}
| If you don't know number of inputs you need struct that can be resized. std::vector is good for it. For adding new data you can use member function push_back.
You can read the input line as std::string (by std::getline) and you can open new stream with read data (std::istringstream). Further one can read values from new stream.
And I think you can use std::sort instead of reverseSort (but for 'reverse' you need use std::greater as comparator).
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
int main(void){
std::vector<int> arrs;
// read only one line
std::string input;
std::getline(std::cin, input);
std::istringstream row(input);
int x;
while (row >> x)
{
arrs.push_back(x);
}
//like your reverseSort
std::sort(arrs.begin(), arrs.end(), std::greater<int>{});
for (auto var : arrs) {
std::cout << var << "; ";
}
return 0;
}
|
69,970,230 | 69,970,273 | Is there a way to slice the structure vector in c++? | I have an data named faces which definition is like this:
struct ivec3 {
unsigned int v0;
unsigned int v1;
unsigned int v2;
};
std::vector<ivec3> faces;
I got the faces with 100 elements(faces.size()=100).
Now I want to get all v0 of faces. If I use the Python, I can do it like this
all_v0 = faces[:, 0]
So, how can I use the slicing operation in C++ like above code of Python?
Thanks very much!
| You can do this with the help of std::transform:
std::vector<int> all_v0;
all_v0.reserve(faces.size());
std::transform(faces.begin(), faces.end(),
std::back_inserter(all_v0),
[] (const ivec3& i) { return i.v0; });
|
69,970,334 | 69,970,382 | C++ SafeSingleton 3 level inheritance | I have a templated SafeSingleton class, Base class which is derived from SafeSingleton and implements some base methods. I want to have class that is derived from Base and can be accessed via instance() method of SafeSingleton. The problem is that when I am trying to access Derived::instance() it returns the pointer to a Base class and the compiler doesn't know anything about methods of derived class. What should I do to make below code work.
template<class T>
class SingleTon {
public:
static T* instance()
{
return holder().instance;
}
protected:
template<class I>
struct Holder
{
Holder() : instance(new I())
{
}
I* instance;
};
static Holder<T> &holder()
{
static Holder<T> holder;
return holder;
}
};
// Hopefully issue is here, I am never creating SingleTon<Derived>, but how can it be done?
class Base : public SingleTon<Base> {
public:
Base() = default;
void printBase() {
std::cout << "Base";
}
};
class Derived : public Base {
public:
Derived() = default;
void printDerived() {
std::cout << "Derived";
}
};
int main()
{
Derived::instance()->printBase();
Derived::instance()->printDerived(); // Here is the error
//Error: main.cpp:57:26: error: ‘class Base’ has no member named ‘printDerived’
//57 | Derived::instance()->printDerived();
return 0;
}
| template<class D>
class Base : public SingleTon<D> {
and
class Derived : public Base <Derived>
and ... done?
If you want to put Base's non-Ddependent methods in a cpp file, you'll have to get fancy. Have BaseImp that does not derive from SingleTon, put code there. Have Base<D> derive from it and write forwarding glue to it BaseImpl. But you probably don't need this.
|
69,970,809 | 69,970,865 | What is the difference between these two expressions | #include <bits/stdc++.h>
using namespace std;
void test(){
int a = 100;
cout << a << endl;
}
int main()
{
void(*b)() = test;
(*b)(); //expression one
b(); //expression two
return 0;
}
test is a pointer to function, isn't it? (*b)() is a correct form, because it is equivalent to function prototype. But Why is it correct to delete a symbol *? They all produced the right results.
|
test is a pointer to function, isn't it?
No, it isn't. test is a function.
b is a pointer to function.
But Why is it correct to delete a symbol *?
Because you can also invoke the function call operator on function pointers, and not just functions.
Furthermore, since a function can implicitly convert to a function pointer, this is also equivalent:
(********b)();
What is the difference between these two expressions
One indirects through function pointer and invokes function call operator - which calls the pointed function.
The other invokes function call operator on a function pointer - which implicitly indirects through the pointer and calls the pointed function.
The former requires 3 more characters to write.
|
69,971,076 | 69,972,187 | How to express a constraint in terms of another concept | It's probably easiest to describe specifically what I'm trying to solve to make this easier to understand.
I have a SmartPointer concept, so that I can have functions which can accept either std::unique_ptr or std::shared_ptr:
template <typename T>
concept SmartPointer = requires(const T& t) {
requires std::same_as<decltype(t.get()), typename T::pointer>;
};
I want to make a function which can take a pair of iterators, where the iterator value type must be of type SmartPointer and I don't need to explicitly define any types.
I can create a function which has template parameter with the SmartPointer constraint, and check against that:
template <SmartPointer T, std::forward_iterator TIterator, std::sentinel_for<TIterator> TIteratorSentinel>
requires std::same_as<std::iter_value_t<TIterator>, T>
void doWithSmartPointers(TIterator begin, TIteratorSentinel end) {
for (auto it = begin; it != end; ++it) {
// Some logic with it->get() etc.
}
}
However, when using it, I am required to explicitly specify T, which I would prefer not to have to do:
std::vector<std::unique_ptr<int>> v{};
v.push_back(std::make_unique<int>(1));
v.push_back(std::make_unique<int>(2));
v.push_back(std::make_unique<int>(3));
doWithSmartPointer(v.begin(), v.end()); // Error, couldn't infer template argument T
doWithSmartPoint<std::unique_ptr<int>>(v.begin(), v.end()); // OK
From the error message, I'm guessing I need some sort of template deduction guide but as far as I can see they can only be defined for classes/structs and not functions.
I essentially want something like this:
template <std::forward_iterator TIterator, std::sentinel_for<TIterator> TIteratorSentinel>
requires std::same_as<std::iter_value_t<TIterator>, SmartPointer> // Not valid syntax!
void doWithSmartPointers(TIterator begin, TIteratorSentinel end) {
for (auto it = begin; it != end; ++it) {
// Some logic with it->get() etc.
}
}
Am I going about this in the correct way? Is this even possible? Thank you in advance!
| You don't need T as a template parameter:
template < std::forward_iterator TIterator
, std::sentinel_for<TIterator> TIteratorSentinel >
requires SmartPointer< std::iter_value_t<TIterator> >
// ^^^^^^^^^^^^
void whatever(TIterator begin, TIteratorSentinel end)
{
// ...
}
|
69,971,092 | 69,972,136 | google mock : error: ‘class ISInfo’ has no member named ‘gmock_registerCallBack’ | I have an interface in C++ called SInfo
class ISInfo
{
public:
/// Register a callback
virtual Handle registerCallBack( const std::string topic) = 0;
/// De-register a callback
virtual bool deregisterCallback(Handle handle) = 0;
/// Deconstructor
virtual ~ISInfo()
{
};
};
I have class MSInfo that implements ISInfo
class MSInfo : public ISInfo
{
public:
/// Constructor
MSInfo( Node *Node);
/// Deconstructor
~MSInfo();
/// Register a callback
Handle registerCallBack( const std::string topic);
/// Deregister
bool deregisterCallback(Handle handle);
};
I have created a Mock class called MockMSInfo as shown below.
class MockMSInfo : public MSInfo
{
public:
MockMSInfo(Node *node) : MSInfo(ode) {}
MOCK_METHOD1(registerCallBack, Handle(const std::string topic));
MOCK_METHOD1(deregisterCallback, bool(Handle topicHandle));
};
In my unit test,I create a Mock object of the above type MockMSInfo as below
Node *node = new Node();
ISInfo *isInfo = new MockMSInfo(node);
The problem is when I do
EXPECT_CALL(*isInfo, registerCallBack(_));
I get the below error
googletest/install/include/gmock/gmock-spec-builders.h:2026:16: error: ‘class ISInfo’ has no member named ‘gmock_registerCallBack’
((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \
^
googletest/install/include/gmock/gmock-spec-builders.h:2034:3: note: in expansion of macro ‘GMOCK_ON_CALL_IMPL_’
GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)
^
MonitorUnitTests.cpp:52:5: note: in expansion of macro ‘EXPECT_CALL’
EXPECT_CALL(*isInfo, registerCallBack(_));
| For a starter: I propose you derive from the base class, not from the impl class:
class MockMSInfo : public ISInfo
{
public:
MOCK_METHOD1(registerCallBack, Handle(const std::string topic));
MOCK_METHOD1(deregisterCallback, bool(Handle topicHandle));
};
And now the actual problem: the compiler is your friend here. Indeed, you want to call a method that is not available in IsInfo. See, you've created an instance of MockMSInfo, but you've assigned it to a ptr to the base class (i.e. ISInfo *). The macro MOCK_METHOD* adds a new method to the mock class (but of course, not the base class!), called gmock_<METHOD_NAME>. And EXPECT_CALL requires such method to be defined in the class passed. But you passed ISInfo *. Therefore, to fix this, just create the mock and use MockMSInfo * as the type. Working example https://godbolt.org/z/Pe8eM9E9s.
|
69,971,612 | 69,973,367 | How does -march native affect floating point accuracy? | The code I work on has a substantial amount of floating point arithmetic in it. We have test cases that record the output for given inputs and verify that we don't change the results too much. I had it suggested that I enable -march native to improve performance. However, with that enabled we get test failures because the results have changed. Do the instructions that will be used because of access to more modern hardware enabled by -march native reduce the amount of floating point error? Increase the amount of floating point error? Or a bit of both? Fused multiply add should reduce the amount of floating point error but is that typical of instructions added over time? Or have some instructions been added that while more efficient are less accurate?
The platform I am targeting is x86_64 Linux. The processor information according to /proc/cpuinfo is:
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 85
model name : Intel(R) Xeon(R) Gold 6152 CPU @ 2.10GHz
stepping : 4
microcode : 0x2006a0a
cpu MHz : 2799.999
cache size : 30976 KB
physical id : 0
siblings : 44
core id : 0
cpu cores : 22
apicid : 0
initial apicid : 0
fpu : yes
fpu_exception : yes
cpuid level : 22
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear flush_l1d
bugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa itlb_multihit
bogomips : 4200.00
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
| The use of FMA can both decrease and increase error, both of those may result in a testcase failing, depending on how the test works. FMA improves error "locally", but the effect may be the opposite when put in a wider context.
For example, a * c - b * d (determinant of a 2x2 matrix) famously gives some (usually minor) trouble when FMA-contracted. Without FMA, the subtraction has the potential to eliminate the rounding error, if it is the same on both sides. That does not always happen, but it can happen when a * c = b * d which is of special interest because that means the determinant should be zero. Without FMA the result would actually be zero, with FMA it won't be.
#include <math.h>
#include <stdio.h>
double determinant(double a, double b, double c, double d)
{
return a * c - b * d;
}
int main()
{
volatile double a = M_PI;
double x = determinant(a, a, a, a);
printf("%E\n", x);
return 0;
}
This program, compiled by GCC 11.2 with optimizations enabled and FMA allowed, does not print zero, but something on the order of 1E-16.
Some variants of an "is this result close enough"-test in a unit-test would conclude that this result is, relative to zero, extremely wrong. Another way to look at it though, is that if one of the inputs changed by just 1 ULP, that would have introduced an error on the order of 1E-15, which is even worse.
Most special/new instructions either don't affect accuracy or are by default restricted. For example addsubpd and haddpd (from SSE3) are just equivalents of what would have cost more code before, and roundpd (from SSE4.1) is by default only used in ways that don't affect results (using roundpd for floor and ceil is safe, ironically using it for round itself is non-trivial due to the different halfway rounding).
|
69,972,016 | 69,974,618 | OpenCV's Warp Affine Has Lower Quality Compared to Photoshop | I want to transform and align a detected face (320x240 Size) from a CelebA image (1024x1024 Size) using OpenCV's cv2.warpAffine function but the quality of the transformed image is significantly lower than when I try to align it by hand in Photoshop: (Left Image Is Transformed By Photoshop & Right Image Is Transformed in OpenCV)
I have used all of the interpolation techniques of OpenCV but none of them came close in quality to Photoshop.
The code I'm using is:
warped = cv2.warpAffine(image, TRANSFORM_MATRIX, (240, 320), flags=cv2.INTER_AREA)
What could be wrong that made the transformed image have such low quality?
Here's a Link to the original 1024x1024 image if needed.
| Problem and general solution
You are down-sampling a signal.
The approach is always the same:
lowpass to remove high frequency components
resample/decimate
What not to do
If you don't do the lowpass, you'll get aliasing. You noticed that. Aliasing means the sampling step can completely miss some high frequency component (edge/corner/point/...), giving those strange artefacts. A properly resampled image would not completely lose such high frequency features.
If you do the lowpass after resampling, it won't fix the issue, only hide it. The damage has already been done.
You can convince yourself of both these aspects if you downsample some regular grid of strongly contrasting lines. Try alternating single-pixel lines of black and white for most effect.
Implementations
Libraries such as PIL do the lowpass implicitly before resampling.
OpenCV does not (kinda, in general). Not even with Lanczos interpolation (in OpenCV) will you be able to skip the lowpassing, because OpenCV's Lanczos has a fixed coefficient.
OpenCV has INTER_AREA, which is a linear interpolation, but it additionally sums over all pixels that are in the area between the corner samples (instead of just sampling those four corners). This can spare you the extra lowpass step.
here's the result of cv.resize(im, (240, 240), interpolation=cv.INTER_AREA):
Here's the result of cv.warpAffine(im, M[:2], (240, 240), interpolation=cv.INTER_AREA) with M = np.eye(3) * 0.25 (equivalent scaling):
It appears that warpAffine can't do INTER_AREA. That sucks for you :/
If you need to downsample with OpenCV, and it's a power of two, you can use pyrDown. That does the lowpass and decimation... for a factor of two. Repeated application gives you higher powers.
If you need arbitrary downsampling and you don't like INTER_AREA for some reason, you'd have to apply a GaussianBlur to the input. Sigma needs to be (inversely) proportional to the scale factor. There is some relation between the gaussian filter's sigma and the resulting cutoff frequency. You'll want to investigate that some more, if you don't want to pick a value arbitrarily. Check out the kernel for pyrDown, and what gaussian sigma it matches best. That's probably a good value for a scale factor of 0.5, and other factors should be (inversely) proportional.
For simple downscaling, one gaussian blur would be fine. For affine warps and higher transformations, you'd need to apply lowpassing that respects the different scale for every single pixel that is looked up, because their "support" in the source image isn't square any longer, maybe not even rectangular, but an arbitrary quad!
What am I not saying?
This goes for down-sampling. If you up-sample, do not lowpass.
|
69,972,833 | 69,972,972 | Fastest "trivial" way of shuffling a vector | I am working on a chess engine for some time now. For improving the engine, I wrote some code which loads chess-positions from memory into some tuner code. I have around 1.85B fens on my machine which adds up to 40Gb (24B per position).
After loading, I end up with a vector of positions:
struct Position{
std::bitset<8*24> bits{};
}
void main(){
std::vector<Position> positions{};
// mimic some data loading
for(int i = 0; i < 1.85e9; i++){
positions.push_back(Position{})
}
// ...
}
The data is organised in the following way:
The positions are taken from games where the positions are seperated by just a few moves. Usually about 40-50 consecutive moves come the same game / line and are therefor somewhat equal.
Eventually I will read 16384 position within a single batch and ideally none of those positions come from the same game. Therefor I do some initial sorting before using the data.
My current shuffling method is this:
auto rng = std::default_random_engine {};
std::shuffle(std::begin(positions), std::end(positions), rng);
Unfortunately this takes quiet some time (about 1-2 minutes). Since I dont require perfect shuffles, I assume that some easier shuffles exist.
My second aproach was:
for(int i = 0; i < positions.size(); i++){
std::swap(positions[i], positions[(i*16384) % positions.size()]);
}
which will ensure that there are not going to be positions coming from the same game within a single batch and are evenly spaces by 16384 entries.
I was wondering if there is some even simpler, faster solution. Especially considering that the modulo-operator requires quiet some clock cycles.
I am happy for any "trivial" solution.
Greetings
Finn
| There is a tradeoff to be made: Shuffling a a std::vector<size_t> of indices can be expected to be cheaper than shuffling a std::vector<Position> at the cost of an indirection when accessing the Positions via shuffled indices. Actually the example on cppreference for std::iota is doing something along that line (it uses iterators):
#include <algorithm>
#include <iostream>
#include <list>
#include <numeric>
#include <random>
#include <vector>
int main()
{
std::list<int> l(10);
std::iota(l.begin(), l.end(), -4);
std::vector<std::list<int>::iterator> v(l.size());
std::iota(v.begin(), v.end(), l.begin());
std::shuffle(v.begin(), v.end(), std::mt19937{std::random_device{}()});
std::cout << "Contents of the list: ";
for(auto n: l) std::cout << n << ' ';
std::cout << '\n';
std::cout << "Contents of the list, shuffled: ";
for(auto i: v) std::cout << *i << ' ';
std::cout << '\n';
}
Instead of shuffling the list directly, a vector of iterators (with a std::vector indices woud work as well) is shuffled and std::shuffle only needs to swap iterators (/indices) rather than the more costly actual elements (in the example the "costly to swap" elements are just ints).
For a std::list I don't expect a big difference between iterating in order or iterating via shuffled iterators. On the other hand, for a std::vector I do expect a significant impact. Hence, I would shuffle indices, then rearrange the vector once, and profile to see which performs better.
PS: As noted in comments, std::shuffle is already the optimal algorithm to shuffle a range of elements. However, note that it swaps each element twice on average (possible implementation from cppreference):
for (diff_t i = n-1; i > 0; --i) {
using std::swap;
swap(first[i], first[D(g, param_t(0, i))]);
On the other hand, shuffling the indices and then rearranging the vector only requires to copy/move each element once (when additional memory is available).
|
69,973,152 | 69,973,475 | How to change the increment or step or scale of a Google Benchmark 'Range()' function | I have a very simple Google Benchmark program that benchmarks a function taking two integer arguments, I'm trying to use the benchmark to see how exactly does the time the function takes increase as the second argument's value increases from 1 to 100, so with the first argument staying with the same value of 999999 .
The way to achieve this that looked the most logical to me was to use Google Benchmark's Ranges() function like this:
// registering function 'largestDivisorOdd' as a benchmark
BENCHMARK(largestDivisorOdd) ->Ranges( { {999999, 999999}, {1,100} } );
The resulting output was this:
-----------------------------------------------------------------------
Benchmark Time CPU Iterations
-----------------------------------------------------------------------
largestDivisorOdd/999999/1 116 ns 116 ns 6018141
largestDivisorOdd/999999/8 205 ns 205 ns 3485489
largestDivisorOdd/999999/64 2715 ns 2715 ns 260611
largestDivisorOdd/999999/100 2710 ns 2710 ns 256160
My problem is that it seems Google Benchmark has made the range from only values of an exponential increase from 1 to 100, resulting in only 4 benchmarks of 4 different values for the second parameter, instead of 100 benchmarks of 100 values from 1 to 100 as I expected and wanted.
| One of the following should work:
BENCHMARK(largestDivisorOdd)
->ArgsProduct({
benchmark::CreateRange(999999, 999999, /*multi=*/2), // This is probably not what you want
benchmark::CreateDenseRange(1, 100, /*step=*/1) // This creates a DenseRange from 1 to 100
})
Or create your own custom arguments:
static void CustomArguments(benchmark::internal::Benchmark* b) {
for (int i = 999999; i <= 999999; ++i)
for (int j = 1; j <= 100; j++)
b->Args({i, j});
}
BENCHMARK(BM_SetInsert)->Apply(CustomArguments);
Both examples are taken from the User Guide
|
69,973,270 | 69,973,595 | Can a C++20 [[likely]] or [[unlikely]] attribute be used on the condition of a do-while loop? | I have tried placing C++20's [[likely]] and [[unlikely]] attributes at various locations around the condition of a do-while loop, and it seems placing them at the end of the line after the semicolon is accepted by all three major compilers:
int main(int i, char**)
{
do {
++i;
} while (i < 42); [[likely]]
return i;
}
However this looks rather strange. Is this really the correct place for the attribute?
|
Can a C++20 [[likely]] or [[unlikely]] attribute be used on the condition of a do-while loop?
[[likely]] cannot be applied on "conditions". It can be applied on labels and statements.
However this looks rather strange. Is this really the correct place for the attribute?
You've applied the attribute to the return statement. If we adjust whitespace a bit, then you'll see it better:
} while (i < 42);
[[likely]] return i;
You should apply the attribute to the block statement that is the loop body:
do [[likely]] {
|
69,973,456 | 69,973,621 | Overloaded ++ operator only works from left side (C++) | #include <iostream>
enum class Color { RED, GREEN };
Color& operator++(Color& source)
{
switch (source)
{
case Color::RED: return source = Color::GREEN;
case Color::GREEN: return source = Color::RED;
}
}
int main()
{
Color c1{ 1 };
Color c2 = Color::RED;
++c1; // OK
std::cout << (int)c1 << std::endl;
c2++; // error
std::cout << (int)c2 << std::endl;
return 0;
}
I overloaded ++ operator but it only works from left hand side.
What is the reason behind it?
Is it related to the way I do overloading or is it related to lvalue-rvalue concept?
| Color& operator++(Color& source) is for pre-incremant,
you need
Color operator++(Color& source, int) for post increment.
|
69,974,121 | 69,974,232 | C++11 vector with smart pointer | I read a lot of documentation about vector modern usage.
One of the common thing appearing is, "you can replace every push_back by emplace_back". Is it true ? I'm unsure, and the fact is I don't get the idea with a smart pointer.
So, is there a difference to emplace a smart pointer than pushing it into the vector ?
In other words :
myVector.emplace_back(std::make_shared< XXX >(x, y, z));
VS
myVector.push_back(std::make_shared< XXX >(x, y, z));
I read a comment about emplacing a smart pointer and a possible exception (low memory) raised just before the insertion leading to a memory leak. Is it true ? Memory leaking
And finally, I was hoping to write something like this :
myVector.emplace_back(x, y, z);
But I'm pretty sure, I can forget it. So that's why I'm thinking about the real benefits of emplace with smart pointers.
| There's no difference between the emplace_back and push_back at the start of your question, they both supply a prvalue std::shared_ptr<XXX> that will be passed to the move constructor of the vector element.
You can't myVector.emplace_back(x, y, z); if myVector holds std::shared_ptr<XXX> because there's no constructor of std::shared_ptr<XXX> that takes those arguments. You could do that if it were a std::vector<XXX>, and that would construct one XXX in-place.
Much of this is moot however, because copy elision means that an implementation is allowed to construct the shared pointer in place.
|
69,974,183 | 69,974,251 | How exactly structure packing and padding work? | How exactly structs are packed and padded in c++? The standard does not says anything about how it should be done (as far as I know) and compilers can do whatever they want. But there are tutorials showing how to efficiently pack structs with known rules (for example that every variable needs to be on address that is multiple of its size and if end of previous variable is not multiple, then padding will be inserted), and with these rules we can pack structs by hand in source. What is it finally? We know in what way structs will be packed on modern machines (for example PCs) or it is just idea that can be right, but it is not good to take it for granted?
|
How exactly structs are packed and padded in c++?
Short answer: In such way that alignment requirements are satisfied.
The standard does not says anything about how it should be done (as far as I know) and compilers can do whatever they want.
Within bounds of the alignment requirements, this is indeed correct. This is also an answer to your question.
|
69,974,388 | 69,974,449 | How do I include other .cpp files | I've watched several tutorials on C++ header files and did EXACTLY what they were showing, but I can't really understand why I can't use a function from other .cpp file.
Main.cpp
#include <iostream>
#include "Header.h"
int main() {
std::cout << sum(2, 2);
return 0;
}
Header.cpp
#include "Header.h"
int sum(int a, int b) {
return (a + b);
}
Header.h
#pragma once
int sum(int a, int b);
| Your program is working as can be seen here.
To get your program working on your machine follow these steps(assuming you're using g++ and Ubuntu:
Step 1: Create a binary/executable using the command:
g++ main.cpp Header.cpp -o myexecutable
Step 2: Test/Run your executable created in the last step using the command:
./myexecutable
Alternate Solution: A shortcut
Now if you're wondering that you've to type the name of every source file to make the executable, then you can take a sigh of relief because there is a shortcut as given below:
Assuming you have many source files(.cpp files) in your current directory and you want to compile them all without writing the names of all of them, then you can use the command:
g++ ./*.cpp -o myexecutable
The above command will create a binary/executable named myexecutable .
|
69,975,281 | 69,976,156 | Why my program shortcut is not highlighted in Windows start menu when newly installed? | I have a c++ program built with visual studio. An NSIS installer creates a shortcut for the program in the start menu. But the shortcut is not highlighted-as it is the case for all newly installed programs in Windows. Here it says that I have to add the version resource to my program; Which I did, but still no highlights. Windows 10 x64
Thank you.
| I don't think Windows 10 will highlight your new shortcut. If it appears in the "Recently added" section then Windows has correctly detected your new shortcut.
Windows XP to 7 highlighted new shortcuts in a different color. Windows 8 would promote a new shortcut as a tile on the start screen.
Windows 8 and later does some filtering to new shortcuts. Anything that points to a help file, URL or the uninstaller may be hidden.
|
69,975,308 | 69,975,708 | C++ Multipath Inheritance : Why the access using Base class scope is non-ambiguous? | I am studying C++ and while studying virtual inheritance, I came across following doubt:
class A {
public:
int x;
A() { x = 677; }
A(int a) {
cout << "A con , x= " << a << endl;
x = a;
}
};
class B : public A {
public:
B(int a) : A(a) { }
};
class C :public A {
public:
C(int a) : A(a) { }
};
class D : public B, public C {
public:
D(int a,int b) : B(a),C(b) { }
};
int main()
{
D d(5,6);
cout << d.A::x; //prints 5
}
In line cout << d.A::x; It prints 5. Shouldn't this call be ambiguous and if not why it prints 5?
| d.A::x; is indeed ambiguous. GCC and Clang report it as error, only MSCV fails to do so: https://godbolt.org/z/1zhjdE6a8.
There is a note in [class.mi] with an example of multiple inheritance stating that:
In such lattices, explicit qualification can be used to specify which subobject is meant.
The body of function C::f can refer to the member next of each L subobject:
void C::f() { A::next = B::next; } // well-formed
Without the A:: or B:: qualifiers, the definition of C::f above would be ill-formed because of ambiguity ([class.member.lookup]).
— end note]
It is just a note, because it follows from [class.member.lookup] (which is a little more contrived to read and understand) that without the qualifier the member access is ambiguous. "ill-formed" implies that a conforming compiler must issue either an error or warning.
|
69,975,344 | 69,985,371 | How can I gracefully stop a process created with CreateProcessW and option CREATE_NEW_CONSOLE? | Somewhere in my application, I am creating a process like this:
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(STARTUPINFO);
PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo, sizeof(processInfo));
const auto created = CreateProcessW(
pathToExe,
cmdLine,
nullptr,
nullptr,
false,
CREATE_NEW_CONSOLE,
nullptr,
workingDir,
&startupInfo,
&processInfo);
The exe I am running here is a console application.
At some later time, I would like to gracefully stop that process. I can kill it with TerminateProcess, but I would like to make it more graceful, as the process might have to save data to some database or perform some clean up (e.g. close hardware connections).
I tried to get the process HWND without success with EnumWindows and GetWindowThreadProcessId. In fact, EnumWindows doesn't list the process I created. With that HWND, my idea was to send a WM_CLOSE message.
Maybe I should not use the CREATE_NEW_CONSOLE flag? I tried the following startup info:
STARTUPINFO startupInfo;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(STARTUPINFO);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOW;
but that does not show me a console window (which I need to have). What am I doing wrong? How should I create my process and how can I then later gracefully stop it?
| In fact, at the time where I was trying to gracefully kill my console, it was too early to get a HWND to the console window. It was in a test where I naively just created the process and then almost straightaway killed it. If I wait long enough (i.e. if I actually interact for some time with the process I created), then I can get the handle to the console window and send it a WM_CLOSE message with success.
|
69,975,909 | 69,990,751 | No matching function call for boost::get in graph | I'm modeling my graph after example geometry/07_a_graph_route_example from boost.
My Graph looks like this:
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, gG_vertex_property<string, double, pointClass>, gG_edge_property<listClass, pointClass>> graph_type;
graph_type Graph;
with gG_vertex_property and gG_edge_property as custom properties.
Now every time I try to call dijkstra_shortest_path with
boost::dijkstra_shortest_paths(Graph, endVert, // Graph Object, End of Search Object
&predecessors[0], &costs[0], // Vectors to store predecessors and costs
boost::get(boost::edge_weight, Graph),
boost::get(boost::vertex_index, Graph), // Vertex Index Map
std::less<double>(), std::plus<double>(), // Cost calculating operators
(std::numeric_limits<double>::max)(), double(), // limits
boost::dijkstra_visitor<boost::null_visitor>()); // Visitior, does nothing at the moment
as WeightMap i get:
error: no matching function for call to 'get' boost::get(boost::edge_weight, Graph)
And a whole lot of templates for add which do not fit my use case. How i'm reading the docs this is the standard way to do it. Are my properties missing something?
What am i doing wrong?
Thanks for your help.
| I guess gG_vertex_property and gG_edge_property are "Bundled" properties (there's no so such thing as custom properties). If so, you should pass these instead of "boost::get(boost::edge_weight, Graph)", which tries to access "Internal" properties, completely separate thing. See https://www.boost.org/doc/libs/1_77_0/libs/graph/doc/bundles.html . I guess if properties are structs and edge weights are kept in gG_edge_property::weight, the correct code would be something like this:
boost::dijkstra_shortest_paths(Graph, endVert, // Graph Object, End of Search Object
&predecessors[0], &costs[0], // Vectors to store predecessors and costs
get(&gG_edge_property::weight, Graph), /*!!!!!!!!*/
boost::get(boost::vertex_index, Graph), // Vertex Index Map
std::less<double>(), std::plus<double>(), // Cost calculating operators
(std::numeric_limits<double>::max)(), double(), // limits
boost::dijkstra_visitor<boost::null_visitor>()); // Visitior, does nothing at the moment
|
69,976,104 | 69,978,148 | ESP32 WiFi.status() always returns WL_DICSONNECTED (STA_MODE) | I've spent a many hours trying to solve this.
I have added multiple attempts, tried to WiFi.disconnect() before Wifi.begin().
Nothing works: statusremains to be WL_DISCONNECTED (0x06).
WiFi.mode(WIFI_STA);
for(;;) {
attempt++;
Wifi.begin(ssid, password);
wl_status_t status = WiFi.status();
String m = connectionStatusMessage(status);
log("Connection attempt %d: status is%s", attempt, m.c_str());
if (status == WL_CONNECTED) {
Serial.println();
success("connected (WL_CONNECTED)");
information();
break;
}
[UPDATE]
Note: I use a ESP-WROOM-32 devkit package. The ESP32 sdk being the latest stable available on PlatformIO. I tested others devkits such a one from Az-Delivery too.
| I finally found a solution: The fix is to use WiFi.waitForConnectResult() instead of WiFi.status().
I initially thought it was a bug but as @juraj mentioned, and by examinination of the WiFi code, it is a matter of waiting for the status to come. And the waitFoConnectionResult() does just that. Hence the result.
Working code as follows:
WiFi.mode(WIFI_STA);
for(;;) {
attempt++;
Wifi.begin(ssid, password);
// >>>> the fix <<<<<
uint8_t status = WiFi.waitForConnectResult();
String m = connectionStatusMessage(status);
log("Connection attempt %d: status is%s", attempt, m.c_str());
if (status == WL_CONNECTED) {
Serial.println();
success("connected (WL_CONNECTED)");
information();
break;
}
|
69,976,349 | 69,978,715 | Qt/QML: how to redirect console output to syslog | I have a QtQuick/QML application running on a remote embedded target system. I have syslog configured on the target to direct log messages to a log server.
Now, I'd like to have the standard out and err console output also redirected to the local syslog so I can get all of my application feedback in one place.
Is there a "best practices" way to do this? Or will I want/need to obtain all this output within my application and log it through "normal channels"?
Edit: I can do this with bash redirection per this question/answer, but I would still prefer to do it from within the application, if possible.
Edit: I suppose I should make more clear that I'm not asking about how to get the messages that go through the application's logging API to go to syslog. If there are errors in my QtQuick QML, the Qt runtime generates error and warning messages that get printed to stderr. It's those messages that I want to get redirected to the system logging facility.
| Mind that all Qt and QML log will be streamed through this channel.
#include <syslog.h>
#include <QtGlobal>
/// Consider https://linux.die.net/man/3/openlog
/// Qt Log Message handler
static void qtLogMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray loc = msg.toUtf8();
switch (type) {
case QtDebugMsg:
syslog (LOG_DEBUG, "%s", loc.constData());
break;
case QtInfoMsg:
syslog (LOG_INFO, "%s", loc.constData());
break;
case QtWarningMsg:
syslog (LOG_WARNING, "%s", loc.constData());
break;
case QtCriticalMsg:
syslog (LOG_CRIT, "%s", loc.constData());
break;
case QtFatalMsg:
syslog (LOG_ERR, "%s", loc.constData());
break;
}
}
int main(int argc, char* argv[])
{
/// When starting the process
openlog("MY_APP_LOG", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_USER);
/// Install Qt Log Message Handler in main.cpp
qInstallMessageHandler(qtLogMessageHandler);
/// The Qt app GUI start can be
QApplication app(argc, argv);
app.exec();
/// When quitting the process
closelog();
}
|
69,976,568 | 70,017,733 | Why am I unable to use CreateWICTextureFromFileEx after shutting down SDL | I am trying to shutdown my DX12 renderer, and restart it within the same process.
Said application is heavily based on the microsoft MiniEngine example code, now with some modification to allow re-initialisation of global variables. I am using SDL for window and event management.
The last stumbling block for a clean shutdown and re-initialisation, it appears, is the loading of textures in a texture manager class, which in turn uses the DirectXTK12 code to load textures, via CreateWICTextureFromFileEx for .png files.
To summarise what I'm trying to do:
start up application
initialise rendering into SDL window
render in rendering loop
shut down all rendering and window handling (remove all resources, release device handle) - calls SDL_Quit
re-initialise rendering into new SDL window (get new device handle, etc)
render in rendering loop
The texture management class is shut down as part of the rendering shutdown, removing all traces of textures and their handles to resources etc.
As part of the rendering re-initialisation, the default textures are created via CreateWICTextureFromFileEx. (see here) and crash when trying to do this.
EDIT: since first posting, I can say that this crashing starts directly after calling SDL_Quit() (and persists after the call to restart with SDL_Init(SDL_INIT_VIDEO))
I am now fairly confident it's an issue with this area specifically rather than some other part of the renderer that isn't being re-initialised correctly, since I can force it to use .DDS textures instead of .pngs, and the system fires up again nicely. In this case it uses DDSTextureLoader without any (obvious) problems.
I've added the source to my project and can see the crash is occurring when trying to do this:
ComPtr<IWICBitmapDecoder> decoder;
HRESULT hr = pWIC->CreateDecoderFromFilename(fileName,
nullptr,
GENERIC_READ,
WICDecodeMetadataCacheOnDemand,
decoder.GetAddressOf());
The failure reported is
Unhandled exception thrown: read access violation.
pWIC->**** was 0x7FFAC0B0C610.
pWIC here is obtained via _GetWIC() which is using a singleton initialisation:
IWICImagingFactory2* _GetWIC() noexcept
{
static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT;
IWICImagingFactory2* factory = nullptr;
if (!InitOnceExecuteOnce(
&s_initOnce,
InitializeWICFactory,
nullptr,
reinterpret_cast<LPVOID*>(&factory)))
{
return nullptr;
}
return factory;
}
Since first posting, I can now say that this crashing starts directly after calling SDL_Quit(). I have test code that starts the graphics up enough to get a device and get a texture, which will complete successfully at any point until SDL_Quit.
Re-initialising SDL with SDL_Init(SDL_INIT_VIDEO) doesn't help.
I also note that the WICTextureLoader comments state "Assumes application has already called CoInitializeEx". Is this an area that SDL_Quit could be messing with?
| I'll post an answer here but will remove it if @ChuckWalbourn wants to post his own.
This was due to letting SDL call CoInitialize for me. When it cleaned up through SDL_Quit, it called CoUninitialize which then (presumably) invalidated the IWICImagingFactory2 set up by WICTextureLoader . By adding a call to CoInitialize in my rendering startup, the internal count in CoInitialize keeps the IWICImagingFactory2 alive and all is well.
|
69,976,985 | 69,977,182 | I'm getting a segmentation fault error in my program, but it is unclear how | From my understanding of segmentation faults, they occur when you try to access memory outside of the "space" of the program. My IDE says the exception occurs within in the first for loop where I perform the following operation: pi = w + i * i; I don't understand how I am accessing memory that I shouldn't access. The program is supposed to compute pi, up to a given amount of digits, it is not yet complete. I was testing what I have so far when the error occurred. The code follows:
/// computes the continued fraction, recursivley
int w = 1;
static long double pi = 0;
long double continued_fraction(int k, int i){
for(int i = 1; i <= k; i++){
pi += w + i * i;
w += 2;
pi /= continued_fraction(k, i++);
}
return pi;
}
/// continued fraction method to compute pi, up to a limit k
long double limit_fraction(int k){
int i = 1;
/// continued fraction method
pi = 4 / continued_fraction(k, 1);
return pi;
}
| Included code has infinitive recursion.
Lets call continued_fraction(1, 1). Then we enter for loop which redefines i and set it to 1 then first iteration when it does: continued_fraction(k, i++); it do: continued_fraction(1, 1) since post-increments provides old i.
This call is exactly same as first call, so recursion goes forever and you have stackoverflow - crash.
|
69,977,543 | 69,977,615 | Inconsistent behavior with `empty` std ranges view depending on type | Consider the following code snippet:
#include <vector>
#include <ranges>
#include <iostream>
struct A
{
};
struct B
{
B(void *) {};
};
template<class T, class R>
std::vector<T> foo(R &&range)
{
return std::vector<T> {
std::ranges::begin(range),
std::ranges::end(range)
};
}
int main()
{
std::cout << foo<A>(std::views::empty<A>).size() << "\n";
std::cout << foo<B>(std::views::empty<B>).size() << "\n";
}
It correctly prints 0 on the first line and incorrectly prints 2 on the second line on GCC 11.2 (https://godbolt.org/z/s6aoTGbr4) and MSVC 19.30.30705 (Visual Studio 2022 17.0).
Apparently in the second case std::views::empty view produces iterators that causes constructor taking initializer list to be selected.
Changing std::vector<T> { ... } to std::vector<T> ( ... ) fixes this, but I wonder if it is actually a bug in implementation (or even definition) of the empty view?
| This is why you should be wary of list-initialization! In particular, this syntax:
std::vector<T>{ ... }
should only (!!) be used when you're specifically trying to invoke the std::initializer_list<T> constructor, and specifically providing elements to the vector and not in any other case. Like this one, where you're not trying to call that constructor.
The issue is that in list-initialization, the std::initializer_list constructor is strongly preferred. If it is at all viable, it is chosen first. In this case, we are trying to construct a vector<B> from two pointers to B (that's the iterator type for empty<B>). A B is constructible from a B* (via the void* constructor), which makes the std::initializer_list<B> constructor a viable candidate, which means it's selected.
As a result, you get a vector<B> with two Bs, each constructed form a null pointer.
For A, there's no such viable constructor, so you fallback to normal initialization, which will select the iterator pair constructor, giving you an empty vector<A>.
The fix here is to use ()s when you initialize, since that's actually what you intend to do.
|
69,977,662 | 69,977,694 | Why is my class size appending an extra byte? | I have the following class structure:
#pragma pack(push, 1)
class Base{
Base(){}
~Base{}
void accept();
};
class A : Base{
int m1;
int m2;
int m3;
};
class B : Base{
A a;
int m1;
int m2;
int m3;
int m4;
};
#pragma pack(pop)
Size of B in this case is 29 bytes.
However, when I make class A not inherit from Base, but B still inherits from Base, Class B becomes 28 bytes.
Then if I make class A inherit from Base but B not inherit from base Class B also becomes 28 bytes.
So only when both A and B inherit from Base does my class B's size go from 28 -> 29 bytes.
What is happening that would cause this behavior?
| The C++ object model doesn't allow two distinct subobjects of the same type to exist at the same address.
https://eel.is/c++draft/intro.object#9
Two objects with overlapping lifetimes that are not bit-fields may have the same address if one is nested within the other, or if at least one is a subobject of zero size and they are of different types; otherwise, they have distinct addresses and occupy disjoint bytes of storage.
Here your two subobjects (B::Base)b and (A::Base)(b.a) both have zero size, but they are not of different types, therefore they require distinct addresses.
|
69,977,740 | 70,117,729 | Box2d: How to get cursor position to apply a velocity to a dynamic body in that direction? | I want to apply a velocity vector to a dynamic body in the cursor direction:
void Game::mousePressEvent(QMouseEvent *e){
double angle = atan2(realBall->GetPosition().y - e->pos().y(), realBall->GetPosition().x - e->pos().x());
realBall->SetLinearVelocity(b2Vec2(-cos(angle) * 50, -sin(angle) * 50));
}
But the dynamic body has an incorrect direction, so i think that the cursor position it's wrong.
Thank you for the help!
| First, you must know that in order for your code to work, the coordinates of your screen and the coordinates of box2d must match. Be aware that if you use screen coordinates in pixels, it means that the size of one pixel matches an 1 meter in box2d. But let’s assume that you have already taken all this into account. Then I would not advise you to use trigonometry for calculations. So you can easily make a mistake. In this case, simple vector operations will be enough for you: substraction, scaling and normalizing a vector. You can try this: velocity = (cursor_position - real_ball_position).normalize().scale(50f). In box2d there is a b2Vec class for vector operations. You can read about it in detail in the documentation.
|
69,977,947 | 69,978,019 | Using negation operator ! with std::atomic<uint_32> | I have a working piece of code:
#include <atomic>
#include <cstdint>
int main()
{
std::atomic<uint32_t> foo;
foo = 5;
std::cout << foo.load() << std::endl;
if (!foo) // what is checked here????????????
{
std::cout << "!foo == TRUE\n";
}
else
{
std::cout << "!foo == FALSE\n";
}
return 0;
}
// Output :
// 5
// !foo == FALSE
There is no bool operator on cppreference for std::atomic and CLion doesn't show it as operator. What is checked in if-condition?
| What it is trying to do is convert it to a boolean value so that it can determine which block to run.
Because 5 is a 'truthy' value, it is converting it to true, and then negating that to false. On the other hand, 0 is a 'falsy' value, so it becomes false negated to true.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.