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 |
|---|---|---|---|---|
67,790,189 | 68,827,669 | GStreamer gst_buffer_make_writable seg fault and refcount "hack" | I implemented a custom metadata structure for the buffer in GStreamer. To use this structure I created a pad probe and access the buffer with auto buffer = gst_pad_probe_info_get_buffer(info);, where info is a GstPadProbeInfo *info.
Most elements of the pipeline have writeable buffers and I have no problems with them, ... | If the reference count of the source buffer buf is exactly one, the caller is the sole owner and this function will return the buffer object unchanged.
If there is more than one reference on the object, a copy will be made using gst_buffer_copy. The passed-in buf will be unreffed in that case, and the caller will now o... |
67,791,095 | 67,791,401 | When is a move constructor called in practice? | I've recently learned about move constructors, but a lot of the online resources don't talk about copy elision. Copy elision makes sense to me too, but it left me wondering when is the move constructor ever going to be called without a super contrived example.
From a popular SO post that explained move semantics to me ... | In your examples the moved from objects are temporaries, but thats not always the case when moving. Sometimes we know that we can move because the moved from object will not be used anymore even though it is not a temporary. Consider this type:
struct foo {
foo() = default;
foo(foo&& f) noexcept {
std::... |
67,791,487 | 67,792,022 | How to avoid warning from nested deprecated function call? | I support a C++ library, and want to declare a number of legacy functions as deprecated. Unfortunately, these functions call one another, and I receive warnings from their compilation. For example:
[[deprecated]] void foo();
[[deprecated]] void bar() { foo(); }
I would like to avoid a warning about calling deprecated... | While this does not work for OP's circumstance as posted, on account of bar() invoking foo() from within the library's header, there is a straightforward solution that is applicable to anyone facing the same issue without that specific constraint. So it could be useful to other people landing here.
Effectively, you wan... |
67,791,938 | 67,943,946 | Transform struct A to B | I have two structures with same internal structure.
struct From {
struct X {
std::string name;
std::vector<int> ids;
};
struct Y {
std::string name;
std::vector<X> x_vec;
};
std::vector<Y> y_vec;
};
struct To {
struct X {
std::string name;
std::vector<int> ids;
};
struct Y {
... | struct From {
struct X {
std::string name;
std::vector<int> ids;
};
struct Y {
std::string name;
std::vector<X> x_vec;
};
std::vector<Y> y_vec;
};
struct To {
struct X {
std::string name;
std::vector<int> ids;
explicit X(From::X&& x)
:name(std::move(x.name)), ids(std... |
67,791,966 | 67,792,117 | Secure way to protect an object in c++ | I'm planning on trying to create something really secure and I want to protect it from memory attack (like looking at a specific adress to get an Object in a program (Like how cheater gets information from entities in CS:GO))
Can someone know how the New operator works on c++ and if it protects whats created from this ... | It is not possible to completely prevent something like this happening, however you can it make it more difficult (for example by randomizing the memory locations). Also a relevent link: https://en.wikipedia.org/wiki/Address_space_layout_randomization.
|
67,792,115 | 67,792,326 | Crypto++ HexEncoder not working consistently | Here's my code
#include <cryptopp/hex.h>
#include <string>
#include <iostream>
void hexlify(CryptoPP::byte* bytes, std::string &hex_string, size_t size)
{
CryptoPP::StringSource ss(bytes, size, true, new CryptoPP::HexEncoder(new CryptoPP::StringSink(hex_string)));
}
void unhexlify(std::string hex_string, CryptoP... | void unhexlify(std::string hex_string, CryptoPP::byte* &bytes)
{
std::string decoded;
CryptoPP::StringSource ss(hex_string, true, new CryptoPP::HexDecoder(new CryptoPP::StringSink(decoded)));
std::cout << decoded + "\n"; // For testing
bytes = (CryptoPP::byte*)decoded.data(); // <--
}
You return the... |
67,792,688 | 67,792,824 | Multimap insertion error without insert function | I am not allow to insert values in multi-map like vectors or arrays
using [ ] operator. There is a insert function for insert values in multi-map but how can I insert values using [ ] operator.
Thanks.
#include<bits/stdc++.h>
using namespace std;
int main()
{
multimap<int,int> mp;
mp[0] = -1;
return 0;
}
... | The whole point of multimap is that you can have multiple values at the same key. Keeping that in mind, what is mp[0] supposed to mean?
In std::map<> and std::unordered_map<> it simply means "the value at that key", no sweat. But for std::multimap<> it can't be that simple.
If mp[0] were to return something when using ... |
67,793,080 | 67,793,728 | Casting of json value results in std::domain_error | I am trying to iterate over an array in a json file to retrieve an entry with an ID. The value that I want to compare it to is not a string (the json default type), but an uint64_t. For testing purposes, I wrote this simplified example:
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int... | What version are you using? Because I got next output on latest version:
value: 10
also matching numeric
value: null
terminate called after throwing an instance of 'nlohmann::detail::type_error'
what(): [json.exception.type_error.302] type must be number, but is null
Aborted (core dumped)
|
67,793,445 | 67,793,660 | Overload resolution between va_list and ellipsis differs based on the literal value. Why? | I have two overloaded functions where the only difference is the last argument, in one case being a va_list and in the other case being an ellipsis.
I noticed the selected overload is different depending if this last argument is an integer literal 0 or 1.
I made a simplified working example as follows, where I am exper... | The ... overload will only be selected if there is no implicit conversion sequence to va_list. In other words, the ellipsis always has the lowest possible priority during overload resolution.
Since the definition of va_list is unspecified, in general the results you observe will not be portable: Func(x) could call eith... |
67,793,565 | 67,796,522 | What causes Visual Studio to hide files on some machines but not others? | I have a Visual Studio solution which appears to be fine on one machine, but on another machine it has decided to hide all of the files in a single project.
None of the nodes can be double-clicked, and Studio refuses to allow any context menus to function.
What might cause this effect in Visual Studio?
The source appe... | Ok, this appears to have been solved now.
It seems the answer to this was to delete the .vs folder for the solution.
I guess something got corrupted in the copy on one machine.
Please note that this appeared to screw up the compilation of the entire solution at first.
However it turns out that it just forgot which plat... |
67,793,656 | 67,793,765 | Why don't we update rank for disjoint set after path compression? | I have made a template for disjoint set with rank heuristic and path compression.
template <typename T>
class disJSet
{
map<T,T> parent;
map<T,int> rank;
public:
//Linear time complexity
void makeSet(vector<T> it)
{
for(T i:it)
{
parent[i]=i;
rank[i]=0;
... | You can't update rank after path compression, because there may be other paths to that root which are longer than the new path length.
And you don't need to update the rank after path compression, because it only needs to represent an upper bound on the path length.
|
67,794,331 | 67,796,079 | Safe place for an ATL object to release itself | Is there a strategy for safely allowing an ATL object to release itself in response to a Windows message or sink event?
In other words, let's say you have an ATL class that's subclassing some windows (using a message map) and/or sinking events from COM objects (using a sink map). And you'd like the class to release it... | you can do next implementation
class MySubClass : public CWindowImplBaseT<>
{
ULONG dwRefCount = 1;
BEGIN_MSG_MAP(MySubClass)
MESSAGE_HANDLER(WM_CHAR, OnChar)
END_MSG_MAP()
LRESULT OnChar(UINT uMsg, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
// f... |
67,794,389 | 67,795,771 | DNS functions are not found | I am trying to build TerraGear from the FlightGear project. I got no errors while compiling but while linking I'm getting undefined reference to multiple functions all starting with dns_ and none of them is present in /usr/lib/x86_64-linux-gnu/libdns.so.1100. In which library are these defined ? Because, I googled for ... | Okay, I should do more research before asking here ;) : these functions come from libudns, and I just forgot to link it ! :@
|
67,794,928 | 67,794,996 | Different output depending on whether or not I print the return value | So I have a simple snippet of C++ code which is SUPPOSED to insert a node into a binary search tree. It returns true if the value is successfully inserted and false if the value is already in the tree.
struct Node {
int data;
Node* parent = nullptr;
Node* left = nullptr;
Node* right = nullptr;
};
bool insert(N... | You invoke undefined behaviour right there:
Node newNode = {data, &root};
root.right = &newNode;
This stores, in your tree, the address of a stack variable. As soon as the function returns, it's not legal anymore to dereference this Node's children. From there, anything could happen.
You probably want something li... |
67,795,012 | 67,795,267 | Saving high scores of a game to a file and then accessing them, how? | I want to save all the scores of my game (a simple snake game) to a file and then read all the scores. Problem is, i dont know how to save them without knowing how many there will be.
Example:
one person plays it, gets 1200 score, it gets saved;
2nd person plays it, gets 1000 and sees the first person's score;
3r... | From what you describe, what you want is:
open the file for writing
write to the file
be done with writing to the file
open the file for reading
read from the file
be done with reading form the file.
So your code should reflect that sequence!
The key point is that you are ever only reading or writing from the file at... |
67,795,632 | 67,795,680 | Comparing an int64_t value with another uint32_t value | int main(){
int64_t a = -1;
uint32_t b = -1;
bool c = a > b;
std:: cout << c << std::endl;
return 0;
}
My understanding is b which is a smaller type will be converted to the bigger type of a (unit32 to int64):
Comparing int with long and others
Then a which is a signed value will be turned to an unsigned value... | Given int64_t a and uint32_b, in a > b, b will be zero-extended to 64 bits (remember, it's unsigned, so it's really 4294967295 and not -1), and then a comparison is performed. The relevant comparison is that -1 > 4294967295 is false.
Relevant bits of the C++ standard are under "6.8.4 Integer conversion rank [conv.rank]... |
67,796,344 | 67,797,659 | Which way to synchronize vkQueueSubmit() to use? |
I have a function that copies data from one buffer to another, I need to synchronize its execution.
I have such a bad option:
void MainWindow::copyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size)
{
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(logicalDevice, &allocInfo, &commandBuffe... | Both functions are bad in the same way. They both block the CPU from doing anything until the transfer is done. And they both could be used to potentially submit multiple CBs to the same queue in the same frame, but with different submit commands.
Neither is desirable if performance is something you care about.
Ultimat... |
67,796,383 | 67,796,499 | How do usual arithmetic conversions work? | I was running this code in VS2019:
#include<iostream>
#include<string>
#include<typeinfo>
using namespace std;
int main() {
string mystring = "hello world";
for (int j = 0; j < 10; j++) {
if (mystring[j + 1] == 'w') {
cout<<"string contains w letter\n";
}
else {
... | The "C26451" warning is not a standard compiler warning. It's part of the C++ Code Guidelines Checker which is giving you 'recommendations'. For more on this feature, see Microsoft Docs.
In C++ Core Guidelines the specific recommendation the checker is using here is: ES.103: Don't overflow.
The reason this only happens... |
67,796,996 | 67,797,432 | How to safely clock_cast days? | I'm using HowardHinnant/date in lieu of the new C++20 calendar/timezone facilities that are not yet available in Clang/GCC. My question applies equally to both implementations: How do I safely clock_cast time_points having days duration?
When I try:
using namespace date; // or using std::chrono in C++20
tai_time<days> ... | The reason that the clock_cast insists on at least seconds precision is because the offset between the epochs of system_clock and tai_clock has a precision of seconds:
auto diff = sys_days{} - clock_cast<system_clock>(tai_time<days>{});
cout << diff << " == " << duration<double, days::period>{diff} << '\n';
Output:
37... |
67,797,060 | 67,797,105 | Specializing constructors with requires for a possibly reference type | I need to make a wrapper class template that can possibly contain a reference member. I have both copy and move constructors defined, where references of the wrapped type are passed as arguments. This is all good if the type is not a reference. But if it is, both type& and type&& become lvalue references, and the two c... | Every function you define has to be distinct in some way - different name, different parameters, different constraints, etc.
For T=int&, your three constructors are:
S(int&) requires (!std::is_reference_v<int&>);
S(int&) requires (!std::is_reference_v<int&>);
S(int&) requires (std::is_reference_v<int&>);
The first two... |
67,797,148 | 67,797,174 | Surprising behaviour with an unordered_set of pairs | How can the unordered_set can hold both (0, 1) and (1, 0) if they have the same hash value?
#include <iostream>
#include <unordered_set>
#include <utility>
using namespace std;
struct PairHash
{
template <class T1, class T2>
size_t operator()(pair<T1, T2> const &p) const
{
size_t hash_first = hash... | unordered_set can hold one instance of any unique data-value; it is not limited to only holding data-values with unique hash-values. In particular, when two data-values are different (according to their == operator) but both hash to the same hash-value, the unordered_set will make arrangements to hold both of them reg... |
67,797,438 | 67,797,838 | How to get and set class fields in class methods | I have an .h file that describes the fields and methods of the class. The implementation of the methods is located in the .cpp file. For example, I have 2 fields:
int x = 0;
int y = 0;
And setters and getters for them.
On pressing a button on the form, If I want the value of the field to change, for example, x = y + ... | Better to answer in terms of C#. C# has properties that make usage of members and setters/getters similar syntactically. Creation of setters/getters are easy. And because the cost of usage of properties are low it's usually preferable to use properties. Because coder can add some data verification of input, etc. later ... |
67,797,518 | 67,797,778 | How do I get elements into a nested vector with an initializer list c++ | I have a Matrix class which contains a vector inside a vector as data within it. I would like to be able to insert elements through initializer lists.
An example of this would be the following:
#include <vector>
int main(void) {
std::vector<std::vector<int>> v = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10... |
I would like to be able to insert elements through initializer lists. ...I know the size of the outer initializer list (in the above example it is two), but I don't know how to get the size of the second initializer list.
Perhaps I misunderstand you, but the code snippet below should give you a start. It prints the s... |
67,797,762 | 67,797,800 | Looking for a recursive solution to the problem given below | I want to find the longest island where "1" represents land and "0" represent water. Furthermore, i want to do it using a recursive solution. I am getting a stack overflow error. Is something wrong with the function calling??
int ans;
vector<vector<int>> dir = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
void calcarea(vector<v... | You need to mark the place as "visited" so you won't check it again.
You can do something like this in the calcarea function:
if(grid[t1][t2] == 1)
{
grid[t1][t2] = 0; // add this
ans += 1;
calcarea(grid, t1, t2, m, n, ans);
}
|
67,797,817 | 67,798,149 | how to check a string for specific conditions in C++ | following snippet shows a very small part of my current output:
1464: ebfffe4d bl da0 <memcpy@plt>
14bc: ebfffe37 bl da0 <memcpy@plt>
every line from the output refers to a string. What I want to archieve is, that in this
case only memcpy@plt will be printed once. When a string cont... | We can use a unordered_set to deduplicate the substring, if the same substring has already been printed, then skip it.
This step can be extracted into a single method to follow the single responsibility principle, which is more natural than process the duplication in print function, this work is left for you.
We use un... |
67,798,126 | 67,841,330 | How to copy dependent executable also to the same folder where the main executable lives while deploying with CQtDeployer? | I will start my question with an example. Suppose I have a qt application named 'MyApp' and there are two dependent executable 'xprintidle' and 'xdotool' . For perfect working of my application I need MyApp, xprintidle and xdotool are to be in same folder after installing.
I am using CQtDeployer to deploy my applicatio... | cqtdeployer -bin MyApp,xprintidle,xdotool
This will copy all three in the same folder with MyApp
|
67,798,458 | 67,804,712 | bounded arrays vs unbounded arrays in C++ | I stumbled upon std::is_bounded_array and std::is_unbounded_array, and I also know that std::make_unique doesn't support bounded arrays.
Can someone shed more light into why that is so and what are the differences between creating a bounded array vs creating an unbounded array?
EDIT: This is different from what is an u... | A curious case where bounded vs unbounded arrays arrays is relevant is one of the few cases in C++ where the declared type of an object differs from the declared type of the same object elsewhere. Namely, when the (incomplete) declared type of an array object is an array of unknown bound vs. when the declared type is a... |
67,798,506 | 67,798,596 | What is the difference between std::trivially_copyable_v and std::is_pod_v (std::is_standard_layout && std::is_trivial_v) | I was looking at the documentation for both of these type traits and I'm not sure what the difference is. I'm no language lawyer, but as far as I could tell, they are both valid for "memcpy-able" types.
Can they be used interchangeably?
| No the terms cannot be used interchangeably. Both terms denote types that can be used with memcpy, and anything that's a POD is trivially copyable, but something that's trivially copyable is not necessarily POD.
In this simple example, you can see that foo is POD (and subsequently trivially copyable), while bar is not ... |
67,798,598 | 67,798,701 | How to count a certain character/ replaced character | ...
v.push_back(s);
}
for (int i =0; i < v.size(); ++i)
{
int a_pos = -1;
a_pos = v[i].find('a');
if (a_pos != -1)
v[i][a_pos] = '@';
}
cout<< v.size() << " ";
Edited to remove my previous whole code, as only this part was/is needed in order to answer my question. Rest of code solved the issue, while this part 'cou... | If you need it to output the count of the replacements then the most direct way is to just introduce a dedicated counter variable and increment it at every replacement:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> v;
string s;
int numOfStrings;
... |
67,799,074 | 67,799,094 | How to achieve partial output to cmd window and partial redirection to file for c++ program? | I know how to use pipe operator to redirect whole output of a c++ executable file(generated by my c++ code),but the question is that there are some contents that do not need to redirect to file, but to cmd window.
In my limited experience with c++ programming, I guess there may be some kind of redirection method with h... | Use std::cout for things that you want to redirect to the file, and std::cerr for things that you want to print to the command window. Normal redirection with > and | only affects the former.
|
67,799,265 | 67,810,973 | Usage of compression IO functions in apache arrow | I have been implementing a suite of RecordBatchReaders for a genomics toolset. The standard unit of work is a RecordBatch. I ended up implementing a lot of my own compression and IO tools instead of using the existing utilities in the arrow cpp platform because I was confused about them. Are there any clear examples of... | Here is an example program that inflates a compressed zlib file and reads it as CSV.
#include <iostream>
#include <arrow/api.h>
#include <arrow/csv/api.h>
#include <arrow/io/api.h>
#include <arrow/util/compression.h>
#include <arrow/util/logging.h>
arrow::Status RunMain(int argc, char **argv) {
if (argc < 2) {
... |
67,799,303 | 67,799,481 | Does a constructor in c++ code return any object? | The problem is not exactly as the question. The real question is: why did my code work?
I posted this question on stackoverflow->make objects in function arguments. What I asked is whether you can do something similar to:
....
// java code
Obj o1 = new Obj(new Objectt()); // we made and passed a new object in a functio... | A constructor doesn't return anything, but nevertheless C++ lets you declare a temporary/anonymous object as an argument to a function, in certain cases. An object declared this way will be constructed on the stack just before the function is called, passed to the function, and then destroyed immediately after the fun... |
67,799,351 | 67,799,669 | do constant calculations in #define consume resources? | as far as I'm concerned, constants and definitions in c/c++ do not consume memory and other resources, but that is a different story when we use definitions as macros and put some calculations inside it. take a look at the code:
#include "math.h"
#define a 12.2
#define b 5.8
#define c a*b
#define d sqrt(c)
When we use... |
as far as I'm concerned, constants and definitions in c/c++ do not consume memory and other resources,
It depends on what you mean by that. Constants appearing in expressions that potentially are evaluated at runtime have to be represented in the program somehow. Under most circumstances, that will take some space.... |
67,799,720 | 67,800,045 | C++ program is not giving output involving large array | Why am I not getting any output from this program?
I tried resolving every issue from YouTube and stack as well but no luck. I tried using vs code extensions and I don't if it has anything to do with JSON configurations.
This is not showing any errors but not showing any output as well.
#include <iostream>
#include <bi... | You get no output because your program doesn't run. Instead it crashes because of the too large array you're attempting to allocate on the stack. You would know it crashes if you were to debug it.
const int N = 1e6 + 2;
int idx[N];
One way of fixing it, which I don't recommend, is to allocate it on the heap:
int *idx ... |
67,799,891 | 67,801,448 | How to make sf::Vector2f transform(float t) speed faster? | #include <iostream>
#include <SFML/Graphics.hpp>
float period_ms = 5000.f;
using namespace std;
sf::Vector2f transform(float t)
{
float const ellipse_width = 500.f;
float const ellipse_height = 500.f;
float const a = ellipse_width / 2.f;
float const b = ellipse_height / 2.f;
float const pi = 3.1... | You can add a time factor variable. This would require you to change some things about time management:
Restart the clock each frame and acumulate the time in a separate variable.
Have a new variable with the time factor, that multiplies the delta time each frame.
float timeFactor = 1.0f;
float accTime = 0.0f;
For e... |
67,800,132 | 67,800,484 | How can I connect QtcpSockets to about 100 servers without a UI hang? | How can I connect QtcpSockets to about 100 servers without a UI hang?
When I create 100 QTcpSockets to connect to each server and call the connectToHost() function, the QDialog stuck. Is there a way to run the connectToHost() part as a background job?
As a result, all connections are made, but while trying to connect (... | Time-consuming tasks should not be run on the main thread. In that case there are 2 strategies:
Use of threads.
Divide into subtasks and execute in parts every T seconds.
In this case I think the second option is the best using QTimeLine.
*.h
private:
void handleFrameChanged(int i);
QTimeLine timeLine;
*.cpp
{... |
67,800,595 | 67,800,634 | Logic error on counting consonants in a string C++ | So Im trying to count count vowels, consonants and special character. I got the vowels and special part to work, but not the consonants. Here's the code;
#include <iostream>
using namespace std;
void characterType(string);
int main()
{
string input = "Testing a sentence.";
characterType(input);
}
void charac... | The definitions
int vowel, consonant, special = 0;
only initialized special to 0. The other two variables are uninitialized and will have indeterminate values.
You need to explicitly initialize all variables you want to have a specific initial value:
int vowel = 0, consonant = 0, special = 0;
This is why many recomme... |
67,801,088 | 67,802,068 | How to stack a char[] inside a structure in C++ | I have been beating my head over this for a while now. I can't find any proper reference to this online.
I have a structure with char data[] inside it. Say for example -
struct mystruct
{
char mydata[];
};
How do I create a mystruct variable with length of data whatever I want.
This works-
mystruct my {"Test"};
B... | In mystruct you declare char mydata[]; as an incomplete type (an array, but not how-many). The specific use of an object of that type comes from C. By allowing an array of incomplete type as the last member of a struct, in C this provides you with the ability to dynamically allocate storage for the struct itself, plus ... |
67,801,375 | 67,801,654 | I have some problems with fopen() for c-string | I have a file name stored as c-string. I need to open the file and count lines in it.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
char str[] = "myfile.txt";
FILE* file = fopen(str, "r");
int counter = 0, ch = 0;
while (EOF != (ch = fgetc(file)))
if (ch == '... | please use string.c_str()
int main() {
string path = "myfile.txt";
FILE* file = fopen(path.c_str(), "r");
int counter = 0, ch = 0;
while (EOF != (ch = fgetc(file)))
if (ch == '\n')
++counter;
fclose(file);
printf("%d", counter);
return 0;
}
|
67,801,438 | 69,058,311 | DX12: Is there a way to extract any information from a PSO? | I'm pretty new to PSOs. I was wondering if there is a way to extract a D3D12_GRAPHICS_PIPELINE_STATE_DESC structure for example, holding the info for a particular PSO? Or if there is any way really to access any information from a PipelineStateObject? Or does a PSO become a black box once first created?
| Once created, a PSO becomes a black box, you can't retrieve any info about it anymore.
The only thing your can retrieve is the "binary blob" by calling :
pso->GetCachedBlob
Which allows you to save it to disk (so you can create it back using the cached version, which is faster).
Please note that this blob is Hardware ... |
67,801,625 | 67,802,827 | ROS/catkin compiled C++ file won't find image sources | I created a C++ game that uses images from a folder in the same parent directory.
/game_folder
----/Images
--------icon1.png
--------icon2.png
----game.cpp
Program uses Allegro 5 library to include images:
ALLEGRO_BITMAP* icon1 = al_load_bitmap("Images/icon1.png");
ALLEGRO_BITMAP* icon2 = al_load_bitmap("Images/icon2.... | The reason why this does not work is that your code gets compiled and is then placed inside the catkin_ws/devel/lib/<package_name> folder (lib not include!). Then when you launch the code it will look only in paths relative to the executable. This means you would actually have to place it inside the catkin_ws/devel/lib... |
67,801,681 | 67,801,842 | map inside map in C++ | I have a difficult time creating nested maps in C++.
First of all I have typedefed my types
typedef std::map<std::variant<int, std::string>, std::variant<int, long long int, std::string>> SimpleDict;
typedef std::map<std::variant<int, std::string>, std::variant<int, std::string,std::vector<SimpleDict>,SimpleDict>> Comp... | In both cases, you miss one set of braces to denote "a pair in top level map":
typedef std::map< std::string, std::map<std::string, std::string> > ComplexDict2;
ComplexDict2 m = {
{ //first pair of map
"MAC0", {
{"TAG0", "111001011000"},
{"SEQ", "110000100100"},
{"IOD", "... |
67,802,016 | 68,033,138 | Speed up reading frames from a video file | Is there any way with OpenCV to read frames from a video file in parallel or speed up reading in some other way?
I have tried using the cap.read(frame) function in multiple threads, but application crashes.
I also tried with VideoCapture object array caps, all referencing the same video file, then in each thread I can ... | I have not found any other way to speed up the reading other than changing the video format. I changed it to HapQ (original format was Apple ProRes H422) and the performance was noticeably better, about 30% faster (20-25 ms for reading frames compared to 30-35 ms before).
|
67,802,356 | 67,803,199 | How to make cmake pass D argument to ar for reproducible build of a static library | My project uses CMake to build both static and dynamic libraries from the same C++ code. The dynamic library file (.so) stays the same on rebuild, but the static library file (.a) changes on every rebuild. I have come to understand that it's because of the behaviour of ar tool and I need to pass D argument to create de... | The following works to set arguments for ar and ranlib for generating deterministic static library output files:
set(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> qcD <TARGET> <LINK_FLAGS> <OBJECTS>")
set(CMAKE_CXX_ARCHIVE_FINISH "<CMAKE_RANLIB> -D <TARGET>")
|
67,802,824 | 67,802,902 | No viable conversion from '__wrap_iter<std::__1::vector<MenuItem *>::const_pointer>' to '__wrap_iter<std::__1::vector<MenuItem>::pointer>' | I am working on a file that I have to iterate through the object's vector but for some reason I am getting this error:
No viable conversion from '__wrap_iter<std::__1::vector<MenuItem *>::const_pointer>' to '__wrap_iter<std::__1::vector<MenuItem>::pointer>'
this is the line which causes the error:
for (vector<MenuItem... | There are two problems here. First, a function with the signature
const vector<MenuItem*>* menuItems() const;
(virtual or not) returns a pointer to a const-qualified instance of a vector. The begin() and end() member functions of const-qualfied vectors return const_iterators, not iterators. As it makes sense that you ... |
67,803,256 | 67,804,831 | Swift Package Manager: add compile flag to a single file -fno-objc-arc | Overview
I'm porting an C++ / ObjC++ library to Swift Package Manager. The library targets common Apple platforms (iOS, macOS). Currently, the library can be built using xcodebuild and a static library target.
Question
Since the library contains C++ <> ObjC bridging code, it has one file compiled with the flag -fno-obj... | I believe it is not possible at the moment. Yet we have a hope that this proposal will be accepted and your (and mine) problem will be solved. There are few alternatives that may help:
Use Cocoa pods
Use submodules
Use precompiled binary
|
67,803,329 | 67,806,626 | Write 4 byte integers into char* array | I've got a QByteArray of a given size. Accessing the raw data of the array returns char*, basically a character array.
I want to fill the QByteArray's whole size with a uint32_t value.
What is the safest and most efficient way to do this? I know I could use the Qt functions for appending data into an empty QByteArray, ... | Accessing a char array as if it were an int array is a violation of the strict aliasing rule.
Aside from that, it is possible that your array is misaligned for int. Misaligned access is a major problem as some processors can't do it at all, while others can do it but very slowly. It is also undefined behavior.
Here's a... |
67,803,332 | 67,803,407 | How can i call a member function pointer from another member function? | I have a class which has a data memeber which store a member function pointer. The pointer points to different member functions in different time. I would like to call this funcion pointer from another member function. How can i do this?
class A {
void (A::*fnPointer)() = nullptr;
void callerMemberFunction(){
... | You need to specify which object to call the function on:
(this->*fnPointer)();
|
67,803,474 | 67,806,194 | Counting occurrence of each character in string C++ | So i wanted to count all the characters in a string and categorized them in vowels, consonants, and specials character. For example;
Enter string: sentence example ..
Vowels: e(5) a(1)
Consonants: s(1) n(1) t(1) c(1) x(1) m(1) p(1) l(1)
Specials: blank space .(2)
Here's coding:
void characterType(string input)
{
in... | Since you want to do this and it's not some type of assignment, here's how I would approach the problem, using modern C++ features:
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
int main() {
std::map<char, std::size_t> occurrance;
std::string input{"This is A long string with lot... |
67,803,479 | 67,803,580 | C++ map and unordered_map: emplace to do an upsert/update/replace (for case where value type has no default-constructor)? | This must be a duplicate... if so, help me find, else... help.
I am trying to update an entry in a map, where the mapped-type has no default constructor (and possibly no copy constructor).
Usually we would do something like this:
std::map<K, V> myMap;
myMap[k] = V(...);
However, for the case that we don't have a defau... | When you can use C++17, there is also `std::map<K, V>::insert_or_assign, which you can use as follows.
std::map<K, V> myMap;
myMap.insert_or_assign(myKey, myMappedTypeInstance);
The second argument is perfectly forwarded, so in order to avoid copies, you might want
myMap.insert_or_assign(myKey, std::move(myMappedType... |
67,803,820 | 67,805,222 | How do namespace's with same name but different scope (e.g. foo, bar::foo) work? | If there are two namespaces named Foo and Bar and there is a namespace named Foo inside Bar. If I refer to a variable Foo::i from inside Bar will it search for i in both Foo and Bar::Foo. If not, is it possible to make the compiler search in both namespaces when i doesn't exist in Bar::Foo?
More concrentely in the belo... | If you can change b::a, then you can indeed make certain declarations available in b::a from ::a as fallbacks:
namespace a {
int i = 1;
int j = 2;
}
namespace b {
namespace a {
namespace detail {
using ::a::i; // Selectively bring declarations from ::a here
}
using names... |
67,804,784 | 67,808,573 | C++ code generating errors LNK2005 & LNK1169 on VS2019 | The following code generates errors LNK2005 & LNK1169 on Visual Studio 2019.
LNK2005: "void__cdecl OverloadingPlus(void)" (?OverloadingPlus@@YAXXZ) already defined in main.obj
LNK1169: one or more multiply defined symbols found
I reached this point by following a course on Udemy, where the instructor seems to have no... | The issue seems to be related to VS2019. Renaming the file to something different, rebuilding the project and renaming the file back to its original name fixed the issue.
While using inline as others suggested did circumvent the issue, it does not solve this specific problem as the conflicting file was not being inclu... |
67,805,199 | 67,846,588 | After running a project in Qt Debug build, the binary (exe) disappears and object files are shrunk. How to fix that? | My Qt Creator is 4.11 which is based on Qt 5.14 in Ubuntu 17.04. Due to ongoing development, I have not updated Qt Creator and Ubuntu to avoid disturbing the working setup.
Whenever I run it in Debug build mode, it compiles fine and runs the executable. But then if I check the "build--*" directory, the binary file (viz... | This issue is not related to Qt, but related to our own code. We have a module which Gzips all files in a given directory recursively.
However, if the directory path is empty, then original binary's path is taken as a zipping directory. Hence all the object files were zipped and somehow the binary file itself was disap... |
67,807,562 | 67,807,801 | How to get numeric updown control? | I have searched in toolbox and many post but don't know where to find this type of control to use on MFC:
Does such a control exist in MFC?
| The control is known as a "Spin Control" in the Visual Studio Resource editor and they are normally associated with a "Buddy" edit control. You can set this in the "Behaviour" group of its "Properties" window – with "Auto Buddy" set to "True", it will associate with the 'nearest' edit control (actually, the previous co... |
67,807,613 | 67,807,826 | Cleanly handling void as generic return type of labmda in C++ | I am trying to write a function like this:
template <typename T>
void testActionBehavesIdentically(Foo& fooA, Foo& fooB, std::function<T(Foo&)> action)
if (std::is_same<T, void>::value)
{
// perform action even if T is void
action(fooA);
action(fooB);
}
else
{
// if T is not void, test also re... | Right now what's happening is that the compiler still will compile both if branches (since it doesn't actually know which will be called until runtime). This results in a failure since one of the branches doesn't compile correctly. There are a couple fixes (from the comments):
If your compiler supports it this would be... |
67,808,201 | 67,810,188 | Base type is not converting to derived type yet can call its functions and variables | As far as i know created base type can't be casted into derived type on OOP. But i have encountered something like this and i wasn't expecting to work. Here is the example classes:
class Base {
public:
virtual void Call1() { std::cout << "Base call 1" << std::endl; }
virtual void Call2() { std::cout << "Base c... | What's happening here is covered mostly by the comments, but there's one thing there I haven't seen yet: how the SetAll() method is setting memory, and where it is setting it. For the record, what I describe below is what is probably happening, as you are heavily into "Undefined Behavior" here.
Derived* d1 = (Derived*... |
67,808,914 | 67,809,166 | Chained shared_ptr vector initialization | I use the following example code to initialize vector of shared_ptr:
#include <iostream>
#include <memory>
#include <string>
#include <vector>
struct Song
{
std::wstring artist;
std::wstring title;
Song(const std::wstring& artist_, const std::wstring& title_) :
artist{ artist_ }, title{ title_ } {}... | You can use a nested type to initalize a type which is nested one level deeper like that
vector<shared_ptr<Song>> v {
make_shared<Song>(L"Bob Dylan", L"The Times They Are A Changing"),
make_shared<Song>(L"Aretha Franklin", L"Bridge Over Troubled Water"),
make_shared<Song>(L"Thalía", L"Entre El Mar y Una Estrella... |
67,808,976 | 67,809,069 | Determine size of std::array return type without a function call | I have a class B that takes classes like A as a template parameter.
template<typename T>
class B{
///...
Each T has an operator()() that returns an std::array<double, N>. I would like each specialization B<T> to be able to deduce N without additional requirement on the Ts and without calling the operator()(). How can ... | You can add a member to B, like this
static constexpr std::size_t ArraySize = std::tuple_size_v<decltype(std::declval<T&>()())>;
Here's a demo
|
67,809,035 | 67,809,468 | Is there a better way of reading the name of the file from the command line? | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc ,char *argv[]){
int *array;
int pl;
string filename;
if (argc == 2){
filename = argv[1];
}
fstream f(filename, ios::in| ios::out);
f >> pl;
array = new int[pl];
for(int i=0; i<p... | Your solution is perfectly fine and is along the fastest to achieve your goal. Anything else, including classes, just need more effort/typing to do the same with no advantage. I would only add a minimal error handling:
#include <iostream>
#include <string>
using namespace std;
int main(int argc ,char *argv[]){
if... |
67,809,345 | 67,809,515 | Do C++ compilers perform tricks to make moving data within classes faster? | I'm curious about the optimisations that C++ compilers do when it comes to moving data around during run-time. Recently, I've been thinking about how classes are passed through the code as I know that if you pass a bool to a function you don't need to define it as const& but if you have, for example, a std::vector<T> t... | Yes, the compiler will, by default, copy an int64_t and a class or struct containing two int_32_t the same way. Both cases are simply 8 bytes of raw memory on mainstream architectures, so at the low level of copying data they will be treated as such. (For classes and structs this behavior can be changed by overriding t... |
67,809,374 | 67,809,452 | Why my pointer becomes dangling pointer in c++? | My main language is C#, and I'm learning opengl with scarce c++ background.
// readShaderSource returns const string
// no warning
auto vShaderStr = readShaderSource("vshader.glsl");
auto vShaderSource = vShaderStr.c_str();
// dangling pointer warning
auto vShaderSource = readShaderSource("vshader.glsl").c_str();
Wh... |
What I thought about dangling pointer is something like this ... which does not seem to be the case.
It is the same case, actually. Just in a different form.
The pointer returned by std::string::c_str() is valid only for as long as the std::string object remains alive (and unmodified).
readShaderSource() returns a t... |
67,809,386 | 67,809,506 | Can a self-contained C++ concept match a particular template with any arguments? | I'd like to have a C++ concept that matches a particular template type regardless of one of the template arguments. I can, of course, do this using some other helper declarations to pick apart the template type. But one of the benefits of concepts and requires expressions in particular is that they eliminate many of ... | I don't know what the broader problem might be, but we can decompose the problem of checking that something is a basic_string<char, char_traits<char>, A> into the problems of: (1) it's a basic_string and (2) its first two types are char and char_traits<char>.
The first problem is the standard is_specialization_of trait... |
67,809,411 | 67,809,699 | Check if using termux or normal distro in C++ | I have a program that checks if apt, apt-get and dpkg are installed. But now I need to check if using a normal distro (like Mint, Ubuntu, etc.) or using termux to change the path, how can I do that?
I already tried this, but then it says the path doesn't exist (on a normal distro):
std::ifstream aptget("/usr/bin/apt-ge... | The problem with your code is that you are checking if the ifsteram is open before you open it.
As you can look in this documentation: std::ifstream::is_open:
Returns whether the stream is currently associated to a file.
Streams can be associated to files by a successful call to member open or directly on construction... |
67,810,378 | 67,819,230 | Can I build wxwidgets with clang++? | There are walkthroughs to build wxwidgets with common compilers on windows, such as MSVC or MinGW, but there are no options for clang. I do have the other two compilers, but I dislike using Visual Studio for projects that are not C# or other .NET languages and I just don't like MinGW, nothing specifically. I use clang ... | You can definitely build wxGTK and wxMac under Linux and Mac respectively with clang and I think people did build wxMSW under Windows with it too, but it's a less commonly used compiler there, so your best bet would be to just try doing it. If you run into any problems, please free to open tickets on wxTrac, we do want... |
67,810,691 | 67,811,420 | C++ - Invalid operands to binary expression 'basic_ostream<char>' | I have an 'IntList' class with a dynamic array of integers, but the following fragment of test code gives me troubles:
main.cpp
#include <iostream>
#include "IntList.hpp"
using std::cout;
using std::endl;
int main(int argc, const char * argv[]) {
IntList list{};
cout << "list-1 -> " << list << endl;
return... | It appears (from the fragments you have shown) that there is no declaration of your << override in the header file (IntList.hpp). Thus, the code in your main function is not (and cannot be) aware of that override, which is provided in a separate source file.
You need to add a declaration of that override function in th... |
67,810,702 | 67,833,248 | How to "fully bind" a constant buffer view to a descriptor range? | I am currently learning DirectX 12 and trying to get a demo application running. I am currently stuck at creating a pipeline state object using a root signature. I am using dxc to compile my vertex shader:
./dxc -T vs_6_3 -E main -Fo "basic.vert.dxi" -D DXIL "basic.vert"
My shader looks like this:
#pragma pack_matrix(... | Long story short: shader visibility in DX12 is not a bit field, like in Vulkan, so setting the visibility to D3D12_SHADER_VISIBILITY_VERTEX | D3D12_SHADER_VISIBILITY_PIXEL results in the parameter only being visible to the pixel shader. Setting it to D3D12_SHADER_VISIBILITY_ALL solved my problem.
|
67,810,705 | 67,815,017 | C++/cli I'm having an issue that my std::list is empty | My problem is that I am trying to save 3 strings in a list to take the same place how ever it doesn't work for me for some reason, I have tried using vector instead of list but same issue appeared. I know for a fact that the variables have correct input so I don't understand why it wouldn't push the values to the list ... | Replacing
serviceOrderNumber = serviceOrder_Number;
With
serviceOrder_Number = serviceOrderNumber;
Has fixed my issue
Thanks to 1201ProgramAlarm for solving my problem.
|
67,810,807 | 67,825,835 | How to execute a method of a dll (C++) with parameters with command prompt | I created a dll(in c++) with one method called "changeSize"(in kb) which has the argument "size". So the method basically sets a new size of a file (the file that is stated in the method).
Now I want to execute the method of this dll in command prompt.
I've tried to execute the method with the help of "rundll32.exe", s... | Question 1: First of all, not every .dll can be executed with rundll32.exe, because the .dlls need a special signature, so a special structure. For example is an EntryPoint necessary.
Here it says how the structure looks like:
https://stackoverflow.com/a/11913860/16104144
Question 2: The arguments are stored in LPSTR ... |
67,810,969 | 67,811,140 | Reverse a number without converting it to string in C++ | I am trying to make a program in c++ to reverse a number it is ok with a number like 1234 but if am trying to input a number like 5430 it is showing 345 and the same in case the number starting with zero eg: if input 0234 it will show 432.
Can somebody tell me how to handle zeros at starting and ending.
I have to store... | If you are not allowed to use a std::string to std::reverse the number, you could store the number of digits in the original number and use the I/O manipulators std::setw() and std::setfill() to add the leading zeroes when you print the reversed number.
Example:
#include <iomanip>
#include <iostream>
int main(){
i... |
67,811,636 | 67,811,789 | Determining in template function the shortest float type that faithfully represents integer type parameter | template< typename int_type >
bool foo( int_type argument )
{
float_type value = argument; // float_type must faithfully represent argument.
...
}
That is, I'd like to derive within the template function the shortest floating point type float_type that has at least as many significant digits as the template pa... | Indeed this is possible without directly using specializations. You can use std::conditional from the standard header type_traits to define a type conditionally based on the size of int_type:
template< typename int_type >
bool foo(int_type argument)
{
using float_type = std::conditional<sizeof(int_type) <= 4,
... |
67,811,685 | 67,811,819 | find prime numbers up to n digits using only 1 loop statement | I am new in programming and trying to solve some questions and in this question, I am trying to find prime numbers up to n digits using only 1 loop statement.
| //this program will print prime number from 2 to N . and break loop
without using break statment
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int range;
cin>>range;
int num=2;
for(int i=2;i<=num;i++){
if(num>range){
... |
67,811,693 | 67,811,777 | Custom unique_ptr inside std::pair and standard collections | I'm trying to use a custom unique_ptr inside a std::pair inside collections. Below is what I have so far, but if I uncomment the first commented-out line then I get an error:
No matching constructor for initialization of PairedThing1
So I haven't gotten as far as putting these pairs in a container (the second comment... | You can't copy a std::unique_ptr (hence the name). You have to move it.
PairedThing1 duo(uni, 42);
should be
PairedThing1 duo(std::move(uni), 42);
likewise the 2nd commented piece of code should be
someThings.insert(someThings.begin(), std::move(duo));
|
67,811,930 | 67,811,977 | Is it possible to send a window handle with WM_COPYDATA? | I am trying to send an HWND with the WM_COPYDATA IPC method.
So far when sending a string LPCTSTR it works.
LPCTSTR str = L"Test";
COPYDATASTRUCT cds;
cds.dwData = 20;
cds.cbData = sizeof(TCHAR) * wcslen(str);
cds.lpData = (PVOID)str;
LRESULT l = SendMessage(myhWnd, WM_COPYDATA, (WPARAM)nullptr, (LPARAM)&cds);
But whe... | An HWND is not a pointer. You most likely want:
COPYDATASTRUCT cds;
cds.dwData = 20;
cds.cbData = sizeof(HWND);
cds.lpData = &targetWnd;
// ^
LRESULT l = SendMessage(myhWnd, WM_COPYDATA, (WPARAM)nullptr, (LPARAM)&cds);
Also, there seems to be some confusion between the source and destination HWNDs, but perh... |
67,812,318 | 67,813,664 | How do you use std::declval find the return value of a template function? | I have a class B that takes a template argument such as A. I create a B b and call B::operator()(A a). Regardless of the type of a, b(a) should return a double. I would like to deduce this from outside of B using decltype.
If I had a function B::operator()(), I could do that with
std::declval<B&>()()
This was presente... | I believe you're looking for
decltype(std::declval<B>()(std::declval<A>())) c = b(a);
Broken down:
std::declval<B>() //pretend there's a B object
std::declval<A>() //pretend there's an A object
std::declval<B>()(std::declval<A>()) //call b(a) with these
decltype(std::declv... |
67,812,541 | 67,813,341 | How to link jsoncpp with cmake | I cannot find a way to link jsoncpp with my executable. I have tried many things but none succeeded:
linking jsoncpp_lib
also what is written here
I want to use the jsoncpp library that comes with ubuntu. Has anyone managed to do this?
$ ls /usr/lib/x86_64-linux-gnu/libjsoncpp.*
/usr/lib/x86_64-linux-gnu/libjsoncpp.... | The wiki mentions
get_target_property(JSON_INC_PATH jsoncpp_lib INTERFACE_INCLUDE_DIRECTORIES)
include_directories(${JSON_INC_PATH})
target_link_libraries(${PROJECT_NAME} jsoncpp_lib)
but I couldn't get that to work myself. If you have the jsoncpp .cmake files installed in a place searched automatically, this could b... |
67,813,300 | 67,813,637 | Allocate vs construct an array of ints using operator new and placement new | Hello to understand more placement new, operator new, expression delete.. and separating the initialization from construction, I've tried this example:
int main(){
int* p = static_cast<int*>(operator new[](10 * sizeof(int)));
p = new(p)int[10];
for(int i = 0; i != 10; ++i)
p[i] = i * 7;
for(i... | As you noted, there is no placement delete. When using placement new, you have to call destructors manually, eg:
void* mem = operator new[](10 * sizeof(T));
T* p = new(mem) T[10];
...
for(int i = 0; i < 10; ++i)
p[i].~T();
operator delete[](mem);
Where T is the desired element type.
Calling destructors is not very... |
67,813,924 | 67,813,987 | Is it possible to reduce templates parameters here? | I have a template class that has two template arguments. One of argument logically connected with another.
I want to reduce two arguments of the template into one.
This is what I have (simplified):
#include <iostream>
#include <vector>
template <typename T, typename dataT>
struct SomeManager {
std::vector<T> v;
... | This should be as simple as:
template <typename T>
struct SomeManager {
typedef typename T::data dataT;
... with the rest of the template unchanged.
|
67,814,209 | 67,814,246 | Pointing to destroyed objects | Why behavior like this is allowed?:
class A {
public:
void print() { cout << ++x; }
private:
int x = 10;
};
int main() {
A* ptr;
int* ptr2;
{
A a;
ptr = &a;
int b = 10;
ptr2 = &b;
}
ptr->print();
cout << ++*ptr2;
}
program output: 11 11
Here we are u... |
Why behavior like this is allowed?:
Why do you think that it is allowed? What do you mean by "allowed"?
The behaviour of the shown program is undefined.
Why program isn't throwing exceptions in this case?
Because a program isn't guaranteed to throw exceptions when the behaviour is undefined. Nothing is guaranteed a... |
67,814,478 | 67,814,653 | Is there a function for accessing the amount of elements that have a value in an std::array? | In C++, assume I have an std::array<std::optional<std::int>, 5> array. Let's say I set the first 3 elements to be of a certain value. Is there a function that when passed array returns 3 (i.e. Returns the number of elements that has an assigned value)? Or is there anyway to improve the std::array so that it supports th... |
I already knew about std::count, but I do not know how to check if an element is defined.
You can use std::count_if() for this, eg
std::array<std::optional<int>, 5> arr;
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
auto cnt = std::count_if(arr.begin(), arr.end(),
[](const auto &elem){ return elem.has_value(); ... |
67,814,656 | 67,814,893 | Equivalent of LinkedList in Java to C++ code | I am converting the source code from JAVA (working) to C++. Although I have very little experience in C++, I have managed to convert most of the code but I can't find the equivalent of import java.util.LinkedList; in C++. At the moment of compiling I get an error in these lines. Does anyone have any idea how I can conv... | arts is std::list<Articulacion*>, you are assigning std::list<Articulacion>(). The same for sensors and movimientos. You should not initialize these variables, this looks like initializing the default value with the default value.
RobotIndustrial()
{
arts = std::list<Articulacion>();
sensors = std::list<Sensor>();
... |
67,814,844 | 67,815,078 | Can I construct base class to allocate while initializing derived class? | I'm making this program assignment. So I can't change header file. That means I can't make get() or set() functions.
Below code is header of Base class I'm using
#include "IShape.h"
#include <vector>
class Polygon : public IShape {
private:
std::vector<Point> points;
public:
Polygon() = default;
Polygon(co... | Create a static helper function to make temp_vec, like this:
static std::vector<Point> get_temp_vec(Point p1, Point p2, Point p3, Point p4) {
std::vector<Point> temp_vec;
temp_vec.push_back(p2);
temp_vec.push_back(p1);
temp_vec.push_back(p3);
temp_vec.push_back(p4);
return temp_vec;
}
Then make... |
67,815,084 | 67,817,576 | How do I mock this on C++? | FuncRes Test::test(HttpRequest& request, std::string& result) {
try {
auto httpClientSync = HttpClientSync::create(param);
HttpResponse response = httpClientSync->execute(request);
if (...) {
return FuncRes::SUCCESS;
} else if (...) {
return FuncRes::RETRY;
... | Refactor this function into 2 parts, one that creates real HttpClientSync, and one that accepts HttpClientSync interface:
FuncRes Test::test(HttpClientSync& httpClientSync, HttpRequest& request, std::string& result);
FuncRes Test::test(HttpRequest& request, std::string& result) {
auto httpClientSync = HttpClientSync... |
67,815,234 | 67,815,297 | how can i call template function not using explicit type in C++? | When I wrote C++ code like below:
#include <iostream>
#include <memory>
#include <functional>
template <typename T>
struct Node
{
T data;
std::shared_ptr<T> left;
std::shared_ptr<T> right;
Node(const T& data)
:data(data)
{}
};
template <typename T>
void PreorderTraverse(std::shared_ptr<No... | Basically, the template is too complicated for the compiler to deduce. More specifically, the second argument is a closure (the anonymous type created by a lambda expression), not a std::function - it's compatible with a std::function that takes the first shared_ptr as an argument, but that's too complicated a deductio... |
67,815,618 | 67,815,744 | Function that works on vector of class objects in C++ | I have a struct called Edge with memebers pair<double,double> s and pair<double,double> e.
In the main function,I have an vector of edges vector<Edge> edges.
I populate that with Edge objects.
Now I want to find the index of a particular Edge x.
So I wrote a function :
int indexOf(vector<Edge>& arr,Edge& k);
Body of f... | Maybe inherit std::vector?
#include <iostream>
#include <vector>
using namespace std;
struct Edge
{
Edge(double _s, double _e) : s(_s), e(_e) {}
double s;
double e;
};
bool operator==(const Edge &lhs, const Edge &rhs) {
return lhs.s == rhs.s && lhs.e == rhs.e;
}
class MyVector : public vector<Edge>
... |
67,815,919 | 67,835,166 | Attempting to display image using pixel values in OpenCV. Only 1/3rd of Image shows | I'm attempting to read the pixels in an image and convert them into another format by iterating through the pixels.
After my conversion I only seem to be getting 1/3rd of the image and I'm certain it's because of the way I'm accessing the pixels using the .at() function.
I'm reading in the following image:
Mat image =... | You're loading your image with cv::imread, which with default value (cv::IMREAD_COLOR) will load it as a 3 channel image of type CV_8UC3 (aka cv::Mat3b).
If your original image is grayscale, when loading as a 3 channel image you have the same intensity value for each channel.
So when you scan the image you should acces... |
67,816,495 | 67,817,558 | How could I assign the value from lua_tostring() to a variable in type of wstring or const wchar_t* in utf-8 | The type of the return value of the function lua_tostring() is const char*. However, I have a C Function that needs a string as a parameter. And the string will be Chinese in UTF-8 coding format.
extern "C" LUALIB_API int PrintString(lua_State * L) {
const char* str = lua_tostring(L, 1) // Get the string parameter ... | You are not using MultiByteToWideChar() correctly.
Specifically, you are setting its cchWideChar parameter to -1 on the 1st call, when it needs to be 0 instead:
cchWideChar
Size, in characters, of the buffer indicated by lpWideCharStr. If this value is 0, the function returns the required buffer size, in characters, i... |
67,816,624 | 67,817,386 | munmap_chunk(): invalid pointer Error while making an Array data structure in C++ | I tried going through many similar questions regarding munmap_chunk(): invalid pointer errors, but I'm stuck as to what to do. I tried adding free commands too.
I'm a C++ novice and normally use Python and Java, so the whole concept of pointers and memory management are new to me. It would be great if someone can expla... | The size() function depends on the len member being set, which it was not.
You should also be aware that the expression "Illegal Capacity: " + cap does not append the value of cap to the end of the string. It does pointer arithmetic and if cap is less than zero you will be constructing the exception with a pointer to m... |
67,816,795 | 67,816,896 | invalid instantiation of template by compiler giving error | #include<iostream>
template<typename T, typename... Rest>
void printf_vt( const char *s, T value,Rest... rest)
{
while (*s) {
if (*s == '%' && *(++s) != '%') {
std::cout << value;
printf_vt(s, rest...); //called even when *s is 0,
return; //but does nothing in that case
}
std:... | The problem is, at the final recursive call, rest becomes empty for printf_vt(s, rest...);; and there's no candidate printf_vt to be called.
You can add an overloaded printf_vt taking only const char * to match the above scenario, it's also expected to terminate the recursive call. E.g.
void printf_vt(const char *s)
{
... |
67,817,100 | 67,817,687 | declare an array with pointer within the bounds of the available RAM | I want to create an array using pointers but I want to set its capacity to the maximum available RAM. I've tested this method:
void init()
{
long maxSize = 0x7fffffff;
long capacity = maxSize / sizeof(int);
int* _array = new int[capacity];
}
but this method fails and gives me this error at runtime:
Unhandled e... | You should understand that if you have 10 GB of free RAM, it does not mean that you can allocate an array of 10 GB. Imagine that the letter e denotes an empty gigabyte and the letter b denotes a busy one. And in real life, your RAM will look something like this
eebeebbeeebeebe We can notice that here 10 GB are free, bu... |
67,817,421 | 67,817,543 | GLFW and GLEW not showing triangle red | My code does not display a red triangle, instead there is a black screen. I was following the OpenGL tutorial by The Cherno. This happened at end of the 7th episode. I am using Visual Studio 2019 with Visual C++ on Windows 10 Home. My Graphics Card is a NVidia 820m.Link for tutorial I was following.
#include <gl/glew.h... | Your "triangle" is not a triangle, it is just a straight line.
float positions[6] = {
-0.5, -0.5,
0.0, -0.5,
0.5, -0.5
};
Change the vertex coordinates:
float positions[6] = {
-0.5, -0.5,
0.0, -0.5,
0.5, 0.5
};
Do not call glewInit() twice. Call it just once after making the OpenGL Context cu... |
67,818,010 | 67,819,705 | Add custom header view to table view | I want to create a custom header view and add it to a table view using model. This is my approach:
QStandardItemModel * s= new QStandardItemModel(this);
s->setHeaderData(0, Qt::Horizontal, "Header 1", Qt::DisplayRole);
s->setHeaderData(1, Qt::Horizontal, "Header 2", Qt::DisplayRole);
s->setHeaderData(2, Qt::Horizontal,... | The column count is missing in your example that's why it's not showing header. Use s->setColumnCount(3) in your code. For more information read this.
|
67,818,601 | 67,837,800 | Win32 API - How to make resizable textbox similar to text in MS-Paint | I tried to replicate the text button in MS-Paint for my own simple Paint win32 project using Visual Studio. The user click the button, select a rectangular area as textbox and then type text in:
I have done some research but haven't had any clue how to implement this to my project. I attempted to make a textbox at a s... | Thanks to everyone's comments i have found out the solution and they are:
Why my solution in my question failed: "textbox" is not a proper window class. In this case, i changed them to EDIT (more about EDIT control) and the window i need appears.
How to implement the text button in MS-Paint to my project: while user ... |
67,818,659 | 67,825,924 | c++ useless-cast from size_t to uint32_t for different targets | I have some code that builds for different targets. It also has some legacy functions that take uint32_t instead of size_t - which is annoying when I want to cast size_t types to it - with the levels of warnings that we have set (lots of gcc warnings).
So here is a contrived example:
val32 = static_cast<uint32_t>(strin... | It is a good solution, and it can still be improved somewhat.
The cast and the std::is_same_v are not really necessary. A simple assignment will do exactly the same thing (when working with unsigned integral types, but we want to check for that). The function could look like this:
template<typename TO, typename FROM>... |
67,819,394 | 67,823,194 | Migrating program code written in C++ to C# - What's the equivalent of `set<ii> ::iterator`? | I have a program written in C++ that process To place students to departments in order of preference and by their scores. Then I want to migrate this code to C# language. I converted all but the PlaceStudents() function is not complete. How can I find equivalent of set<ii> ::iterator in C#?
using namespace std;
typedef... | I do not think you should be that literal when converting code
set<ii> ::iterator it = b->S.end();
it--; // last element of set
int x = it->second; // index of worst scored student
b.S.Remove(it); // delete worst scored student
The goal of all this is apparently to extract and remove t... |
67,819,928 | 67,820,359 | In my quicksort implementation using C++ vectors, is partition function same as using the trivial method of swaps? | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
void quick_sort(vector<int> &a, int start, int end);
int partition(vector<int> &a, int start, int end);
int main(){
vector<int> v = {7, 6, 5, 4, 3, 2, 1};
int n(7);
quick_sort(v, 0, n);
for (auto& itr : v){
cout << itr << ' ';
... | You move every element after end doing the insert, and every element after i doing the erase. This version is much worse than swapping. With std::swap, you only touch two elements.
Aside: sorting in C++ is traditionally done with iterators, not indexes, i.e.
using iterator = std::vector<int>::iterator;
void quick_sor... |
67,820,235 | 67,824,036 | Persistent std::chrono time_point<steady_clock> | I am using in my projects some time_point<steady_clock> variables in order to do operations at a specific interval. I want to serialize/deserialize in a file those values.
But it seems that the time_since_epoch from a steady_clock is not reliable, although time_since_epoch from a system_clock is quite ok, it always cal... | On the cppreference page for std::chrono::steady_clock, it says:
This clock is not related to wall clock time (for example, it can be time since last reboot), and is most suitable for measuring intervals.
The page for std::chrono::system_clock says that most implementations use UTC as an epoch:
The epoch of system_c... |
67,820,557 | 67,820,836 | Logger system - using levels c++ | How can I use a function from (Wrap ostream in class and templatize << operator)
I want to use SEVERITY levels for the logger and each level can take any number of msg/ elements
This class accept any number for elements in the object but I need it also for each function in the class
ex:
ClassName ClassObject(&std::cout... | For a very simple solution, let info() write to *str and return a reference to *this:
logger& info()
{
*str << "info - ";
return *this;
}
Then is can be used as you wish:
l.info() << "print anything" << 5 << endl;
The above should print
info - print anything 5
|
67,820,626 | 67,821,093 | Line 1034: Char 9: runtime error: reference binding to null pointer of type 'int' (stl_vector.h) in leetcode IDE | I have tried a problem in leetcode IDE. Got a runtime error on running the below code.
As I am a beginner, I'm not able to debug the error.
class Solution
{
public:
vector<int> runningSum(vector<int>& nums) {
vector<int> result;
int n=nums.size();
for(int... | The problem in your solution is that result[i] is not a defined address because result vector is empty, it does not have any size defined.
You can either use result.push_back(sum); or while declaring vector<int> result(n); but not both.
Complete code
class Solution
{
public:
vector<int> runningSum(ve... |
67,820,843 | 67,821,019 | How to return object after vector.push_back(std::move(Object))? | I have an Entity which has this piece of code:
std::vector<Component*> Components;
template<typename T, typename... TArgs>
T& AddComponent(TArgs&&... args)
{
T* component = new T(std::forward<TArgs>(args)...);
Components.push_back(std::move(component));
return Components.back();
}
The questions ... |
Is the component guaranteed to be moved and added?
No, because you're "moving" the pointer. And allocations don't get "moved" like that. In fact, there's no reason for you to std::move() if you're using a pointer anyway.
Also, Like @rustyx suggested, you probably want to use std::unique_ptr<Component> rather than Com... |
67,820,959 | 67,821,268 | how do I replace a static array with a dynamic one? | I implemented a static array, how can I convert it to a dynamic array?
I have completed this task:
Write a program for approximating the function f(x) on the interval [a, b] by a given method, m is the number of points at which the function is known (the size of the table). The function type is set to get the values of... | Here you have a good starting point. Not sure I understand your code, but this compiles:
Side notes:
if you use C++, then it is not <math.h> but <cmath>
single letter identifiers (variables and functions) is not recommended (except maybe for iterating ints), you should use significant names.
#include <iostream>
#incl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.