question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
71,709,896 | 71,710,020 | Taking Input to Arrays Issue | I'm creating a console timetable application in which you can create a timetable, change it, and delete it. I'm on the stage of taking the input for the calculator. However, when I run the code, as soon as I finish taking the input, the window just closes. Here is the code:
int input()
{
int numberOfElements;
cout << "How many items do you want in your timetable? ";
cin >> numberOfElements;
char* itemArray[numberOfElements] = {};
for (int i = 1; i <= numberOfElements; i++)
{
cout << "Please enter a session: ";
cin >> itemArray[i];
}
for (int i = 0; i < numberOfElements; i++)
{
cout << itemArray[i] << "\n";
}
return 0;
}
There is some code in the main function as well, but it's irrelevant (only to find out for what day it is). I want you to have a look at the first for loop in the code, where I take in input. When running this code (in a separate window altogether), it closes as soon as I give in the input. Even if I say that I want 3 sessions (or any number), it closes right after I input the first session. In case you were wondering, I already tried replacing
char* itemArray[numberOfElements] = {};
with
char* itemArray[numberOfElements];
Just in case it's useful to anyone, I'm using the MinGW compiler.
Thanks.
| In Standard C++ the size of an array must be a compile time constant. So take for example the following statements in your program:
int numberOfElements;
cout << "How many items do you want in your timetable? ";
cin >> numberOfElements;
char* itemArray[numberOfElements] = {};//not standard C++
The statement char* itemArray[numberOfElements] = {}; is not standard C++ because numberOfElements is not a constant expression.
Additionally, you're going out of bounds of the array because of the <= in the for loop instead of <. This leads to undefined behavior.
Better would be to use std::vector<std::string> as shown below:
#include <iostream>
#include<vector>
#include <string>
int main()
{
int numberOfElements;
std::cout << "How many items do you want in your timetable? ";
std::cin >> numberOfElements;
std::vector<std::string> arr(numberOfElements); //create vector of size numberOfElements
for (std::string &element: arr)
{
std::cout << "Please enter the element: ";
std::cin >> element;
}
for (const std::string& element: arr)
{
std::cout << element << "\n";
}
}
Demo.
|
71,709,962 | 71,711,109 | bucket_count of libc++'s unordered_set.reserve | When I call reserve(n) on a libc++'s empty unordered_set, libc++ find the next prime number as bucket_count if n is not a power of two, otherwise they just use n. This also makes reserve(15) have a bigger bucket_count than reserve(16).
libc++ source:
if (__n == 1)
__n = 2;
else if (__n & (__n - 1))
__n = __next_prime(__n);
I am wondering is there any useful case of this?
I known that some hash-table implementation can use a power of two as size to avoid modulo calculations. But that seems make sense only if it is known at compile-time that only power-of-two numbers can be used.
Testing Demo: https://godbolt.org/z/W5joovP4q
#include <cstdio>
#include <unordered_set>
bool is_prime(int x) {
if (x < 2) return false;
if (x % 2 == 0) return x == 2;
for (int i = 3; i * i <= x; i += 2)
if (x % i == 0) return false;
return true;
}
int next_prime(int x) {
while (!is_prime(x))++x;
return x;
}
__attribute__((noinline))
void test(int i) {
std::unordered_set<char> s;
s.reserve(i);
int a = s.bucket_count();
int b = next_prime(i);
if (a != b) {
printf("%6d %6d %6d\n", i, a, b);
}
}
int main() {
for (int i = 0; i < 3000; ++i)
test(i);
}
Program stdout:
0 0 2
4 4 5
8 8 11
16 16 17
32 32 37
64 64 67
128 128 131
256 256 257
512 512 521
1024 1024 1031
2048 2048 2053
| The original commit message sheds some light on this. In short, libc++ originally used just prime numbers. This commit introduces an optimization for power-of-2 numbers in case the user explicitly requests them.
Also note that the new function __constrain_hash() in that commit checks if it is a power-of-2 and then does not use the modulo operation. According to the commit message, the cost for the additional check if the input is a power-of-2 number is outweighed by not using a modulo operation. So even if you do not know the information at compile time, you can get a performance boost.
Quote of the commit message:
This commit establishes a new bucket_count policy in the unordered containers: The policy now allows a power-of-2 number of buckets to be requested (and that request honored) by the client. And if the number of buckets is set to a power of 2, then the constraint of the hash to the number of buckets uses & instead of %. If the client does not specify a number of buckets, then the policy remains unchanged: a prime number of buckets is selected. The growth policy is that the number of buckets is roughly doubled when needed. While growing, either the prime, or the power-of-2 strategy will be preserved. There is a small run time cost for putting in this switch. For very cheap hash functions, e.g. identity for int, the cost can be as high as 18%. However with more typical use cases, e.g. strings, the cost is in the noise level. I've measured cases with very cheap hash functions (int) that using a power-of-2 number of buckets can make look up about twice as fast. However I've also noted that a power-of-2 number of buckets is more susceptible to accidental catastrophic collisions. Though I've also noted that accidental catastrophic collisions are also possible when using a prime number of buckets (but seems far less likely). In short, this patch adds an extra tuning knob for those clients trying to get the last bit of performance squeezed out of their hash containers. Casual users of the hash containers will not notice the introduction of this tuning knob. Those clients who swear by power-of-2 hash containers can now opt-in to that strategy. Clients who prefer a prime number of buckets can continue as they have.
|
71,710,026 | 71,710,712 | qt: slot not called guarantee after disconnect of an auto direct connection | I have a single-thread gui application and I do not choose a type of connection, so according to documentation the connection will be a direct one. According to documentation then: "The slot is invoked immediately when the signal is emitted. The slot is executed in the signalling thread."
For my understanding, this obviously leads to the conclusion that if I disconnect such an auto-connection in a method, then there is a guarantee that there is no possibility that after completion of this method (in which I do the disconnection) I can get a slot (corresponding to the just-disconnected connection) still being called. The reason of that is, as far as I understand, the fact that no event queue is used for such an auto (here direct) connection.
Am I right? Or should I be careful and better keep a state-variable and double check this state and return from the slot if it's in a some (unclear to me) way still got called? I am especially worried for the situations where I have connections, in which signals are produced by Qt entities (e.g. signals QNetworkReply::finished(), etc.), rather than by me, as I do not control them fully.
I have found related questions, like this one, but I have not found the exact question, and so I have inconfidence and decided to ask.
| If you use only direct connections then you can't "receive" any further signals after you disconnected from getting them. Direct connection is just a callback call, nothing more.
|
71,710,274 | 71,728,275 | Why C++ throws an out of range error here? | I really cannot find the reason why here a "cannot seek vector iterator after end" error occurs. I cannot show the whole code but I think that this part should be enough:
qDebug() << Pun.size() << ", " << 2*pos - counter;
Pun.erase(Pun.begin() + 2*pos - counter); //the error seems to happen here
qDebug() << "B";
Pun.erase(Pun.begin() + 2*pos - counter);
counter += 2;
When I run my code, the last what is printed is "4, 1" and the "B" is not printed so it has to be in the line above but it can't if Pun.size() is 4 and 2*pos - counter is 1.
Maybe this helps: This is part of a big algorithm for a special problem and I run into this problem when I tested the program on a lot of instances. I traced down the error to a special instance and the weird thing is that when I run the algorithm the first time this error doesn't occur but when it's done the second time it somehow does....
Any hint would be really helpful...
| Operator precedence problems -- + and - are the same precedence (and are left-recursive), so your erase call is really
Pun.erase((Pun.begin() + 2*pos) - counter);
which probably tries to advance well past the end of Pun, causing it to throw an exception. I'm assuming here Pun is some custom sequence type that does bounds checking (ie, not std::vector). You want
Pun.erase(Pun.begin() + (2*pos - counter));
|
71,710,337 | 71,710,475 | How to make clang-format not align parameters to function call? | I want to make clang-format not align call parameters to the '(' symbol. I had tried setting PenaltyBreakBeforeFirstCallParameter to 0, but it didn't help.
How I want it to be:
veeeeeeeryLongFunctionName(
longParameter1, longParameter2,
longParameter3, longParameter4
)
// or
veeeeeeeryLongFunctionName(
loooooooooongParameter1,
loooooooooongParameter2,
loooooooooongParameter3,
loooooooooongParameter4
)
How clang-format does it:
veeeeeeeryLongFunctionName(loooooooooongParameter1,
loooooooooongParameter2,
loooooooooongParameter3,
loooooooooongParameter4
)
| You can use
AlignAfterOpenBracket : BlockIndent
Always break after an open bracket, if the parameters don’t fit on a single line. Closing brackets will be placed on a new line. E.g.:
someLongFunction(
argument1, argument2
)
Reference
|
71,710,357 | 71,710,486 | Why "operator<" for std::vector<int>::iterator seems to compare absolute values when out of range (before .begin())? | cppreference on std::vector doesn't seem to have any links for std::vector<T>::iterator type. Since it is a bidirectional iterator on a contigious memory, I supposed that it can be "negative".
std::distance(vec.begin(), std::prev(vec.begin()) yields -1, and I ended up using std::distance to compare iterators for a loop.
But I was expecting while(iterLeft < iterRight) to be a valid check, and it is shorter than while(std::distance(iterLeft, iterRight) > 0).
This code, however, demonstrates that operator< for some reason seems to compare absolute values:
(This code surved to recreate the problem. The actual code had a variable-sized vector as an input)
#include <vector>
#include <iostream>
int main()
{
std::vector<int> vec{};
auto iterLeft = vec.begin(),
iterRight = std::prev(vec.end());
std::cout << "Left = " << std::distance(vec.begin(), iterLeft)
<< ", Right = " << std::distance(vec.begin(), iterRight)
<< ", Left < Right: " << std::boolalpha << bool(iterLeft < iterRight)
<< std::endl;
return 0;
}
Program returned: 0
Left = 0, Right = -1, Left < Right: true
https://godbolt.org/z/PErY35Ynj
So basically the UB is caused Not by std::prev(vec.end()), but by an iterator goind out of range (before .begin()).
The code example is just to recreate the problem.
Initially the code is to traverse an array with 2 iterators and the intent was to make the code declarative (meaning to handle empty arrays without an explicit check).
for (auto leftIter = vec.begin(), rightIter = std::prev(vec.end()); leftIter < rightIter;)
{
// do stuff
++leftIter;
--rightIter;
}
The code worked fine for most cases, but empty arrays. Hence the question.
| std::distance can yield negative values if applied to valid iterators to the same range and operator< can be used to compare the ordering of valid iterators into the same range. And it does this comparison in the expected way. iterLeft < iterRight will be equivalent to std::distance(iterLeft, iterRight) > 0.
However the only valid iterators are those in the range from begin() to end(). Trying to obtain an iterator "before" begin() or "after" end() causes undefined behavior.
So std::distance(vec.begin(), std::prev(vec.begin()) does not result in -1. It has undefined behavior.
Similarly in your code block std::prev(vec.end()) has undefined behavior because the vector is empty and so vec.begin() == vec.end().
|
71,710,476 | 71,710,752 | How to get the sum of numbers in a vector with two string variables? | How would I get the total of the numbers in the vector of MAXARR?
The code below only sort the vector but I want to know how to the sum of the left part of each array by getting the sum. But I have no clue where to even begin.
This is the code to used to sort vector:
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
class NameAndNumber
{
public:
std::string number;
std::string name;
NameAndNumber();
NameAndNumber(std::string nam, std::string num);
void show();
};
#define MAXARR 10
NameAndNumber arr[MAXARR] = { {"2100","Fred"},
{"2300","Jane"}, {"2112","Tony"},{"230","Owen"}, {"21010","Jamison"},
{"2310","Akmed"}, {"1112","OneOneOneTwo"},
{"1301","Sung"}, {"1013","Luke Skywalker"},{"20010","Kevin Jamison"}
}; // THANk YOU FOR STAnDard ALLOCATORS
NameAndNumber::NameAndNumber(string num, string nam)
{
name = nam;
number = num;
}
NameAndNumber::NameAndNumber() // default constructor
{
name = "";
number = "";
}
void NameAndNumber::show()
{
cout << setw(7) << number << " " << setw(20) << name << " ";
}
int main1()
{
std::cout << "------------------------------------ \n";
NameAndNumber temp;
int sum = 0;
for (int i = 0; i < MAXARR; i++)
{
for (int k = 1; k < MAXARR; k++)
{
if (stoi(arr[k].number) < stoi(arr[k - 1].number))
{
temp = arr[k];
arr[k] = arr[k - 1];
arr[k - 1] = temp;
}
}
}
for (int i = 0; i < MAXARR; i++)
{
arr[i].show();
cout << " - [" << i << "]\n";
}
std::cout << "------------------------------------ \n";
return 0;
}
int main()
{
main1();
return 0;
}
The vector has both variables in the array as strings, so I will also need help on how to change them into integers.
|
How would I get the total of the numbers in the vector of MAXARR?
Use std::accumulate to add up the values.
Use std::stoi to convert the string version of the number to an integer.
#include <numeric>
//...
int32_t total = std::accumulate(arr, arr + MAXARR, 0L,
[&](int32_t total, NameAndNumber& n)
{ return total + std::stoi(n.number); });
Full Example.
|
71,710,626 | 71,915,383 | Thread 1 "my_app" received signal SIGSEGV, Segmentation fault when accessing API from another library | From my C++ application my_app compiled using G++, I am invoking several API's from another shared library tool.so (tool.so also developed using C++). Each reference of API call from tool.so I am getting the below segmentation fault from the GDB.
Thread 1 "my_app" received signal SIGSEGV, Segmentation fault.
0x00007ffff61406cd in boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code\*) () from /usr/lib/x86_64-linux-gnu/libboost_filesystem.so.1.65.1
problem seem to be boost version mismatch. myapp needs boost 1.65 but tool.so compiled using boost 1.55. I am statically linking both and get segmentation error. I modified the CmakeList.txt, so that it dynamically links my_app, tool. but still I get the same segmentation error. any suggestion?
CmakeLists.txt
add_library(tool SHARED IMPORTED)
set_target_properties(tool PROPERTIES IMPORTED_LOCATION ${TOOL_LIB_DIR}/tool.so)
target_link_libraries(my_app PRIVATE tool)
Thread 1 "my_app" received signal SIGSEGV, Segmentation fault.
0x00007ffff61406cd in boost::filesystem::detail::status(boost::filesystem::path const&, boost::system::error_code\*) () from /usr/lib/x86_64-linux-gnu/libboost_filesystem.so.1.65.1
int main(int argc, const char* argv[])
{
..
if(TOOL_Initialize() == TOOL_FAIL) ----> Call 1
{
std::cout <<" failed to initialize.\n";
}
..
..
..
if(TOOL_DEVICE_GetCount(DEVICE_TYPE)!= TOOL_SUCCESS)--> call 2
{
cout << "Get CPU count API failed exiting" << endl ;
}
}
Getting segmentation fault in call 1, if comment out call 1 then getting in call 2 wherever I am invoking lib call
| it worked by adding this option,
target_link_options(my_app PUBLIC "LINKER:/home/fkamalmu/toollib_1_7_8/lib/linux/tool.so") instead of below way of
linking
add_library(tool SHARED IMPORTED)
set_target_properties(tool PROPERTIES IMPORTED_LOCATION ${TOOL_LIB_DIR}/tool.so)
target_link_libraries(my_app PRIVATE tool)
|
71,710,930 | 71,712,158 | C++: Parse decimal from stream into uint8_t | Is there a way to do the following directly using stream operators?
uint8_t actual;
uint32_t temporary;
std::cin >> std::dec >> temporary;
if (temporary > UINT8_MAX) {
// error
}
actual = static_cast<uint8_t>(temporary);
In particular, I would like to parse a sufficiently small decimal number into a uint8_t without resorting to a larger temporary variable.
| No, I don't think there is a way to read a number directly into unsigned char with a std::istream (std::num_get::get doesn't support unsigned char)
You could encapsulate it into a function:
inline std::uint8_t read_uint8(std::istream& is) {
unsigned short temporary;
is >> temporary;
if (!is) return -1;
if (temporary > UINT8_MAX) {
is.setstate(std::ios_base::failbit);
return -1;
}
return std::uint8_t(temporary);
}
int main() {
std::uint8_t actual = read_uint8(std::cin);
if (!std::cin) {
// error
}
}
Or you can do something like what std::put_money or std::osyncstream does and wrap one of the arguments to call a custom operator>>:
struct read_uint8 {
std::uint8_t& v;
read_uint8(std::uint8_t& v) : v(v) {}
};
inline std::istream& operator>>(std::istream& is, read_uint8 v) {
unsigned short temporary;
is >> temporary;
if (is) {
if (temporary > UINT8_MAX) {
is.setstate(std::ios_base::failbit);
} else {
v.v = std::uint8_t(temporary);
}
}
return is;
}
int main() {
std::uint8_t actual;
if (!(std::cin >> read_uint8(actual))) {
// error
}
}
|
71,711,051 | 71,711,236 | C++ operators overload, rules for spaces in expression | I want to learn the rules (if any) about usage of spaces for writing correct operator overloads.
I've seen different forms:
T operator+(T t1, T t2) /* etc. */
T operator+ (T t1, T t2) /* etc. */
T operator +(T t1, T t2) /* etc. */
T operator + (T t1, T t2) /* etc. */
I'm talking about the space(s) between the operator keyword, operator characters and first parenthesis.
Which one(s) is(are) correct? What is(are) the preferred one(s) over the others? Are some of them wrong, or, are some of them right in certain cases and wrong in others (and vice-versa)?
In short: do the spaces have any special meaning here (in this particular subject (I don't ask about use of spaces generally in code)?
If so, when and why? If not, what are considered as best practices?
| Other than in character and string literals, the only place in C++ code where whitespace is significant is to separate tokens that would be (or could be) otherwise merged.
In your case, there is a clear separation between the three tokens, operator, + and (, so the added space characters make no difference whatsoever to how the compiler will interpret the declaration.
However, something like Toperator+(T t1, T t2) is invalid, because the T and the operator will now be treated as a single (identifier) token.
As for which one is "best" – that's really a matter of taste and opinion, although cppreference generally uses the "no space" option for overload declarations.
|
71,711,185 | 71,719,783 | How to pass a variable to python script from c++ | There are similar questions & answers to this kind of problem but I still can't find a satisfying answer to my specific problem:
I need to pass a variable (should be a global variable to this python script) to a python script from c++ code. I run this python script using following line in c++:
PyRun_SimpleString ( "exec(f.read())" );
and I want to pass this variable var="From c++" to the python environment so code in f script is able to access var variable.
I'm looking at PyDict_SetItem and PyDict_SetItemString, etc... but couldn't get it right. How can I do that?
| Based on @mbostic 's comment, I did the following and it works:
add this line PyRun_SimpleString("var='From c++' ");
before this PyRun_SimpleString("exec(f.read())");.
This way f is able to access variable var.
|
71,711,736 | 71,713,155 | cURL write_callback does not pass userdata argument | I am trying to collect some data from a URL. If I do not define any CURLOPT_WRITEFUNCTION and CURLOPT_WRITEDATA I can obviously see the output on console. Then I tried to write that data to memory by copiying the example code, however userdata argument of my callback function returned NULL and I got following exception on line:
char* ptr = (char*)realloc(mem->memory, mem->size + realsize + 1);
Exception thrown: read access violation.
mem was nullptr.
Am I doing something wrong?
Here is my code:
struct MemoryStruct {
char* memory;
size_t size;
};
//-----------------
// Curl's callback
//-----------------
size_t CurlWrapper::curl_cb(char* data, size_t size, size_t nmemb, void* response)
{
size_t realsize = size * nmemb;
std::cout << "CALLBACK CALLED" << std::endl;
MemoryStruct* mem = (struct MemoryStruct*)response;
char* ptr = (char*)realloc(mem->memory, mem->size + realsize + 1);
if (!ptr) {
/* out of memory! */
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), data, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
//--------------------
// Do the curl
//--------------------
void CurlWrapper::curl_api(
const std::string& url,
std::string& str_result)
{
MemoryStruct chunk;
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &CurlWrapper::curl_cb);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk);
// TODO: enable ssh certificate
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); // true
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); // 2
curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "zlib");
auto res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK) {
// nothing
std::cout << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
}
}
}
libcurl version: 7.82.0
| Since libcurl is a C library, it does not know anything about C++ member functions or objects. You can overcome this "limitation" with relative ease using for example a static member function that is passed a pointer to the class.
See this example (from the everything curl book).
// f is the pointer to your object.
static size_t YourClass::func(void *buffer, size_t sz, size_t n, void *f)
{
// Call non-static member function.
static_cast<YourClass*>(f)->nonStaticFunction();
}
// This is how you pass pointer to the static function:
curl_easy_setopt(hcurl, CURLOPT_WRITEFUNCTION, YourClass::func);
curl_easy_setopt(hcurl, CURLOPT_WRITEDATA, this);
|
71,711,830 | 71,711,909 | CRTP base private constructor and derived friend class cause compilation error using C++17 and uniform initialization | I've got the following code:
struct B
{
B(int) {}
};
template <typename T>
class Base : public B
{
friend T;
Base() : B(1) {}
};
class Derived : public Base<Derived>
{
public:
void do_sth() const {}
};
int main()
{
auto x = Derived{}; //Compiles only when using C++11
auto x1 = Derived(); //Compiles using C++17/20 flag
x.do_sth();
x1.do_sth();
}
For some reason when using C++17 compilation fails due to 'non-compilable' initialization of 'x' variable. Compilator says that:
Base::Base() [with T = Derived]' is private within this context
but as you can see, below I'm creating an object of the same type but this time I'm not using uniform initialization.
x1 variable can be compiled using both C++11 or C++17 standards, but the 'x' variable is compilable only in C++11 mode. Why is that? What has changed in the standard that causes this problem?
Compiler explorer
| Apparently Derived is an aggregate since C++17, so Derived{} is an aggregate initialization. (Base classes weren't allowed in aggregates pre-C++17, now public non-virtual bases are allowed.)
Meaning Base::Base() is invoked directly by the caller (main()), rather than Derived.
The solution is to add Derived() {} to Derived to stop it from being an aggregate.
|
71,712,198 | 71,712,809 | Is it possible to create a `map_error` function that takes a lambda? | I am trying to create a map_error method attached to a std::expected type, or something similar. I can't seem to figure out the template meta programming. Is this possible to do something similar to this:
expect<int, fmt_err, io_err> square(int num) {
if (num % 1)
return fmt_err{};
else if (num < 5)
return io_err{};
else
return num * num;
}
square(i)
.map_error([](fmt_err err) {
return 10;
})
.map_error([](const io_error& err) {
return 10;
});
This is what I have so far, I can't seem to get it compiling though. For every .map_error it should remove one type, and then return a sub type of errs with the single error removed.
#include <type_traits>
#include <memory>
template<class...>struct types{using type=types;};
template<class Sig> struct args;
template<class R, class...Args>
struct args<R(Args...)>:types<Args...>{};
template<class Sig> using args_t=typename args<Sig>::type;
struct err
{
virtual ~err() {}
};
struct fmt_err : public err
{
};
struct io_err : public err
{
};
template<typename...> struct errs;
template<typename R, typename T, typename... Ts>
struct errs<R, T, Ts...> : public errs<R, Ts...>
{
using self = errs<T, Ts...>;
using args = errs<R, Ts...>;
using args::args;
errs(R&& result) : errs(std::move(result))
{
}
errs(T t)
{
}
};
template<typename R, typename T>
struct errs<R, T>
{
errs() = default;
errs(const R& result) : result(result)
{
}
errs(R&& result) : result(std::move(result))
{
}
errs(std::unique_ptr<err> error, int index)
: error(std::move(error))
, index(index)
{
}
R result;
int index = -1;
std::unique_ptr<err> error;
};
template<typename...> struct expect;
template <typename T, typename E, typename... Es>
struct expect<T, E, Es...> : public expect<T, errs<T, E, Es...>>
{
using base = expect<T, errs<T, E, Es...>>;
using base::base;
expect(T&&) {
}
expect(E&&) {
}
// template<int N, typename... Ts> using NthTypeOf = typename std::tuple_element<N, std::tuple<Ts...>>::type;
// template<typename En = std::enable_if_t<true, NthTypeOf<0, Es...>>>
// expect(En&&) : expect(std::make_unique<En>(), sizeof...(Es)) {
// }
};
template <typename T, typename E, typename... Es>
struct expect<T, errs<T, E, Es...>>
{
errs<T, E, Es...> errors;
expect() {
}
expect(T&&)
{
}
expect(std::unique_ptr<err>&& error, int index)
{
errors.error = std::move(error);
}
template<typename F>
expect<T, Es...> map_error(F&& func) {
if (errors.index == 0) {
return errors.result;
} else if (errors.index == sizeof...(Es)) {
return func(*static_cast<E*>(errors.error.get()));
} else if (errors.index < sizeof...(Es)) {
return errors;
}
}
};
expect<int, fmt_err, io_err> square(int num) {
if (num % 1)
return fmt_err{};
else if (num < 5)
return io_err{};
else
return num * num;
}
int main()
{
for(int i = 0; i < 10; ++i)
{
square(i)
.map_error([](fmt_err err){
return 10;
});
}
}
| You are missing three constructors, here is a working version of your code: https://godbolt.org/z/cxY8Yzzq1
#include <memory>
#include <type_traits>
template <class...>
struct types {
using type = types;
};
template <class Sig>
struct args;
template <class R, class... Args>
struct args<R(Args...)> : types<Args...> {};
template <class Sig>
using args_t = typename args<Sig>::type;
struct err {
virtual ~err() {}
};
struct fmt_err : public err {};
struct io_err : public err {};
template <typename...>
struct errs;
template <typename R, typename T, typename... Ts>
struct errs<R, T, Ts...> : public errs<R, Ts...> {
using self = errs<T, Ts...>;
using args = errs<R, Ts...>;
using args::args;
errs(R&& result) : errs(std::move(result)) {}
errs(T t) {}
};
template <typename R, typename T>
struct errs<R, T> {
errs() = default;
// ---------------------------------
// needed in order to be able to make copies of errs, copying was disabled by storing a unique_ptr inside the class
errs(const errs& rref) :
result(rref.result),
index(rref.index),
error(new err(*rref.error))
{
}
// ---------------------------------
errs(const R& result) : result(result) {}
errs(R&& result) : result(std::move(result)) {}
errs(std::unique_ptr<err> error, int index)
: error(std::move(error)), index(index) {}
R result;
int index = -1;
std::unique_ptr<err> error;
};
template <typename...>
struct expect;
template <typename T, typename E, typename... Es>
struct expect<T, E, Es...> : public expect<T, errs<T, E, Es...>> {
using base = expect<T, errs<T, E, Es...>>;
using base::base;
expect(T&&) {}
expect(E&&) {}
// ---------------------------------
// needed in order to convert from io_err' to 'expect<int, fmt_err, io_err>' in line 123
expect(Es&&...) {}
// ---------------------------------
// template<int N, typename... Ts> using NthTypeOf = typename
// std::tuple_element<N, std::tuple<Ts...>>::type;
// template<typename En = std::enable_if_t<true, NthTypeOf<0, Es...>>>
// expect(En&&) : expect(std::make_unique<En>(), sizeof...(Es)) {
// }
};
template <typename T, typename E, typename... Es>
struct expect<T, errs<T, E, Es...>> {
errs<T, E, Es...> errors;
expect() {}
expect(T&&) {}
// ---------------------------------
// needed because you pass an int, not an rvalue in line 110 (return expect<T, Es...>(errors.result);)`
expect(const errs<T, E, Es...>& errors) : errors(errors) {}
// ---------------------------------
expect(std::unique_ptr<err>&& error, int index) {
errors.error = std::move(error);
}
template <typename F>
expect<T, Es...> map_error(F&& func) {
if (errors.index == 0) {
return expect<T, Es...>(errors.result);
} else if (errors.index == sizeof...(Es)) {
return func(*static_cast<E*>(errors.error.get()));
} else if (errors.index < sizeof...(Es)) {
return errors;
}
}
};
expect<int, fmt_err, io_err> square(int num) {
if (num % 1)
return fmt_err{};
else if (num < 5)
return io_err{};
else
return num * num;
}
int main() {
for (int i = 0; i < 10; ++i) {
square(i).map_error([](fmt_err err) { return 10; });
}
}
Missing constructors:
errs<R, T>::errs(const errs& rref); // needed in order to be able to make copies of errs, copying was disabled by storing a unique_ptr inside the class
expect<T, E, Es...>::expect(Es&&...) // needed in order to convert from io_err' to 'expect<int, fmt_err, io_err>' in line 123
expect<T, errs<T, E, Es...>>::expect(const errs<T, E, Es...>& errors) // needed because you pass an int, not an rvalue in line 110
|
71,712,249 | 71,712,758 | why only the index 0 changes him value to "" | I'll be directly
Context: I'm making a hangman game
Script "bug" area:
while(lifes > 0){
cout << "word: ";
for(int i=0; i<size; i++){
cout << secret[i];
}
cout << endl;
cout << "lifes: " << lifes << endl;
cout << endl << "choose a letter..." << endl;
cin >> letter;
check=false;
for(int i=0; i<size; i++){
if(key[i] == letter[0]){
secret[i] = letter[0];
check=true;
}
}
if(check == false){
lifes--;
}
}
THE PROBLEM:
I'll simulate what happens:
lets take the secret-word as "bear", ok?
first loop =
word: ----
lifes: 5
cin >> 'b'
second loop =
word: b---
lifes: 5
cin >> 'a'
third loop =
word: -a-
lifes: 5
cin >> 'b'
fourth loop =
word: b-a-
lifes: 5
see???? When I input a new letter, the first letter turn a blank space, but if I input the letter again, it appears!!
I really dont know how to solve this.
Tank you for all help and sorry for the bad english haha.
if you want the full code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main(){
//definição de variáveis
char chave[50], palavra[50], letra[1];
int tam=0, pos=0, vidas=5;
bool acerto=false;
//estabelecendo palavra-chave
cout << "Qual a palavra?" << endl;
cin >> chave;
system("cls");
//descobrindo o tamanho da palavra-chave
while(chave[pos] != '\0'){
tam++;
pos++;
}
//escondendo a palavra secreta
for(int i=0; i<tam; i++){
palavra[i] = '-';
}
/*
.
. etapa 1
.
*/
while(vidas > 0){
//criar painel
cout << "Palavra: ";
for(int i=0; i<tam; i++){
cout << palavra[i];
}
cout << endl;
cout << "Vidas: " << vidas << endl;
cout << endl << "Escolha uma letra..." << endl;
cin >> letra;
//verificar se tem algum caracter identico à letra
acerto=false;
for(int i=0; i<tam; i++){
if(chave[i] == letra[0]){
palavra[i] = letra[0];
acerto=true;
}
}
if(acerto == false){
vidas--;
}
//fim do loop
system("pause");
system("cls");
}
return 0;
}
| ok, given you are trying to learn, and you are not limited by rule of any sort typical of homeworks, you can follow these first steps to do things correctly.
first:
replace those char[] with std::strings.
In c++ you have classes already built to do various stuff, managing strings is one of those, and std::string are the way to go.
second:
letter is literally a single letter, so is does not need to be a char[1] and it can be just a char.
third: try to write variables in english, it's easier for anyone when you are going to share code.
starting from these simple steps you'll write better code that will incidentally help you to avoid errors.
P.s. I'm not going to put a working and improved version of your code 'cause I think you will learn more doing it by yourself instead of just copying some code from here.
|
71,712,855 | 71,712,888 | Can anyone explain why does this recursive function crash? | Why does this recursive (i'm not sure about it, the site i found this code said it was "recursive") code crash (i found this weird approach on Internet, but i'm honestly not understanding how it works) entering values >4000 (sometimes >4023, sometimes >4015, i really don't understand...)...
#include <iostream>
unsigned long long int sum(unsigned long long int k)
{
if (k > 0) {
return k + sum(k - 1);
}
else {
return 0;
}
}
int main()
{
unsigned long long int n;
std::cout << "This program prints the sum of the first N natural numbers.\n\
Enter N: _";
std::cin >> n;
std::cout << "The sum is: " << sum(n) << ".\n\
Press any key to exit...";
system("pause>nul");
return 0;
}
while this, instead, does not?
#include <iostream>
int main()
{
unsigned int n;
std::cout << "Questo programma stampa la somma dei primi N numeri naturali.\n\
Prego inserire N: _";
std::cin >> n;
unsigned long long int tmp = 0;
for (n; n != 0; --n) {
tmp += n;
//std::cout << tmp << ' ';
}
std::cout << "La somma \212: " << tmp << ".\n\
Premere un tasto per uscire...";
system("pause>nul");
return 0;
}
| The recursive version uses a little bit of stack space every time it calls itself, so it is limited by the size of the stack and will crash if it calls itself too many times. It's a classic stack overflow error.
The iterative second version doesn't have that problem.
|
71,713,077 | 71,713,396 | Strip modifiers from decltype(*this) for use in trailing return type | Let's say I have Base and Derived classes:
class Base {
public:
virtual auto DoSomething(const Base&) const -> decltype(*this) = 0;
};
class Derived : public Base {
public:
const Derived& DoSomething(const Base&) const override; // OK, but not what I want
// Derived DoSomething(const Base&) const override; // ERROR, but I want this
};
The uncommented code compiles fine, and works fine if you fill it out. But I don't want to return a const reference from DoSomething(). Is there any way to strip the modifiers from the trailing return type in the base class declaration? I've tried a few methods from <type_traits> (remove_cvref_t, etc), but they seem to evaluate the type to Base, which creates a conflicting return type.
If what I'm trying to do is not possible, why is it not possible?
| As you noticed, you can make make Base::DoSomething return type Base with std::remove_cvref_t:
class Base {
public:
virtual auto DoSomething(const Base&) const -> std::_remove_cvref_t<decltype(*this)> = 0;
};
However, a function that overrides another function must return either the same type as overridden function or a covariant type. Quoting from cppreference:
Two types are covariant if they satisfy all of the following
requirements:
both types are pointers or references (lvalue or rvalue) to classes. Multi-level pointers or references are not allowed.
the referenced/pointed-to class in the return type of Base::f() must be an unambiguous and accessible direct or indirect base class of
the referenced/pointed-to class of the return type of Derived::f().
the return type of Derived::f() must be equally or less cv-qualified than the return type of Base::f().
So yes, if Base::DoSomething will return Base, any overrides must also return Base. If Base::DoSomething will return Base& or Base*, you can override that with Derived& Derived::DoSomething (or respectively Derived*).
What you want to do would be very breaking from compiler point of view. Imagine the following code:
//interface.hpp
struct Base { // sizeof(Base) == 8
virtual Base foo(); // could return through a register
};
//implementation.hpp
struct Derived: public Base { // sizeof(Derived) == 32 at least
std::string x;
Derived foo() override; // too big to return through register, must return through stack
};
//interface_user.cpp
#include "interface.hpp" // doesn't know about implementation.hpp
void bar(Base& myBase) {
Base b = myBase.foo(); // where is it returned? through a register or the stack? compiler knows for sure it should be a register, but...
}
Not to mention the obvious violation of Liskov's subsitution principle.
|
71,713,099 | 71,713,223 | Change base class fields in derived class with base class method | I am not sure where I am wrong here, but there seems to be some miss conception from my side.
I have a base class and a derived class and some methods like in this example.
class Base {
public:
int curr_loc;
Base(int curr_loc):curr_loc(curr_loc)
void reset(int curr_loc){
curr_loc = curr_loc;
}
}
class Derived: public Base{
public:
Derived(int curr_loc):Base(curr_loc)
}
Derived a(1);
a.reset(2);
a.curr_loc //is still 1?
When I call now "a.curr_loc", I still get 1. I thought that I would override the value with the method reset, but this is done on a different object...
Is there a way to do this without I need to copy the functions of the base class for the derived class?
| This code snippet
class Base {
public:
int curr_loc;
Base(int curr_loc):curr_loc(curr_loc)
void reset(int curr_loc){
curr_loc = curr_loc;
}
}
class Derived: public Base{
public:
Derived(int curr_loc):Base(curr_loc)
}
has syntactic errors.
You need to write
class Base {
public:
int curr_loc;
Base(int curr_loc):curr_loc(curr_loc){}
void reset(int curr_loc){
Base::curr_loc = curr_loc;
}
};
class Derived: public Base{
public:
Derived(int curr_loc):Base(curr_loc) {}
};
Pay attention to to the member function reset definition. It should be defined either like
void reset(int curr_loc){
Base::curr_loc = curr_loc;
}
or like
void reset(int curr_loc){
this->curr_loc = curr_loc;
}
Otherwise the parameter ciur_loc is assigned to itself in this statement
curr_loc = curr_loc;
because it hides the data member with the same name of the class Base.
|
71,713,307 | 71,714,123 | Why is std::ranges::views::take using templated type for difference? | Signature of take is
template< ranges::viewable_range R, class DifferenceType >
requires /* ... */
constexpr ranges::view auto take( R&& r, DifferenceType&& count );
It is a minor thing but I wonder why DifferenceType is not some ssize type(practically int64_t on modern machines).
Is this just to avoid warnings on comparisons of integers of different signednes, or is there some other design reason I am missing. My intuition that having a fixed type would make error messages easier to read, so I wonder what was the motivation.
If somebody is interested in code example, here it is, it feels a bit artificial since I wanted to keep it short, but it is quite possible to pass wrong type to take argument and then error message is unreadable(my favorite part is:
/opt/compiler-explorer/gcc-trunk-20220401/include/c++/12.0.1/bits/atomic_base.h:98:3:
note: candidate: 'constexpr std::memory_order
std::operator|(memory_order, __memory_order_modifier)'
).
#include <vector>
#include <iostream>
#include <ranges>
#include <string>
#include <fmt/format.h>
#include <fmt/ranges.h>
auto get_n(){
return std::string("2");
}
int main() {
std::vector v {2,3,5,7,11};
const auto n = get_n(); //oops this is std::string
auto dont_even = v | std::views::filter([](const int& i){return i%2==1;}) | std::views::take(n);
std::cout << fmt::format("{}", dont_even);
}
|
It is a minor thing but I wonder why DifferenceType is not some ssize
type(practically int64_t on modern machines). Is this just to avoid
warnings on comparisons of integers of different signednes, or is
there some other design reason I am missing.
Iterators for different range adaptors have different difference_types. The calculation of difference_type is sometimes not as simple as you think.
Taking iota_view as an example, the standard deliberately uses IOTA-DIFF-T(W) to calculate its difference_type, which makes the difference_type of iota_view<uint64_t> is __int128 and the difference_type of iota_view<__int128> is even a customized __detail::__max_diff_type in listdc++.
This is why the second parameter of views::take is a template and not a specific integer type, but note that the standard also has constraints on DifferenceType in [range.take.overview]:
The name views::take denotes a range adaptor object
([range.adaptor.object]). Let E and F be expressions, let T be
remove_cvref_t<decltype((E))>, and let D be
range_difference_t<decltype((E))>. If decltype((F)) does not model
convertible_to<D>, views::take(E, F) is ill-formed.
which requires that the DifferenceType must be convertible to R's difference_type, which also allows you to
auto r = std::views::iota(0)
| std::views::take(std::integral_constant<int, 42>{});
|
71,713,596 | 71,713,638 | "Undefined symbols for architecture arm64" - What does this mean? | I'm unable to get my code to run, and the internet doesn't seem to know why. I'm not sure what I need to let you know, but I am using CLion if that helps.
This is my plant.h file:
#ifndef COURSEWORK_PLANT_H
#define COURSEWORK_PLANT_H
using namespace std;
class Plant {
public:
void addGrowth();
int getSize();
string getName();
Plant(string x, int y);
private:
string plantName;
int plantSize;
};
#endif //COURSEWORK_PLANT_H
This is my plant.cpp file:
#include <iostream>
#include "plant.h"
using namespace std;
void Plant::addGrowth(int x) {
plantSize += x;
cout << "You have added " << x << " leaves to your plant. Well done!";
}
int Plant::getSize() {
return Plant::plantSize;
}
string Plant::getName() {
return Plant::plantName;
}
This is my main.cpp file:
#include <iostream>
#include "plant.h"
using namespace std;
int main() {
Plant myPlant("Bugg", 2);
return 0;
}
This is my CMakeLists.txt file:
cmake_minimum_required(VERSION 3.21)
project(Coursework)
set(CMAKE_CXX_STANDARD 14)
add_executable(Coursework main.cpp plant.h plant.cpp)
Thank you in advance for any help!
| Undefined symbol means that the symbols is declared but not defined.
For example in the class definition you have the following member function without parameters
void addGrowth();
But then you defined a function with the same name but now with one parameter
void Plant::addGrowth(int x) {
plantSize += x;
cout << "You have added " << x << " leaves to your plant. Well done!";
}
So the function declared in the class definition Plant is still undefined.
Also there is no definition of the constructor
Plant(string x, int y);
in the provided by you code.
And if you are using the name string from the standard library in the header plant.h then you need to include the header <string>
#include <string>
|
71,714,086 | 71,714,122 | Error: Type 'Classname' does not provide a call operator | Working on a program involving matrices and hit with an error involving Multiply and Transpose methods. I'm not sure how to proceed
//Header file
class Matrix
{
public:
Matrix(); // constructor
void initIdentity(int n); // initialize as an identity matrix of size nxn
void initFromFile(string fileName); // read the matrix from a file
bool isSquare(); // test whether matrix is square
int numRows(); // return number of rows
int numCols(); // return number of columns
double getVal(int row, int col); // return matrix value at given row/col location (0-indexed based)
void setVal(int row, int col, double val); // set the matrix value at given row/col location (0-index based)
Matrix Multiply(Matrix B); // post-multiply by B and return resulting matrix
Matrix Multiply(double A); // multiply by a scalar and return resulting matrix
Matrix Transpose(); // return transpose of matrix
vector<double> Diagonal(); // return a vector containing diagonal elements of the matrix
void Print(); // print the matrix to stdout
void Print(string name); // print the matrix to stdout with a name prefix
Matrix(int row, int col, double val); // initializing a matrix
private:
vector< vector<double> > matrix_;
vector< vector<int> > identMatrix_;
vector<double> innerVec_;
int numRows_;
int numCols_;
};
//Main file
Matrix Matrix::Multiply(double A){
Matrix ans(numRows_, numCols_, 0.0);
for (int i=0; i< numRows_; i++){
for (int j=0; j< numCols_; j++){
ans(i, j) = matrix_[i][j] * A;
}
}
return ans;
}
Matrix Matrix::Transpose(){
Matrix ans(numRows_, numCols_, 0.0);
for (int i=0; i<numRows_; i++){
for (int j=0; j<numCols_; j++){
ans(i, j) = matrix_[j][i];
}
}
return ans;
}
Error:
Main.cpp:110:7: error: type 'Matrix' does not provide a call operator
ans(i, j) = matrix_[i][j] * A;
^~~
Main.cpp:120:5: error: type 'Matrix' does not provide a call operator
ans(i, j) = matrix_[j][i];
^~~
| As noted in comments, you have:
ans(i, j) = matrix_[i][j] * A;
Which is trying to call operator() on ans. But you haven't defined this operator for this type of object.
You'd either need to define that operator so this code works, or just use the existing setVal:
ans.setVal(i, j, matrix_[i][j] * A);
|
71,714,560 | 71,714,935 | curl PUT JSON body having issues processing array's | I'm developing a library that communicates with a REST API. The method I wrote for PUT calls has worked up until this point.
void Command::put(const std::string url, const std::string body)
{
CURLcode ret;
struct curl_slist *slist1;
slist1 = NULL;
// slist1 = curl_slist_append(slist1, "Content-Type: multipart/form-data;");
slist1 = curl_slist_append(slist1, "Content-Type: application/json;");
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_BUFFERSIZE, 102400L);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, body.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)12);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, slist1);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "curl/7.79.1");
curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(curl, CURLOPT_SSH_KNOWNHOSTS, "/Users/$USER/.ssh/known_hosts");
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(curl, CURLOPT_FTP_SKIP_PASV_IP, 1L);
curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
ret = curl_easy_perform(curl);
curl_easy_cleanup(curl);
curl = NULL;
curl_slist_free_all(slist1);
slist1 = NULL;
}
curl_easy_cleanup(curl);
curl = nullptr;
curl_slist_free_all(slist1);
slist1 = NULL;
}
However, it seems to not work with arrays. Below are three debug put calls and their output. The first two work. The third does not.
// *** DEBUG ***
commandWrapper->put(
"http://192.168.1.7/api/x1CAh16Nr8NcKwgkUMVbyZX3YKFQrEaMAj5pFz0Z/lights/6/state", "{\"on\":true}");
commandWrapper->put(
"http://192.168.1.7/api/x1CAh16Nr8NcKwgkUMVbyZX3YKFQrEaMAj5pFz0Z/lights/6/state", "{\"bri\":123}");
commandWrapper->put(
"http://192.168.1.7/api/x1CAh16Nr8NcKwgkUMVbyZX3YKFQrEaMAj5pFz0Z/lights/6/state", "{\"xy\":[0.04,0.98]}");
[{"success":{"/lights/6/state/on":true}}]
[{"success":{"/lights/6/state/bri":123}}]
[{"error":{"type":2,"address":"/lights/6/state","description":"body contains invalid json"}}]2022-04-02T02:56:47.220Z - Living Room 1 - Status: 0
I'm a little lost on how to proceed. I verified that this command does work on the command line.
| You need to change this line:
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)12);
To this instead:
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)body.size());
Or, simply omit CURLOPT_POSTFIELDSIZE_LARGE completely, since body.c_str() is a pointer to a null-terminated string in this situation. Curl can determinant the size for you.
The JSON {xy:[0.04,0.98]} is 16 characters, longer than the 12 characters you are claiming, so you are truncating the JSON during transmission, which is why the server thinks it is invalid. Both {"on":true} and {"bri":123} are 11 characters (12 if you count the null terminator), so they are not truncated.
|
71,714,972 | 71,715,183 | How can i adding more nodes in first.cc in ns3? | I've just learned about first.cc and I want to change the number of nodes in first.cc from 2 to 3 or 4 5, but changing only nodes.Create(2) ==> nodes.Create(3) causes me some errors like this
assert failed.cond="c.GetN () ==2" , +0.00000000s -1 file=../src/point-to-point/helper/point-to-point-helper.cc, line=224
terminate called without an active exception
So I've to add some connection between them or else? Any help or suggestion will be appreciated!
| I want to start by encouraging you to use gdb (or lldb) to debug the program. If you did this, you would have found that this line in first.cc is causing the error:
devices = pointToPoint.Install (nodes);
Why would this happen? Well, if we go to the definition of the function being called, we find:
NetDeviceContainer
PointToPointHelper::Install (NodeContainer c)
{
NS_ASSERT (c.GetN () == 2); // line 224
return Install (c.Get (0), c.Get (1));
}
Looking at this code, it is clear that the PointToPointHelper::Install(NodeContainer) imposes the constraint that the NodeContainer can only contain two Nodes. This explains how the error you encountered occurred.
But why?
It's a (good) design choice. A PointToPointChannel can only be installed between exactly two PointToPointNetDevices, not more, not less. So, the implementation imposes the constraint that the NodeContainer can only contain two Nodes.
|
71,715,505 | 71,715,932 | How to create Mouse right click menu option using eventFilter in Qt? | I have a QGraphicsView which contains many QGraphicsItem. If I click mouse right click on any QGraphicsItem, the item should get select and right menu options should appear and then I will choose one of the options among them.To do that I have installed eventFilter and through it, I am using ContextMenu to create right click menu. Right click menu are getting cretaed properly. But propblem is I am not getting how to connect them to some function so that I can write logic for it.
It means if I clicked on save option that particular QGraphicsItem should get select and I should be able to go to some function where I will write logic for saving.
bool myClass::eventFilter(QObject *watched, QEvent *event)
{
switch(event->type())
{
case QEvent::ContextMenu:
{
QMouseEvent *mouseEvent = static_cast<QMouseEvent*> (event);
menu = new QMenu(this);
option = menu->addMenu("CopyOption");
option->addAction("save");
menu->exec(mouseEvent->globalPos());
break;
}
default:
break;
}
}
| In your approach you show a context menu when you have no information if any item is selected. It is rather bad idea. You don't want to show the context menu in any location of view. You have to check if a cursor mouse is over an item.
Why not to derive from QGraphicsItem and just overload mousePressEvent method. Inside this method check if right button of mouse is clicked. If so, show context menu and test which action is clicked. Minimal code would be:
class TItem : public QGraphicsItem
{
bool _selected = false;
public:
TItem(QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) {}
QRectF boundingRect() const override { return QRectF(0,0,20,20); }
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override {
painter->fillRect(QRectF(0,0,20,20),_selected ? QColor(0,255,255) : QColor(255,255,0));
}
void mousePressEvent(QGraphicsSceneMouseEvent* e) override {
QGraphicsItem::mousePressEvent(e);
if (e->button() & Qt::RightButton) {
QMenu menu;
QAction* a1 = menu.addAction(QString("test1"));
QAction* a2 = menu.addAction(QString("test2"));
if(a2 == menu.exec(e->screenPos())) {
test2();
_selected = true;
update();
}
}
}
void test2() {
QMessageBox::information(nullptr,"test2","test2");
}
};
All the job with checking is an item is under mouse is done by QT, mousePressEvent is invoked only if it is necessary.
Another approach would be override mousePressEvent on QGraphicsView. Inside which:
get all items belonging to the scene
iterate over them, checking if an item is under mouse -> QGraphicsItem has isUnderMouse method
if any item is under mouse, create QMenu and show it
check selected QAction, if it is save call a proper method which doing the save and mark the item as selected
|
71,715,630 | 71,715,789 | C++ Max Heap not sorting correctly after remove max | I'm attempting to remove the max by swapping the first and last element of the vector and then using pop_back. When I remove max I output max but the reordering process is not working correctly and I cannot figure out why.
I have attempted changing the way I am testing multiple times and the results do not change. Can anyone see where I have gone wrong?
#include <vector>
#include <string>
class Heap
{
public:
void insert(int data)
{
int parent = 0;
heap.push_back(data);
current = heap.size() - 1;
parent = (current - 1) / 2;
if (heap.size() > 1)
{
while (heap.at(parent) < heap.at(current))
{
if (heap.at(current) > heap.at(parent))
{
std::swap(heap.at(parent), heap.at(current));
current = parent;
parent = (parent - 1) / 2;
}
}
}
// for(int i = 0; i < heap.size(); i++)
// {
// std::cout << heap.at(i) << std::endl;
// }
// std::cout << std::endl;
}
void remove_max()
{
if (!heap.empty())
{
if (heap.size() == 1)
{
heap.pop_back();
return;
}
std::swap(heap.at(0), heap.at(heap.size() - 1));
heap.pop_back();
int parent = heap.at(0);
int lchild = (parent * 2) + 1;
int rchild = (parent * 2) + 2;
// while(lchild < heap.size() && rchild < heap.size())
// {
// if(heap.at(lchild) < heap.at(rchild))
// {
// std::swap(heap.at(parent), heap.at(rchild));
// parent = rchild;
// }
// else
// {
// std::swap(heap.at(parent), heap.at(lchild));
// parent = rchild;
// }
// lchild = (lchild * 2) + 1;
// rchild = (rchild * 2) + 2;
// }
if (lchild < rchild)
{
while (parent > lchild)
{
std::swap(heap.at(parent), heap.at(lchild));
lchild = (lchild * 2) + 1;
parent = (rchild - 1) / 2;
}
}
else
{
while (parent > rchild)
{
std::swap(heap.at(parent), heap.at(rchild));
rchild = (rchild * 2) + 2;
parent = (rchild - 1) / 2;
}
}
}
// for(int i = 0; i < heap.size(); i++)
// {
// std::cout << heap.at(i) << std::endl;
// }
// std::cout << std::endl;
return;
}
int max()
{
return heap.at(0);
}
bool empty()
{
return heap.empty();
}
private:
std::vector<int> heap;
int current = 0;
};
int main()
{
// TODO: implement!
Heap myHeap;
std::string command;
int data;
do
{
std::cin >> command;
if (command == "add")
{
std::cin >> data;
myHeap.insert(data);
}
else if (command == "run")
{
std::cout << myHeap.max() << std::endl;
myHeap.remove_max();
}
else if (command == "exit")
{
while (!myHeap.empty())
{
std::cout << myHeap.max() << std::endl;
myHeap.remove_max();
}
}
} while (command != "exit");
return 0;
}
| Your math is completely wrong. You're confusing stored values with index calculations. In some places you are calculating values by multiplying indexes, in other you are calculating indexes by multiplying stored values. That's never going to work.
void remove_max()
{
if (heap.empty())
return;
std::swap(heap.at(0), heap.at(heap.size() - 1));
heap.pop_back();
size_t parent = 0;
do
{
// get first child slot
size_t child = 2*parent + 1;
if (child < heap.size())
{
// calculate right-child index.
size_t rchild = 2*(parent+1);
if (rchild < heap.size() && heap[rchild] > heap[child])
child = rchild;
// got the child slot. now compare.
if (heap[child] > heap[parent])
{
std::swap(heap[child], heap[parent]);
parent = child;
}
else
{
// parent larger than children. stop here.
break;
}
}
else
{
// reached a node with no children
break;
}
} while (true);
}
|
71,716,106 | 71,716,256 | Can't execute program from the source code even though the compiling process had no error and warnings(Dev C++) | Source Code :
#include <stdio.h>
#include <conio.h>
using namespace std;
int main () {
char huruf;
char nama[]="Muhammad Juan Syarin";
int usia, berat, tinggi;
int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}
huruf='M';usia=19;berat=68;tinggi=170;
printf("Huruf depan : %s", huruf);
printf("Nama Lengkap : %s", nama);
printf("Usia : %d", usia);
printf("\nBerat : %d", berat);
printf("\nTinggi : %d", tinggi);
printf("\nNilai ke-7 dari Array (77,78,80,81,82,83,85,89) adalah %i", arr[7]);
getchar();
return 0;
}
I tried to change the value and the variable and to be true i don't know what to do since this is the very first time i try to learn how to make a source code.I hope some guidance for this newbies.
| You missed a semicolon while defining the array. Also the format specifier in the first printf statement is for strings, not characters. Replace the %s there with %c. So in change line 10 to int arr[8] = {1, 2, 3, 4, 5, 6, 7, 8}; and replace %s in line 13 to %c
|
71,716,181 | 71,727,052 | embedded python using pybind11 in c++ class: how to call member function of c++ class from python | I've a class with a method (MyClass::methodWithPy) that can be customized by some python script using embedded pybind11, which so far works.
Inside the python script I need to somehow call methods of the c++ class. Is this possible somehow?
This is what I have so far, but I do not know how to call the class method from within python.
class MyClass
{
public:
MyClass();
double pureCMethod(double d);
void methodWithPy();
private:
double m_some_member;
};
// method of the c++ class that has acess to members and does some computation
double MyClass::pureCMethod(double d)
{
// here we have some costly computation
return m_some_member*d;
}
// 2nd method of the c++ class that uses embedded python
void MyClass::methodWithPy()
{
namespace py = pybind11;
using namespace py::literals;
py::scoped_interpreter guard{};
py::exec(R"(
print("Hello From Python")
result = 23.0 + 1337
result = MyClass::pureCMethod(reslut) // pseudocode here. how can I do this?
print(result)
)", py::globals());
}
| Thanks @unddoch for the link. That got me to the answer.
PYBIND11_EMBEDDED_MODULE was the part I was missing.
First you need to define an embedded python module containing the class and the methos:
PYBIND11_EMBEDDED_MODULE(myModule, m)
{
py::class_<MyClass>(m, "MyClass")
.def("pureCMethod", &MyClass::pureCMethod);
}
Then pass the class to python (import the module first)
auto myModule = py::module_::import("myModule");
auto locals = py::dict("mc"_a=this); // this pointer of class
And now its possible to access the member methods from python
py::exec(R"(
print("Hello From Python")
print(mc.pureCMethod(23))
)", py::globals(), locals);
|
71,716,400 | 71,716,416 | error with vector, unique_ptr, and push_back | I am learning smart pointers, with the following example test.cpp
#include<iostream>
#include<vector>
#include<memory>
struct abstractShape
{
virtual void Print() const=0;
};
struct Square: public abstractShape
{
void Print() const override{
std::cout<<"Square\n";
}
};
int main(){
std::vector<std::unique_ptr<abstractShape>> shapes;
shapes.push_back(new Square);
return 0;
}
The above code has a compilation error "c++ -std=c++11 test.cpp":
smart_pointers_2.cpp:19:12: error: no matching member function for call to 'push_back'
shapes.push_back(new Square);
Could someone help explain the error to me? By the way, when I change push_back to emplace_back, the compiler only gives a warning.
| push_back expects an std::unique_ptr, when passing raw pointer like new Square, which is considered as copy-initialization, the raw pointer needs to be converted to std::unique_ptr implicitly. The implicit conversion fails because std::unique_ptr's conversion constructor from raw pointer is marked as explicit.
emplace_back works because it forwards arguments to the constructor of std::unique_ptr and construct element in direct-initialization form, which considers explicit conversion constructors.
The arguments args... are forwarded to the constructor as std::forward<Args>(args)....
|
71,717,145 | 71,717,178 | C++ class properties not updating properly | I have a custom galaxy class which has a custom property pos.
pos is an instance of another custom class Vector3D.
A Vector3D has properties x, y, z. The arithmetic operations for Vector3D is basic vector math, the relevant ones below:
Vector3D Vector3D::operator+(const Vector3D& vec) {
return Vector3D(x + vec.x, y + vec.y, z + vec.z);
}
Vector3D &Vector3D::operator+=(const Vector3D& vec) {
x += vec.x;
y += vec.y;
z += vec.z;
return *this;
}
Vector3D Vector3D::operator*(double val) {
return Vector3D(x * val, y * val, z * val);
}
galaxy.cpp has some methods below:
void galaxy::updatePos(double dt) {
pos += vel * dt;
}
void galaxy::updateVel(Vector3D accel, double dt) {
vel += accel * dt;
}
void galaxy::updateStateVectors(Vector3D accel, double dt) {
updateVel(accel, dt);
updatePos(dt);
}
main.cpp calls method updateStateVectors as follows:
// within some while() loop
for (auto g : galaxies) {
Vector3D accel = Vector3D();
for (auto g2 : galaxies) {
if (g != g2) {
accel += g.getGravityAccelBy(g2);
}
}
g.updateStateVectors(accel, dt);
}
(galaxies is a std::vector<galaxy>)
The problem is, the changes made to g.pos (or g.vel) within this for loop doesn't seem to persist. Each iteration on the while loop, I see that g.pos is back to its original value, disregarding the change it previously underwent in the for loop. What am I missing?
This might end up being a very silly mistake but I mainly code in Python and I've spent more time on this than I'd like to admit.
| auto returns a copy of the object, so the original one is copied, not modified. You're then altering a copy of the original object.
Using & will make you reference the original one, so that you can alter it.
for (auto & g : galaxies) {
Vector3D accel = Vector3D();
for (auto & g2 : galaxies) {
if (g != g2) {
accel += g.getGravityAccelBy(g2);
}
}
g.updateStateVectors(accel, dt);
}
|
71,717,211 | 71,717,237 | C++ Single line If-Else within Loop | I read Why I don't need brackets for loop and if statement, but I don't have enough reputation points to reply with a follow-up question.
I know it's bad practice, but I have been challenged to minimise the lines of code I use.
Can you do this in any version of C++?
a_loop()
if ( condition ) statement else statement
i.e. does the if/else block count as one "statement"?
Similarly, does if/else if.../else count as one "statement"? Though doing so would become totally unreadable.
The post I mentioned above, only says things like:
a_loop()
if(condition_1) statement_a; // is allowed.
| Yes, syntactically you can do that.
if/else block is a selection-statement, which is a kind of statement.
N3337 6.4 Selection statements says:
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condition ) statement
|
71,717,523 | 71,717,625 | Is it legal to use struct itself as template argument? | According to Template parameters and template arguments on cppreference.com:
A template argument for a type template parameter must be a type-id,
which may name an incomplete type
That means that this example (copied from that page) is legal:
// Example 0
template <typename T>
struct X {};
struct A;
int main() {
X<A> x1;
}
and, I suppose, also this is legal:
// Example 1
template <typename T>
struct X {};
struct A {
X<A> x1;
};
int main() {
A a1;
}
Now, let's complicate a bit the code:
// Example 2
template <typename T>
struct X {
using type = typename T::type;
};
struct A {
using type = int;
X<A>::type x1;
};
int main() {
A a1;
}
In this case, A is still an incomplete type when used as template argument, and the code compiles. Now, if I change the order of the lines in A:
// Example 3
template <typename T>
struct X {
using type = typename T::type;
};
struct A {
X<A>::type x1; // ERROR HERE
using type = int;
};
int main() {
A a1;
}
the code does not compile anymore. Clang error message is something like no type named 'type' in 'A', but also GCC, ICC and MSVC return similar errors (see this demo on godbolt.com), and this seems almost identical to that of typedefs on CRTP, discussed here.
Anyway, the behavior seems reasonable: compilers use all the properties of A defined at the point X<A> is used.
But what does the C++14 (or later) standard say about it? Is it legal to rely on the behavior of the working Example 2?
| This is CWG issue 287.
You can look at the reasoning there, but my understanding from it is that the consensus is that the standard technically currently doesn't allow either your last or second-to-last example, since the point of instantiation of X<A> will be before the definition of A, where typename T::type cannot be formed.
However, as indicated in the proposed resolution, it is intended that even though the point of instantiation would be before the definition of A, names declared in A before the point requiring instantiation of X<A> shall still be visible to the instantiation.
That is what the compilers implement and you observe.
|
71,717,779 | 71,717,992 | How do I refer to a class with multiple template types by only one of the types? | Let's say I have a class Shape with the declaration:
template <typename T, typename U, typename V>
class Shape {
T value;
U input;
V input2;
...
}
As it is, if I create a Shape object, its type will be something like Shape<int, float, double> - for example.
But what if I want to be able to create a Shape object and still give it inputs of different types (like float and double), but I want its type to be Shape<int>.
That is, after creating a Shape object, I want callers to only care about the type of its value, not the type of its inputs. How do you suggest I go about it?
I've learned that I cannot store templates member variables without having declared the template types at the top. I've also attempted using an alias like:
template <typename T, typename U, typename V>
using ShapeAlias<T> = Shape<T, U, V>
But that doesn't work either. Do you have any suggestions on how I can go about this?
I'm considering some form of inheritance where there's a base class with only one of the types, and the derived class contains all three types, but I thought I should check here.
Edit: I need the second and third types because the idea is that a user will be able to pass a function to a Shape constructor to calculate the value of T, which could look like:
auto creator = [](U a, V b){
return (something of type T)
}
And I want to keep the values of the input types in the Shape class.
So from a client's perspective, their code should look like this:
Shape<T> shapeA(Shape<T>(uValue, vValue, creator)
As it is now, they would have to do:
Shape<T, U, V> shapeA(Shape<T, U, V>(uValue, vValue, creator))
| It seems like you are looking for CTAD (class template argument deduction). It only works when the caller does not specify any template argument, hence a layer of indirection has to be added:
template <typename T>
struct ShapeWrap {
template <typename U,typename V>
struct Shape {
T value;
U input;
V input2;
Shape(const U& u,const V& v) : input(u),input2(v) {}
};
};
Caller can now call:
auto s = ShapeWrap<int>::Shape(1.0,0.1f);
To instantiate ShapeWrap<int>::Shape<double,float>.
Alternatively via template argument deduction of a function template:
template <typename T, typename U,typename V>
struct Shape {
T value;
U input;
V input2;
Shape(const U& u,const V& v) : input(u),input2(v) {}
};
template <typename T,typename U,typename V>
Shape<T,U,V> make_shape(const U& u, const V& v) {
return {u,v};
}
int main() {
auto s = make_shape<int>(1.0,0.1f);
}
|
71,718,036 | 71,718,136 | Program only allows login if the email matches the last registered user. C++ | So, I've been trying to make this program this entire day and I got stuck at this big problem where I cannot it to log into the account by verifying with the previously existing data in my txt file of registered users.
NOTE: userEmail is inheritted from another class and is defined.
This is my login function:
void logIn() { // ! Function to log into an existing account.
system("cls");
string loginEmail, loginPassword;
bool verifyEmail = false;
cout<<"\n~\t~\tLogging into an existing account..\t~\t~\n";
cout<<"\nEmail: ";
cin.ignore();
getline(cin,loginEmail);
ifstream checkEmail("registeredUsers.txt");
ifstream open("registeredUsers.txt");
while(checkEmail>>userEmail && loginEmail.find('@') != string::npos && loginEmail.length() > 6) {
if (userEmail == loginEmail) {
verifyEmail = true;
}
else {
verifyEmail = false;
}
}
if (verifyEmail == true) {
cout<<"\nPassword: ";
getline(cin,loginPassword);
}
else {
cout<<"Email not found.. Please register a new account.\n";
system("pause");
return;
}
system("pause");
}
Lets say if my registeredAccounts.txt has lines
12345@gmail.com
testing@gmail.com
fortified@gmail.com
Then it would only ever continue to the password section if I typed fortified@gmail.com in my program and it would not let me proceed if i typed any other emails.
| Break out of the while loop immediately after you set verifyEmail = true. There is no need to check additional email addresses if you have already found a match. As it is, your code goes on to check non-matching email addresses, setting verifyEmail back to false.
For example:
while(checkEmail>>userEmail && loginEmail.find('@') != string::npos && loginEmail.length() > 6) {
if (userEmail == loginEmail) {
verifyEmail = true;
break;
} else {
verifyEmail = false;
}
}
Now, you don't actually need to set verifyEmail to false. So you can just use:
while(checkEmail>>userEmail && loginEmail.find('@') != string::npos && loginEmail.length() > 6) {
if (userEmail == loginEmail) {
verifyEmail = true;
break;
}
}
|
71,718,142 | 71,718,912 | Race condition when increase a variable value in c++ | I was asked this question in an interview recently. The question is if we have a function that takes a reference of int i as parameter and only does i++. There is no any thread synchronizations. Now in main function, we initialize variable i with 0, then we create 7 new threads to run the same function and pass the same variable i, and after all threads are joined, how many possible values the variable i has? Thank you very much!
I tried thinking about the instructions of doing i++. Like load, add and store instructions. Assume we’re using g++ compiler and in Linux OS.
| The specific instructions used to increment the variable depends on the instruction set, but unless using some kind of atomic increment, it will break down into load/add/store operations as you are describing. On x86 that might be done with a single inc instruction, but without locking it will still break down to internal load/add/store operations.
You will want to look at the possible interleaving of those sequences. The interleaving is caused by interruption of the non-atomic sequences. Here is one possible such possible interleaving:
thread 1 thread 2
load
load
add
store
add
store
That sequence will leave the variable incremented only once, by thread 1, because thread 2's increment operation is effectively ignored — thread 1 stores last so "wins". (Thread 2 started with the wrong value in some sense anyway, so thread 2's store has the same value (+1) as thread 1's store.)
So, on one extreme the answer would be that the variable will be incremented only by one. On the other extreme, if each thread successfully increments without interruption of that sequence, then the variable would be incremented 7 times. All intermediate values (incremented by 2-6) are also possible.
Since there is no synchronization at all, we also have to consider the possibility that we observe the original 0 after the joins, though I think this is unlikely due to the natural synchronization of system calls involved in creating threads and joining them.
|
71,718,249 | 71,718,895 | STL-style algorithm: returning via OutputIterator | I am trying to implement an algorithm that merges elements in an ordered container, if they satisfy a BinaryPredicate.
template <typename ForwardIt,
typename OutputIt,
typename BinaryPredicate,
typename Merge>
void merge_adjacent(ForwardIt first,
ForwardIt last,
OutputIt out,
BinaryPredicate pred,
Merge merge)
{
if(first != last)
*out = *(first++);
while(first != last)
{
if(pred(*first, *out))
*out = merge(*out, *(first++));
else
*(++out) = *(first++);
}
}
When I pass an empty container to put the result in (via OutputIterator), I get an segmentation fault - I also understand why, because the container does not have any space reserved... When I reserve enough space before passing the OutputIterator, the container stays empty...
I am a lil puzzled because I was following an example implementation of the std::transform function on cppreference:
template< class InputIt,
class OutputIt,
class UnaryOperation >
OutputIt transform( InputIt first1,
InputIt last1,
OutputIt d_first,
UnaryOperation unary_op )
{
while (first1 != last1) {
*d_first++ = unary_op(*first1++);
}
return d_first;
}
What am I doing wrong?
My main.cpp for completeness:
#include "merge_adjacent.hpp"
#include <vector>
#include <iostream>
#include <stdexcept>
class Sale
{
public:
Sale(int date, double amount)
: date(date),
amount(amount)
{}
Sale()
: date(0),
amount(0)
{}
int getDate() const
{
return date;
}
double getAmount() const
{
return amount;
}
private:
int date;
double amount;
};
bool sameDate(Sale const& sale1, Sale const& sale2)
{
return sale1.getDate() == sale2.getDate();
}
Sale mergeSales(Sale const& sale1, Sale const& sale2)
{
if (sale1.getDate() != sale2.getDate()) throw ;
return Sale(sale1.getDate(), sale1.getAmount() + sale2.getAmount());
}
int main()
{
std::vector<Sale> sales = {Sale{1,2.9}, Sale(1,2.2),Sale(1,4.7),Sale(2,1.9),Sale(3,3.8),Sale(3,1.1),Sale(5,2.9),Sale(6,2.9),Sale(6,2.9)};
std::vector<Sale> merged;
merged.reserve(20);
merge_adjacent(sales.begin(), sales.end(), merged.begin()/*std::back_inserter(merged)*/, sameDate, mergeSales);
std::cout << "size of merged must be 5: " << merged.size() << std::endl;
return 0;
}
| You may be looking for something like this:
template <typename InputIt,
typename OutputIt,
typename BinaryPredicate,
typename Merge>
void merge_adjacent(InputIt first,
InputIt last,
OutputIt out,
BinaryPredicate pred,
Merge merge)
{
if (first == last) return;
auto accum = *first++;
while (first != last) {
auto cur = *first++;
if (pred(cur, accum)) {
accum = merge(accum, cur);
} else {
*out++ = accum;
accum = cur;
}
}
*out++ = accum;
}
Demo. Not tested very thoroughly, I only confirmed it worked on your example. I think I'm staying within the capabilities of InputIterator and OutputIterator, but I haven't tested that either.
|
71,718,840 | 71,718,900 | << operator overloading and template specialization | As part of study purpose, I was just playing with template specialization together with operator overloading
#include <iostream>
template<class T>
void operator<<(std::ostream& COUT,T val)
{
std::operator<<(COUT,val); //works for basic data types
}
//specializing for const char*
template<>
void operator<<(std::ostream& COUT,const char* val)
{
std::operator<<(COUT,val);
}
int main()
{
std::cout<<"samplestring"; //getting error here
return 0;
}
I am getting following error which I cannot figure out.
<source>:17:14: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'const char [13]')
17 | std::cout<<"samplestring";
| ~~~~~~~~~^~~~~~~~~~~~~~~~
| | |
| | const char [13]
| std::ostream {aka std::basic_ostream<char>}
what is the problem here
Thank you..!
| The problem is there is already operator<<(std::ostream& COUT,const char* val) defined by the standard library.
So now there are two symbols
std::operator<<(std::ostream& ostream,const char* val);
operator<<(std::ostream& COUT,const char* val); // YOURS
Because the symbols are different, there are no multiple-definition errors.
For a call std::cout << "Hello", the compiler searches for all operator<< functions currently defined at the call site. That looks like it is just your function, but the compiler also looks into all namespaces in which the passed arguments are defined. In this case it is std:: namespace and there the compiler finds the STL version. That is called argument dependent lookup(ADL).
Since both functions are templates and neither is more specialized than the other, the call is ambiguous.
Please do not use all capital letters as variable COUT, that is usually reserved for macros, with one-letter template parameters being exception T.
//works for basic data types
That is also not true, std::cout<<5; will NOT call your definition with T. Because there exists std::ostream::operator<<(int v) method. Same lookup happens but since this method is not a template, it is a better candidate and thus chosen. Your template function is never called.
|
71,718,920 | 71,718,982 | gcc: invalid error "use of deleted function" (copy constructor)? | Simplified issue:
#include <stdio.h>
class X
{
public:
int a = 0;
X() { printf("constr-def %d\n", a); }
X(int i):a(i+1) { printf("constr-i %d\n", a); }
int operator=(int i) { a = i; return i; }
operator bool() { return !!a; }
//~ X(const X& o) { a = o.a; printf("copy-constr %d\n", a); };
//~ const X& operator=(const X& o) { a = o.a; printf("copy-op %d\n", a); return *this; };
X(const X& o) = delete;
const X& operator=(const X& o) = delete;
};
int main() {
X x;
X y = 5; // should be equivalent to X y(5)
printf("results: %d %d\n", x.a, y.a);
}
Output when compiled as is with MSVC; or with gcc / MSVC and non-deleted copy constructor variants active (commented out above):
>g++ -Os dede.cpp -o dede
>dede
constr-def 0
constr-i 6
results: 0 6
>Exit code: 0
--> Copy constructor is never used; MSVC compiles successfully as is.
Compile as is with gcc (v9.3.0 current mingw/msys64 build):
>g++ -Os dede.cpp -o dede
dede.cpp: In function 'int main()':
dede.cpp:20:8: error: use of deleted function 'X::X(const X&)'
20 | X y = 5; // should be equivalent to X y(5)
| ^
dede.cpp:14:5: note: declared here
14 | X(const X& o) = delete;
| ^
dede.cpp:7:2: note: after user-defined conversion: 'X::X(int)'
7 | X(int i):a(i+1) { printf("constr-i %d\n", a); }
| ^
>Exit code: 1
Why does gcc error out with use of deleted copy constructor, when he doesn't use it in the non-deleted case?
| Before C++17 such copy elision is an optimization, which is permitted but the copy (or move) constructor still must be present and accessible.
Since C++17 the code works fine because for mandatory copy elision the copy/move constructors need not be present or accessible again.
C++17 core language specification of prvalues and temporaries is fundamentally different from that of the earlier C++ revisions: there is no longer a temporary to copy/move from.
|
71,719,266 | 71,719,599 | C++17 decorate lambda or member function with non-capturing lambda | I'm trying to craft a function that returns a non-capturing lambda (so it can be converted to a function pointer) that decorates an inner function, where the inner function can be either a lambda or a member function pointer.
Compiler Explorer link for reference, which I'll dissect in the following.
I've come up with two strategies, one for lambdas and the other for member functions. Specifically, for lambdas
template <typename Callable>
auto decorate_lambda(Callable&& lambda) {
static const Callable callable = std::forward<Callable>(lambda);
return [](auto... args) {
return 100 + callable(std::forward<decltype(args)>(args)...);
};
}
Saving off the lambda as a static allows callable to be used in a non-capturing lambda. This is fine because the decorate_lambda template instantiation will be unique for each lambda (IIRC).
For member functions the strategy is somewhat different (note the template parameter)
template <auto callable>
auto decorate_memfn() {
return [](auto... args) {
return 100 + std::mem_fn(callable)(std::forward<decltype(args)>(args)...);
};
}
I can then do something like
const auto decorated_lambda =
decorate_lambda([](int i) { return i + 1; });
const auto decorated_memfn =
decorate_memfn<&Worker::work>();
int (*lambda_fnptr)(int) = decorated_lambda;
int (*memfn_fnptr)(Worker&, int) = decorated_memfn;
resulting in function pointers that can be used e.g. in a C interface (ultimately).
The end result that I would like is to roll decorate_lambda and decorate_memfn into a single decorate(lambda_or_memfn) function (using template specialisation, if constexpr, or whatever). E.g.
decorate([](int i) { return i + 1; });
decorate(&Worker::work);
I.e. essentially I would like to have decorate_memfn(&Worker::work) rather than decorate_memfn<&Worker::work>(). The problem is that
Passing a member function pointer as a parameter, rather than template argument, means the member function pointer is no longer considered a static/global variable within decorate_memfn. Is there a way to force the compiler to recognize that a parameter is from a static/global and hence allow it's use within a lambda without capturing?
Doing something similar to decorate_lambda with it's static trick doesn't work for member function pointers because the template instantiation is not necessarily unique (i.e. if two Callables have the same signature). Maybe there is a way to make it unique, though?
I understand C++20 could help, but unfortunately I'm stuck with C++17.
Any hints much appreciated!
| First, your decorate_lambda is buggy: it silently breaks if you call it with a stateful callable. As a simple check, you could allow callables only if std::is_empty_v is true.
The end result that I would like is to roll decorate_lambda and decorate_memfn into a single decorate(lambda_or_memfn) function
You can use std::integral_constant
template<auto x>
inline constexpr std::integral_constant<decltype(x), x> constant{};
template<typename T, typename F, F T::* x>
auto decorate(std::integral_constant<F T::*, x>)
{
return [](auto&&... args) {
return 100 + std::mem_fn(x)(decltype(args)(args)...);
};
}
auto d = decorate(constant<&Worker::work>);
|
71,719,326 | 71,719,468 | Writing a custom std::next_permutation(string) function | I am trying to implement a function similar to std::next_permutation(std::string w). Please see the code below for how I am doing this:
string biggerIsGreater(string w) {
// 1. Find the largest non-increasing suffix. This suffix already has the maximum permutation.
// 2. Assign the char before that as the pivot
// if there is no such char,
// then the whole string is non-increasing => no next permutation.
// 3. Swap the pivot with the smallest element in the suffix that is greater than the pivot itself.
// If there are multiple smallest char > pivot, then choose the rightmost one
// As this will keep the suffix non-increasing.
// 4. reverse the order of the suffix, so that it is now non-decreasing.
// This is the lowest next permutation.
// 1.
int suffix_start = (int)w.length()-1;
//single character has no next permutation:
if (suffix_start == 0) return "no answer";
// else keep decreasing suffix_start until the element is not > the previous.
while(w[suffix_start-1] <= w[suffix_start]) {
suffix_start--;
if(suffix_start==0) return "no answer";
}
// 2.
int pivot = suffix_start - 1;
// 3.
int smallest_char = (int)w.length()-1;
while(w[smallest_char] <= w[pivot]) smallest_char--;
if(w[smallest_char] == w[smallest_char-1]) while (w[smallest_char] != w[smallest_char-1]) smallest_char--;
swap(w[pivot], w[smallest_char]);
// 4.
reverse(w.begin() + pivot + 1, w.end());
return w;
}
However, this code appears to fail on strings like bb. Please can you tell me where I have gone wrong?
If I print out w after the reversal, I get this: (the first line is the number of test cases):
input:
5
ab
bb
hefg
dhck
dkhc
Then the program prints ba (which means the first one worked) but nothing else is printed.
So the error is in dealing with bb.
Note: My objective is to write this without std::next_permutation() function from <algorithm>.
| I re-implemented your function my own way, if it is not an acceptable answer, then at least it is benefitial for educational purpose. Maybe by my code you can figure out what's wrong in yours.
If this is last permutation, like "bb" case then first lexicographical permutation is returned, same as in std::next_permutation().
Try it online!
#include <algorithm>
#include <iostream>
#include <string>
std::string next_permutation(std::string x) {
if (x.size() <= 1)
return x;
std::ptrdiff_t i = 0, j = 0;
for (i = x.size() - 2; i >= 0 && x[i] >= x[i + 1]; --i);
if (i >= 0) {
for (j = i + 1; j < x.size() && x[i] < x[j]; ++j);
--j;
std::swap(x[i], x[j]);
}
std::reverse(x.begin() + (i + 1), x.end());
return x;
}
int main() {
auto Test = [](auto const & s){
std::cout << "'" << s << "' -> '"
<< next_permutation(s) << "'" << std::endl;
};
Test("ab");
Test("bb");
Test("hefg");
Test("dhck");
Test("dkhc");
Test("abc");
Test("aabb");
Test("cba");
}
Output:
'ab' -> 'ba'
'bb' -> 'bb'
'hefg' -> 'hegf'
'dhck' -> 'dhkc'
'dkhc' -> 'hcdk'
'abc' -> 'acb'
'aabb' -> 'abab'
'cba' -> 'abc'
|
71,719,493 | 71,720,203 | Function or library to create strings from every primitive data type and String? | Is there a function to create strings or char[] by concatenating multiple types?
Something like:
int int_type = 5;
float float_type = 3.14;
String string_type = "I'm";
char char_type = ' ';
char char_arr_type[9] = "a pirate";
String merged = x_func(int_type, float_type, string_type, char_type, char_arr_type);
// expected: "53.14I'm a pirate"
| in c++17 you can use fold expression and string stream.
Example:
#include <iostream>
#include <sstream>
using namespace std;
template<typename ... Args>
string makeString(Args ... args)
{
stringstream ss;
(ss << ... << args);
return ss.str();
}
int main(){
cout<< makeString("a b" , 1, "c d");
}
Output: a b1c d
|
71,719,584 | 71,720,289 | Convert Vector of integers into 2d array of type const int* const* | I have a vector of integers that I should make into a 2d array. The row and column size of the new 2d array are given by user and contain all the integers from previous vector. The 2d array should be of type const int* const*. How do I do this in c++?
| Try something like this:
std::vector<int> nums;
// fill nums as needed...
int rows, cols;
std::cin >> rows >> cols;
if ((rows * cols) > nums.size())
// error
int** arr = new int*[rows];
for (int row = 0; row < rows; ++row) {
arr[row] = new int[cols];
for (int col = 0; col < cols; ++col) {
arr[row][col] = nums[(row*cols)+col];
}
}
// use arr as needed...
for (int row = 0; row < rows; ++row) {
delete[] arr[row];
}
delete[] arr;
|
71,719,941 | 71,720,000 | C++ Function to be called later | I am a complete beginner just started to learning C++. I want to make function say a formula which would take square of a variable. Check the code below to understand better
double raiseToPow(double x, int power)
{
double result;
int i;
result = 1.0;
for (i = 1; i <= power; i++)
{
result *= x;
}
return (result);
}
The above code would be used to square a variable.
I know you can save functions and then recall them to be used in the program. But I do not know how? Do I save it in a separate file and then recall it or do I write above every code. I do have searched Stackoverflow with the same query but most of the questions are way too advance for me to understand them and replicate them. Is there simple and beginner friendly explanation. Or some video that would be great.
Best Regards
| For now, add a main function and call that function. Add this to your code:
#include <iostream>
int main() {
double value = 2.0;
double result = raiseToPow(value, 2);
std::cout << result << 'n';
return 0;
}
Compile the file into an executable and run the executable.
|
71,720,133 | 71,720,607 | Deleted assignment operator error which isn't used | Implicitly deleted member assignment causes a compile error in code that never calls the assignment operator.
#include <vector>
struct A {
A(int arg) : i{ arg } {}
// A& operator=(const A& arg) { return *this; }
const int i;
};
int main()
{
std::vector<A> v;
v.emplace_back(1); // vector of one A initialized to i:1
// The next line causes this compiler error 'A &A::operator =(const A &)': function was implicitly deleted because 'A' has a data member 'A::i' of const - qualified non - class type
v.erase(v.begin()); // ending the lifetime of A and but now using the same storage
v.emplace_back(2); // vector of one A initialized to i:2
}
If I define an assignment operator then the code compiles and, of course, never calls it. Running the code with all special member functions defined shows, as expected, that only the CTOR, and DTOR is called.
So why is this error occurring in multiple compilers?
https://godbolt.org/z/44foEMh6o
| Consider how the erase function might be implemented. It might look something like this:
constexpr iterator erase(iterator pos) {
for (auto i = pos; i + 1 != end(); i++) {
*i = move(*(i + 1));
}
pop_back();
return pos;
}
(The real parameter type is const_iterator, but let's ignore this detail.)
If you choose to erase the last element of the vector, then the loop will run zero times and the assignment operator will be invoked zero times. However, you still force the compiler to instantiate the entire body of the erase function. When this happens, the compiler must perform overload resolution and check whether there is a usable assignment operator. If there is not, a compilation error occurs.
Expecting your program to compile is like expecting this program to compile:
void foo() = delete;
void bar(int num_times) {
while (num_times--) foo();
}
int main() {
bar(0);
}
Would this program compile? Of course not. Even though foo will never be invoked, the mere fact that you attempt to compile some code that contains a call to foo will make the program ill-formed.
With a std::vector, it is possible for you to say "I promise that I will only be removing the last element, so please do not attempt to compile any code that requires the assignment operator". To do this, use the pop_back function instead of erase.
|
71,720,201 | 71,720,467 | Why does MSVC compiler put template instantiation binaries in assembly? | I encountered something weird in the MSVC compiler.
it puts function template definition in assembly while optimization eliminates the need for them.
It seems that Clang and GCC successfully remove function definition at all but MSVC does not.
Can it be fixed?
main.cpp:
#include <iostream>
template <int n> int value() noexcept
{
return n;
}
int main()
{
return value<5>() + value<10>();
}
assembly:
int value<5>(void) PROC ; value<5>, COMDAT
mov eax, 5
ret 0
int value<5>(void) ENDP ; value<5>
int value<10>(void) PROC ; value<10>, COMDAT
mov eax, 10
ret 0
int value<10>(void) ENDP ; value<10>
main PROC ; COMDAT
mov eax, 15
ret 0
main ENDP
Sample code on godbolt
| The /FA switch generates the listing file for each translation unit. Since this is before the linking stage, MSVC does not determine if those two functions are required anywhere else within the program, and are thus still included in the generated .asm file (Note: this may be for simplicity on MS's part, since it can treat templates the same as regular functions in the generated .obj file, though realistically there's no actual need to store them in the .obj file, as user17732522 points out in the comments).
During linking, MSVC determines that those functions are in fact not actually used / needed anywhere else, and thus can be eliminated (even if they were used elsewhere, since the result can be determined at compile time, they'd still be eliminated) from the compiled executable.
In order to see what's in the final compiled executable, you can view the executable through a disassembler. Example for using MSVC to do this, is put a breakpoint in the main function, run it, then when the breakpoint is hit, right click and "View Disassembly". In this, you will see that the two functions don't exist anymore.
You can also generate the Mapfile using /MAP option, which also shows it does not exist.
If I am reading the documentation correctly, it seems as those MS chose to include explicit instantiations of templates classes and functions because it "is useful" when creating libraries. Uninstantiated templates are not put into the obj files though.
|
71,720,217 | 71,720,265 | Why can vectors be instantiated like arrays? | I was learning about classes in my C++ class, and I was trying to understand some of the things about common classes I've used. One of which being vector. I looked through the vector reference on Cplusplus.com, but there was one thing that I couldn't quite understand and was having trouble finding answers to it online. When making a new vector with predetermined values it's possible to do as follows:
vector<int> vect = {1,2,3,4,5};
cout<< vect.at(2);
What's confusing to me is that I have no idea how this works, and how to possibly replicate this in a class of my own. I've looked through the constructors of the vector class but didn't see anything that seemed to relate to instantiation in this manner. Something like vector<int> vect(6) makes sense to me because it's just creating a vector with default size 6, but the way I mentioned above is very different from what I've seen and learned thus far.
So my questions are: How can a vector be instantiated this way, and what might a constructor for this look like?
| This uses an std::initializer_list. Just like "string" forms a string, {element1, element2, ...} forms an initializer list that can be converted to a vector, or another datatype.
For example, we could construct an array manually doing the following:
int w[4];
auto x = {1, 2, 3, 4}; //type is std::initializer_list
int count = 0;
for(auto i : x){
w[count] = i;
count++;
}
|
71,720,245 | 71,727,011 | PubSubClient.publish tries convert char into unsinged int and throws error | First of all, I am a far cry from a being an experienced programmer, so please forgive me if I am asking beginners question here.
I encountered a problem trying to publish a payload using the PubSubClient on an ESP8266. I am using VS Code with Platformio.
During Build I receive the following error. It seems like the PubSubClient is trying to convert the payload from char to unsinged int, even though the payload is defined as const char in the API of the PubSubClient library.
src\main.cpp: In function 'void sendStatusViaMqtt(String)': src\main.cpp:389:39: error: invalid conversion from 'char*' to 'const uint8_t*' {aka 'const unsigned char*'} [-fpermissive] 389 | mqttClient->publish(relay_Status, mqttMessageCharArray, msglength, false); | ^~~~~~~~~~~~~~~~~~~~ | | | char* In file included from src\main.cpp:15: .pio\libdeps\esp12e\PubSubClient\src/PubSubClient.h:154:55: note: initializing argument 2 of 'boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int, boolean)' 154 | boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
This is the code snipped I used. Actually I went out of my way to convert a string into a char needed per PubSubClient documentation.
void sendStatusViaMqtt()
{
unsigned long now = millis();
if (now - lastMqttMsg > 100000) //Making sure I only send messages after a certain time has elapsed
{
String mqttMessage = generateStatusString(); //Function generateStatusString()puts putting current values of variables of the running code on the ESP8266 into a String and returns it
unsigned int msglength = mqttMessage.length();
char mqttMessageCharArray[mqttMessage.length()];
mqttMessage.toCharArray(mqttMessageCharArray, mqttMessage.length()); //Generating a CHAR Array out of the String
lastMqttMsg = now;
Serial.print("Publish message: ");
Serial.println(mqttMessage);
mqttClient->publish(relay_Status, mqttMessageCharArray, msglength, false);
}
}
I am thankful for any hint!
| Your mqttMessageCharArray is of type char[] (which decays to char* on passing to function), whereas your mqttClient->publish() takes a uint8_t* as its second argument.
It can simply be fixed by replacing the last line with :-
mqttClient->publish(relay_Status, (uint8_t*)&mqttMessageCharArray, msglength, false);
Here we take adress of mqttMessageCharArray using the & and then cast it to a uint8_t*.
uint8_t (aka. unsigned 8bit integer) is basically same as unsigned char on virtually every system. Both of them are by definition 1 byte in size so its safe to cast between them without any data loss.
|
71,721,417 | 71,723,954 | How to set correct directory path in add_subdirectory function? | Using Android Studio and have two libraries, Lib(A) and Lib(B), there are two CMakeList.txt for each project.
I want to know how can I set add_subdirectory in Lib(A) because in run mode can not detect function in Lib(B), I guess the compiler/Gradle ignores CMakelist of Lib(B).
libraries structure:
A
|--src
|--main
|--JAVA
|--CPP
|-CMakelist.txt
|-...CPP
and
B
|--src
|--main
|--JAVA
|--CPP
|-CMakelist.txt
|-...CPP
Lib(A) CMakelist:
cmake_minimum_required(VERSION 3.18.1)
project("A")
add_subdirectory("src/main/cpp/")
add_library(A
SHARED
a.cpp)
find_library(log-lib
log )
target_link_libraries(Services
${log-lib} )
Lib(B) CMakelist:
cmake_minimum_required(VERSION 3.18.1)
project("B")
add_library(B
SHARED
b.cpp)
find_library(log-lib
log )
I tested:
add_subdirectory("src/main/cpp/")
and
add_subdirectory("com.myapp.B/src/main/cpp/")
but doesn't work, the error is:
CMake Error at CMakeLists.txt:3 (add_subdirectory):
add_subdirectory given source "src/main/cpp/" which is not an existing
directory.
| The first parameter of add_subdirectory takes the path to the directory containing the CMakeLists.txt file to include. If this path is relative, it's resolved relative to the directory containing the CMakeLists.txt currently being parsed.
If you specify an absolute path or a relative path navigating to a parent directory, you need to specify the build directory to use as second argument.
add_subdirectory(../../../../B/src/main/CPP B_build)
|
71,722,140 | 71,722,154 | C++, operator [], and tracking a change | I'm trying to build a little array-ish class, like so:
class dumb
{
bool mChanged=false;
int mData[1000];
int& operator [](int i) {return mData[i];}
};
Here's my question-- is there any kind of hack or trick I could do so that if I did this:
dumb aDumbStuff;
aDumbStuff[5]=25; <- now mChanged gets set to true!
So basically, I want my class's mChanged value to go true if I modify any content. Any way to do this without making the array itself an array of objects that they themselves track getting changed, or by doing memcmps to see if things changed at all?
Some complex dance of assignment operators that would let my class detect "[n]=" happening?
| You could set the flag to 'changed' inside your existing operator[] method, and add a second version with const returning an int (= not as a reference):
int operator [](int i) const {return mData[i];}
The compiler would pick the right one - modifying or not, as needed!
|
71,722,164 | 71,722,216 | Is it possible to use fold expression in class template deduction guide? | I did a simple test as follow:
#include <iostream>
template <typename T, std::size_t N, std::size_t D> struct MyArray {
template <typename First, typename ... Rest> MyArray(First, Rest...);
int dimension[N];
T m_array[D];
};
template <typename First, typename... Rest> MyArray(First first, Rest... values)
-> MyArray<First, 1 + sizeof...(values), (values * ...)>;
int main()
{
MyArray arr{3, 2, 3};
return 0;
}
The compiler complains about it:
main.cpp:14:13: No viable constructor or deduction guide for deduction of template arguments of 'MyArray'
main.cpp:4:50: candidate template ignored: couldn't infer template argument 'T'
main.cpp:9:45: candidate template ignored: substitution failure [with First = int, Rest = <int, int>]: non-type template argument is not a constant expression
main.cpp:3:60: candidate function template not viable: requires 1 argument, but 3 were provided
If I replace (values * ...) with 18 everything works as expected.
Is there any way to benefit from fold expressions in deduction guides in C++?
| You cannot use the values of function arguments inside constant expressions and here in particular not in a template argument.
If you want to deduce the type differently for different values, you need to make sure that the type also differs from value to value.
Example:
#include<type_traits>
template<auto V>
constexpr auto constant = std::integral_constant<decltype(V), V>{};
//...
MyArray arr{3, constant<2>, constant<3>};
As far as I can tell this should work with your deduction guide as is, although both GCC and MSVC seem to have problems with this code, which look like bugs to me.
std::integral_constant is implicitly convertible to the value in its template argument. This conversion doesn't require accessing the value of a given instant of the type, so (values * ...) should be fine.
sizeof...(values) is always fine, since it doesn't access values at all. It just expands to the number of items in the pack.
GCC claims (values * ...) doesn't contain an unexpanded pack, which seems wrong to me. MSVC has an internal compiler error, which is definitively a bug. But Clang accepts the variation.
|
71,722,452 | 71,724,140 | C++ Using upper_bound instead of find () | I need advice on how to modify the program so that I can search using the upper/lower_bound function. The program works correctly(ok asserts) for the find () function.
I sort the company database after each insertion or deletion, so that's probably not the problem
In the link I enclose the whole program for a better understanding.
https://onecompiler.com/cpp/3xxyvx8vw
bool Company::operator == (Company cmpx) const
{
return ( ( (strcasecmp(addr.c_str(), cmpx.addr.c_str()) == 0)
&& (strcasecmp(name.c_str(), cmpx.name.c_str()) == 0) )
|| (id == cmpx.id)
);
}
bool Company::operator < (Company cmpx) const
{
return id < cmpx.id;
}
bool CVATRegister::cancelCompany ( const string &taxID )
{
Company cmp("", "", taxID);
//auto itr = upper_bound(DCompany.begin(), DCompany.end(), cmp); THIS NOT WORK
auto itr = find(DCompany.begin(), DCompany.end(), cmp);
if(itr != DCompany.end())
{
DCompany.erase(itr);
sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b)
{
return a.getId() < b.getId();
});
return true;
}
return false;
}
| If DCompany is sorted with respect to Company::operator< (i.e. with respect to the company tax ID), then you can do:
bool CVATRegister::cancelCompany ( const string &taxID )
{
Company const cmp("", "", taxID);
auto const itr = lower_bound(DCompany.begin(), DCompany.end(), cmp);
if(itr != DCompany.end() && itr->getId() == taxId)
{
DCompany.erase(itr);
// 1. No need to pass a lamda to sort your container again,
// since your Company::operator< will be called.
// 2. No need to sort again your container after removing an
// element: it will already be sorted.
//sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b)
//{
// return a.getId() < b.getId();
//});
return true;
}
return false;
}
|
71,722,565 | 71,722,841 | create number pattern into a string vector | new to programming so I apologize if this has been answered before...I have tried searching with almost zero luck.
I am trying to create a number pattern like 1,2,2,3,3,3,4,4,4,4 etc;
I have gotten to that point but I need to put it into a string vector so that if the user inputs 5, the string vector elements are 1,2,2,3,3,3,4,4,4,4,5,5,5,5,5
void print_vectorStr(vector<string> &vec, string sep = "")
{
cout << "\nThe vector string elements are: ";
for (auto elem : vec)
{
cout << elem << sep;
}
cout << endl;
}
void print_vector(vector<int> &vec, string sep = "")
{
cout << "\nThe vector integer elements are: ";
for (auto elem : vec)
{
cout << elem << sep;
}
cout << endl;
}
int main()
{
int n;
cout << "insert n \n";
cin >> n;
vector<int> vec(n);
vector<string> vecString;
for (int i = 1; i <= vec.size(); i++)
{
for (int j = 1; j <= i; j++)
{
cout << i << " ";
}
}
print_vector(vec, " ");
print_vectorStr(vecString, " ");
return 0;
}
| If you really need a vector of strings, and need to reproduce the output in a comma-separated pattern, you can do something simple like:
#include <iostream>
#include <vector>
#include <string>
int main () {
size_t n = 0; /* unsigned variable for n */
std::vector<std::string> pattern{}; /* vector of strings */
std::cout << "enter n: ";
if (!(std::cin >> n)) { /* validate EVERY user-input */
std::cerr << "error: invalid input.\n";
return 1;
}
for (size_t i = 0; i <= n; i++) { /* loop n times from 1 */
for (size_t j = 0; j < i; j++) { /* loop i times */
pattern.push_back(std::to_string(i)); /* add i i's to string */
}
}
/* loop over each string in pattern with index to control ',' output */
for (size_t i = 0; i < pattern.size(); i++) {
if (i) { /* if not first string */
std::cout.put(','); /* output ',' */
}
std::cout << pattern[i]; /* output string */
}
std::cout.put('\n'); /* tidy up with newline */
}
Note above you must validate EVERY user-input. Otherwise, what would happen if the user slipped and tapped 't' instead of 5? Also note, to control the ',' separator for output, you can either keep a counter and use a range-based for loop, or, since you need a counter anyway, just use a normal conditioned for loop.
Example Use/Output
$ ./bin/num_pattern
enter n: 2
1,2,2
$ ./bin/num_pattern
enter n: 5
1,2,2,3,3,3,4,4,4,4,5,5,5,5,5
or
$ ./bin/num_pattern
enter n: t
error: invalid input.
Look things over and let me know if you have further questions.
|
71,723,099 | 71,725,647 | What is the macOS alternative to namespaces(7) in Linux or jails in FreeBSD? | When I was using Linux I used to use Linux namespaces:
https://man7.org/linux/man-pages/man7/namespaces.7.html
Also on FreeBSD, there are jails:
https://www.freebsd.org/cgi/man.cgi?jail
I was wondering what the alternative was on macOS 12? I'm new to Macs so I'm just trying to learn the system and any features it might have.
| The equivalent feature to FreeBSD's jails and linux namespaces for macOS is the App Sandbox.
You can find relevant details in the App Sandbox Design Guide.
|
71,723,586 | 71,746,927 | Insert indices to pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> in PCL Library | I'm trying to partitioning & perform some actions to a point cloud using pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> octree.
In the method, it provides a public function called
setInputCloud(const PointCloudConstPtr &cloud_arg, IndicesConstPtr &indices_arg = IndicesConstPtr ())
In the doc, the explanation is used as below.
*\brief Provide a pointer to the input data set.
* \param[in] cloud_arg the const boost shared pointer to a PointCloud message
* \param[in] indices_arg the point indices subset that is to be used from \a cloud - if 0 the whole point cloud is used
Further,
// public typedefs
typedef boost::shared_ptr<const std::vector<int> > IndicesConstPtr;
typedef pcl::PointCloud<PointT> PointCloud;
typedef boost::shared_ptr<const PointCloud> PointCloudConstPtr;
What I have already done is,
pcl::PointCloud<pcl::PointXYZ>::Ptr inputCloud (new pcl::PointCloud<pcl::PointXYZ> ());
pcl::PointIndices::Ptr cloudIndices(new pcl::PointIndices());
pcl::PointIndices::Ptr selectedIndices(new pcl::PointIndices());
/* some code to fill inputCloud and cloudIndices & selectedIndices
(selectedIndices is contains only chosen indices set from all cloudIndices) */
float resolution = 0.1;
pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> octree(resolution);
octree.setInputCloud(inputCloud);
octree.addPointsFromInputCloud();
This works fine. But I need, without creating a new point cloud with selectedIndices, to use the existing inputCloud and use selectedIndices to the function.
I know octree.setInputCloud(inputCloud, selectedIndices); function is not working. It returns
error: cannot convert ‘pcl::PointIndices::Ptr’ {aka ‘std::shared_ptr<pcl::PointIndices>’} to ‘const IndicesConstPtr&’ {aka ‘const std::shared_ptr<const std::vector<int> >&’}
169 | octree.setInputCloud (inputCloud,selectedIndices);
| ^~~~~~~~~~~~~~~~~~~~~~
| |
| pcl::PointIndices::Ptr {aka std::shared_ptr<pcl::PointIndices>}
Do I need to convert std::shared_ptr<pcl::PointIndices>const to std::shared_ptr<const std::vector<int> >&? How can I do this?
| Found the solution to the above question.
PCL Function
setInputCloud(const PointCloudConstPtr &cloud_arg, IndicesConstPtr &indices_arg = IndicesConstPtr ())
accepts indices but you have to convert it to the pcl::IndicesPtr type.
So, My solution was to,
pcl::IndicesPtr indicesTemp(new std::vector<int>());
std::copy(selectedIndices->indices.begin(), selectedIndices->indices.end(), std::back_inserter(*indicesTemp));
float resolution = 0.1;
pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> octree(resolution);
octree.setInputCloud(inputCloud,indicesTemp);
octree.addPointsFromInputCloud();
and results were as expected.
|
71,723,659 | 71,733,621 | how to run a membber function with QtConcurrrent Qt6? type 'decay_t cannot be used prior to '::' because it has no members) | i'm trying to run a member function but but i got an error , help me please
i tried with this line of code
QFuture<qlonglong> future = QtConcurrent::run(this,&backD::analysa);
and analysa() is a methode that returns a qlonglong
| Try QtConcurrent::run([this]{ return analysa(); }); or QtConcurrent::run([this] -> qlonglong { return analysa(); });, whichever compiles in your case.
|
71,724,023 | 71,724,052 | C++ Error checking before constructor delegation | I have a constructor that creates a matrix from size_t dimensions, I want to add support for int dimensions. However, before passing the ints to the size_t constructor I would like to make sure that they are positive.
Matrix(vector<double> vals, int rows, int cols )
\\throw something if rows<= 0 || cols<= 0
:Matrix(vals,static_cast<size_t>(rows), static_cast<size_t>(cols))
Is something like this possible?
| Pass them through a function,
int enforce_positive(int x)
{
if (x <= 0) {
throw something;
}
return x;
}
Matrix(vector<double> vals, int rows, int cols )
: Matrix(vals,
static_cast<size_t>(enforce_positive(rows)),
static_cast<size_t>(enforce_positive(cols)))
You can make this a template, of course.
You could also use a "proof type" and make the condition explicit in the prototype. Something like
temolate<typename T>
class Positive
{
public:
explicit Positive(T x): val(x)
{
if (val <= 0) {
throw something;
}
}
operator T() const { return val; }
private:
T val;
};
Matrix(const vector<double>& vals,
Positive<int> rows,
Positive<int> cols )
: Matrix(vals,
static_cast<size_t>(rows),
static_cast<size_t>(cols))
//...
int x = ...;
int y = ...;
Matrix m(stuff, Positive(x), Positive(y));
|
71,724,261 | 71,725,495 | How detect and avoid multi-threading conflict in a loop with OpenMP compilation? | I am using an open-source simulation software that can be compiled with OpenMP-enabled cmake option. (https://github.com/oofem/oofem/)
In my class I am calling the following method in a for loop:
MaterialStatus *
Material :: giveStatus(GaussPoint *gp) const
/*
* returns material status in gp corresponding to specific material class
*/
{
MaterialStatus *status = static_cast< MaterialStatus * >( gp->giveMaterialStatus() );
if ( status == nullptr ) {
// create a new one
status = this->CreateStatus(gp);
// if newly created status is null
// dont include it. specific instance
// does not have status.
if ( status ) {
gp->setMaterialStatus( status );
}
}
return status;
}
(here is the link of code above in Github repository.)
As you can see in the giveStatus method if there is no status already assigned, it will create and assign one, but if you call gp->setMaterialStatus(gp) and already there is a status instance assigned to gp the code will stop with an error.
Now my problem is if I don't compile the code with OpenMP the code will work fine, but if I use OpenMP-enabled compilation the code will stop with the error that the status is already assigned.
I am not sure what is happening, I think two objects try to get status from the same gp and since no status is assigned, the threads cannot obtain the *status pointer, and all of them try to set the status multiple times.
How can I obtain more information on this problem while debugging and how can I resolve this problem?
| giveStatus is clearly not thread-safe. Thus, calling it from multiple threads in parallel cause a race-condition. Indeed, some threads can concurrently check if status is null and can enter the conditional in parallel. Then status is set by multiple thread causing an undefined behavior (typically an outcome that is dependent of the order of the execution of the threads). Because this code is not designed to be thread-safe, the simplest option is to put critical sections so to protect the code (ie. one thread will execute the section at a time and so the functions). This can be done using the directive #pragma omp critical. If you want the execution to be deterministic, it is probably better to use a #pragma omp master so to force the same unique thread to execute a code and then share its result to others using synchronizations (eg. barrier, atomic, critical sections, etc.).
Alternatively you can rewrite the code so to be thread-safe. To do so, you generally need not to use (hidden) state machines and favour thread-local storage. OOP code tends not to be great for that since a primary goal of OOP code is to abstract a state machine (through encapsulation).
|
71,724,404 | 71,724,502 | template deduction of member functions | I'm trying to understand template argument deduction with regular functions, pointer to regular functions, member functions and pointer to member functions. Can someone explain why the last line yields a compile error while there is no issue with standalone?
#include <iostream>
#include <type_traits>
struct A {
int fun(float, char) const&;
};
void standalone(int, char) {}
template <typename T>
void what(T &&) {
std::cout << __PRETTY_FUNCTION__ << "\n";
}
int main()
{
what(standalone); // void what(T&&) [with T = void (&)(int, char)]
what(decltype(&standalone){}); // void what(T&&) [with T = void (*)(int, char)]
what(decltype(&A::fun){}); // void what(T&&) [with T = int (A::*)(float, char) const &]
what(A::fun); // main.cpp: In function 'int main()':
// main.cpp:30:13: error: invalid use of non-static member function 'int A::fun(float, char) const &'
| // what(A::fun);
| ^~~
}
| The problem is that we cannot pass a reference to a member because from Pointers to members:
The type “pointer to member” is distinct from the type “pointer”, that is,
a pointer to member is declared only by the pointer to member declarator syntax, and never by the pointer
declarator syntax. There is no “reference-to-member” type in C++.
This means that we must explicitly use the address of operator in the call expression to pass a pointer to member instead(since reference to member is not allowed), as shown below:
//-------v---------> must explicitly use address of operator
what(&A::fun);
Side note
Although irrelevant in your case, note that unlike ordinary function pointers, there is no automatic conversion between a member function and a pointer to that member. That is, in case of member functions and in contexts where a pointer is expected(allowed) the expressions A::fun and &A::fun are not equivalent.
|
71,724,511 | 71,724,540 | How to use read syscall with an integer fd in C++ | I am working with sockets. On creating one using socket(), we get an integer file descriptor. I then want to read data from this fd.
To do so, I was following functioning C code - using the read() syscall, in the following line:
read (sockfd /* int */, buff /* char* */, 50);
However, compiling gives the error "read was not declared in this scope; did you mean 'fread'?".
On simply compiling the given functioning C client code as a C++ file with g++, I get the same errors.
The includes in this C++ program are (in-order): iostream, netdb.h, netinet/in.h, stdio.h, stdlib.h, string.h, sys/socket.h, sys/types.h
And the std namespace is in use.
What am I doing wrong?
| You might be missing #include <unistd.h>
But I also recommend using recv, which is declared in sys/socket.h
If you're stuck, always try manpages: man read.2
|
71,724,709 | 71,725,060 | How to get all process in task manager with Microsoft API using C++ in win 64bit | I have a block code below.
I want to get all processes in tasks manager with C++ but it not work.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <psapi.h>
void PrintProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModulesEx( hProcess, &hMod, sizeof(hMod),
&cbNeeded, LIST_MODULES_ALL) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
_tprintf( TEXT("%s (PID: %u)\n"), szProcessName, processID );
CloseHandle( hProcess );
}
int main( void )
{
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
{
return 1;
}
cProcesses = cbNeeded / sizeof(DWORD);
for ( i = 0; i < cProcesses; i++ )
{
if( aProcesses[i] != 0 )
{
PrintProcessNameAndID( aProcesses[i] );
}
}
return 0;
}
I want to get all processes in task manager but it return error like this images.
How to solve it, thanks for any answer.
I try to get all processes in task manager.
| You should try to link with Psapi.lib.
Your errors are linker errors. The linker is creating the final exe, after the compiler compiled the source files to object files.
When you use functions like EnumProcessModulesEx from from <psapi.h>, you need to link with their implementation.
It is recommended to read the documentation for API you are using.
For example: EnumProcessModulesEx.
|
71,725,753 | 71,727,587 | Truly Lock-free MPMC Ring Buffer? Threads able to assist each other to avoid blocking? | This question is inspired by Lock-free Progress Guarantees. The code shown is not strictly lock-free. Whenever a writer thread is suspended when the queue is not empty or not full, the reader threads returned false, preventing the whole data structure from making progress.
What should be the correct behavior for a truly lock-free ring buffer?
Generally, truly lock-free algorithms involve a phase where a pre-empted thread actually tries to ASSIST the other thread in completing an operation.
Any reference to this technique? How could it be implemented for an array-based MPMC queue?
I looked at some codes, and they have similar problems.
craflin's version uses two internal atomics for recording read and write.
https://codereview.stackexchange.com/questions/263157/c-lock-free-mpmc-ring-buffer-in-c20 uses busy-waiting, not lock-free.
| As a good example of how cross-thread assist often ends up working in real life, consider that a lock-free MPMC queue can be obtained by changing the liblfds algorithm along these lines:
Use 3 counters:
alloc_pos: the total number of push operations that have been started. This is incremented atomically when a push starts.
write_pos: all write operations at lower positions are known to be complete.
read_pos: all items written at lower positions are known to have been consumed.
In this scheme, a push or pop operation is completed by a CAS in the affected slot. The write_pos and read_pos variables are redundant.
So to push, a thread first increments alloc_pos, and then increments write_pos past all the slots in front of it that it can see are complete. This is an assist -- it is completing previous writes that were started in other threads. Then the thread has to scan the slots between write_pos and alloc_pos until it finds a free one and manages to reserve it with a CAS.
To pop, the reader first increments read_pos past all the items written at lower positions that it can see are consumed. Again this is an assist -- completing previous reads. Then it scans from read_pos to alloc_pos to see if it can find an item that is finished being written.
As mentioned in comments, doing this for real gets annoying, with implementation decisions trading off performance against which ordering and availability guarantees you need, as well as jumping through hoops to prevent ABA problems.
|
71,726,052 | 71,726,332 | Can a base class and a derived class of that base class have a common friend class which is a friend of both the classes? | I know that a friend class can access the private elements of a class, so I was wondering weather a derived class can use a friend class to access the private members of the base class, if the friend class is friends with both the base class and the derived class?
I am a complete beginner in programming and I have just started learning OOP in C++; I just wanted to ask this question as it came to my mind when I learned of friend functions/classes.
| In C++,
In order to grant access to private or protected members of a class, we should define a friend class or a function (or a method of another class).
Friendship is not inherited.
So in order to access private or protected members of a base class and derived class, from another class you should define the "another" class as friend of both base class and it s derived class.
For the
"....can a derived class use a friend class to access the private members of the base class if the friend class is friends with both the base class and the derived class?...." question.
Friendship is not mutual. If a class Y is a friend of Y, then Y doesn’t become a friend of X automatically.
So derived class can not access private members of base class using friend of base class.
There can be a way to access private members of a base class B from derived class D by using friend class F.
B should define F as a friend. (F can access private and protected members of B)
F should define D as a friend.(D can access private and protected members of F)
F should define methods to access and/modify all private members of B.
F should define an attribute in type B and set this attribute as a parameter in constructor or in a method.
D should define an attribute in type F and set itself to this attribute using the method or construtor defined in 4.
At the end D can access all private members of B via the attribute in type F.
|
71,726,178 | 71,726,422 | Why the code snippet gets stuck when optimization is enabled? | There are three question about the code snippet below.
When the macro(i.e. NO_STUCK_WITH_OPTIMIZATION ) is not enabled, why this code snippet gets stuck when the optimization is enabled(i.e. -O1, -O2 or -O3) whereas the program works well if the optimization is not enabled?
And why the program no longer get stuck if std::this_thread::sleep_for() is added?
UPDATED:
3. If the is_run is declared as volatile(for details, see the code snippet), then the program would never get stuck on X86?
^^UPDATED ENDS^^
#include <functional>
#include <thread>
#include <iostream>
#include <chrono>
#include <atomic>
#ifdef NO_STUCK_WITH_OPTIMIZATION
using TYPE = std::atomic<int>;
#else
using TYPE = int; //The progrom gets stuck if the optimization is enabled.
#endif
int main()
{
TYPE is_run{1};
auto thread = std::thread([&is_run](){while(1==is_run){
//std::this_thread::sleep_for(std::chrono::milliseconds(10)); //If this line is added, the program is no longer gets stuck. Why?
}
std::cout << "thread game over" << std::endl;
});
std::this_thread::sleep_for(std::chrono::seconds(1));
is_run = 0;
thread.join();
}
| You have a multi-threaded program. One thread does is_run = 0;.
The other thread does while(1==is_run). Although you guarantee, with a sleep (matter for another question), that the write is done before the read, you need to tell the compiler to synchronize this variable.
In C++, the simple way to make sure one thread sees the change is to use atomic<int>. If you don't do this, the other thread might never see the change. This hiding of the change might be due to local optimization of the code at compile time, by the OS deciding not to refresh some memory page or by the hardware itself deciding the memory doesn't need to be reloaded.
Putting the atomic variable guarantees all those systems know what you want to do. So, use it. :-)
Lifting from the comments:
https://en.cppreference.com/w/cpp/language/memory_model#Threads_and_data_races
A program that has two conflicting evaluations has a data race unless both evaluations execute on the same thread or in the same signal handler, or
both conflicting evaluations are atomic operations (see std::atomic), or one of the conflicting evaluations happens-before another (see std::memory_order) If a data race occurs, the behavior of the program is undefined.
|
71,726,679 | 71,726,809 | Count square numbers in array using count function | I need to count how many numbers are perfect squares in array of integer values, using a function from the algorithm library.
I have chosen the std::count() function to do that:
#include <algorithm>
#include <iostream>
#include <math.h>
bool is_square_number(int x) {
if (x >= 0) {
long long sr = sqrt(x);
return (sr * sr == x);
}
return false;
}
int count_square_numbers(int *arr, int *arr2) {
int number = 0;
while (arr < arr2) {
if (is_square_number(*arr))
number++;
arr++;
}
return number;
}
int main() {
int n=9,arr[9]={1,2,3,4,5,6,7,8,9};
std::cout << count_square_numbers(arr, arr + n);
std::cout<<std::count(arr,arr+n,count_square_numbers);
return 0;
}
When I use std::cout << count_square_numbers(arr, arr + n), the program prints 3 as result (correctly); but, when I try to use it in the function, std::count, I cannot compile my code.
Could you explain what is the problem here and how could I use the std::count function for this?
Error I get:
ISO C++ forbids comparison between pointer and integer [-fpermissive]
| First, you are confusing the std::count function – which just counts how many values in the container/range are equal to the last parameter (which is a value, not a function)1 – with the std::count_if function (which counts how many values satisfy the predicate, specified as the last parameter and should be a function or lambda taking an element from the range as an argument and returning a bool value).
Then, even when using std::count_if, you just pass it the actual test function (in your case, is_square_number, which fulfils the requirements for the unary predicate), rather than the full, loop-counter function:
#include <algorithm>
#include <iostream>
#include <math.h>
bool is_square_number(int x)
{
if (x >= 0) {
long long sr = sqrt(x);
return (sr * sr == x);
}
return false;
}
int count_square_numbers(int* arr, int* arr2)
{
int number = 0;
while (arr < arr2) {
if (is_square_number(*arr))
number++;
arr++;
}
return number;
}
int main()
{
int n = 9, arr[9] = { 1,2,3,4,5,6,7,8,9 };
std::cout << count_square_numbers(arr, arr + n) << "\n";
std::cout << std::count_if(arr, arr + n, is_square_number) << "\n";
return 0;
}
See: cppreference for fuller details.
1 When a function is passed as an argument to another function (as in your code), it is converted to a pointer to the function – hence the error message: The std::count function is attempting to compare values from the integer array with the function pointer.
|
71,726,692 | 71,726,738 | what do three dots(...) in c++ mean ? | for exmple:
msg is a class whith (operator <<)
msg << ... << args
[source code path][1]
what does three dots (...) imply? anyone know this, please tell me
[1]: https://github.com/Kistler-Group/sdbus-cpp/blob/5caea3b72bf783d88c3fa36eb8cf97cc10a71170/include/sdbus-c%2B%2B/Message.h#L295
| This is a template parameter pack (variadic template)
If you search for variadic template c++ you will find many questions on here related to it.
There is also en.cppreference.com.
https://en.cppreference.com/w/cpp/language/variadic_arguments
https://en.cppreference.com/w/cpp/language/parameter_pack
|
71,726,899 | 71,727,038 | How to make that equal values in array will be written inside brackets? | I'm new at C++ and I'm trying to solve this problem. Here is the code.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int my_rand_arr(int a, int b);
void random_arr(int arr[], int n);
void output_arr(int arr[], int n);
int main(){
srand(time(0));
const int N = 20;
int arr[N];
random_arr(arr, N);
output_arr(arr, N);
return 0;
}
int my_rand_arr(int a, int b){
return rand() % (b - a + 1) + a;
}
void random_arr(int arr[], int n){
for(int i = 0; i < n; i++){
arr[i] = my_rand_arr(1, 6);
}
}
void output_arr(int arr[], int n){
for(int i = 0; i < n; i++){
if(arr[i] == arr[i + 1]){
cout << "(";
}
cout << arr[i] << " ";
}
cout << endl;
}
It is random array and the thing I'm trying to achieve is that if there is a couple of equal adjacent numbers, those numbers will be written inside brackets.
Expected output:
1 6 3 (1 1) 6 2 (4 4 4) 3 6 1 5 6 5 2 1 (5 5)
What should I do in order to achieve that output?
| Just count the number of repetitons of each element and print the elements when reaching the a different element or the end of the array.
void output_arr(int arr[], size_t const n) {
auto pos = arr;
auto const end = arr + n;
while (pos != end)
{
size_t count = 1;
auto const element = *pos;
for (++pos; pos != end && *pos == element; ++pos, ++count)
{
}
if (count == 1)
{
std::cout << element << ' ';
}
else
{
std::cout << '(' << element;
for (; count != 1; --count)
{
std::cout << ' ' << element;
}
std::cout << ") ";
}
}
std::cout << '\n';
}
int main() {
int arr[] = { 1, 6, 3, 1, 1, 6, 2, 4, 4, 4, 3, 6, 1, 5, 6, 5, 2, 1, 5, 5 };
output_arr(arr, sizeof(arr) / sizeof(*arr));
}
|
71,727,455 | 71,727,518 | Simplify C++ inclusion with macros | Considering a C++ project with an include folder inside which the source code of several repositories is placed, how could I simplify their inclusion in the main file?
I tried something like this:
// config.h
#define SOMEPROJ_SRC_PATH "include/someproj/src/"
#define EXPAND_PATH(root, filepath) #root #filepath
//main.cpp
#include EXPAND_PATH(SOMEPROJ_SRC_PATH, "folder/header.h")
But it seems to not work properly.
So, what should I modify in these directives to make them work properly?
| The right way to do it is to pass SOMEPROJ_SRC_PATH as a search path of include files with -I option.
main.cpp:
#include <iostream>
#include "some.h"
int main() {
std::cout << HELLO << std::endl;
}
/some/path/some.h:
#define HELLO "Hello, world!"
And then compile it:
g++ -I /some/path -o main main.cpp
|
71,727,501 | 71,727,679 | c++ fetching web page using wininet | I'm trying to download a web page using WinInet. I've used the code given here: http://www.cplusplus.com/forum/windows/109799/
It mostly works, but there seems to be some encoding issue that I have no idea how to fix.
For instance, this line (using www.stackoverflow.com as an example page):
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Shared/stacks.css?v=48511da708b8">
Is returned as this line:
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Shared/stacks.css?cks.css?ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌðA6÷v=48511da708b8">
(for the sake of not spamming, I've actually removed most of the special characters)
| In this code:
while(InternetReadFile(OpenAddress, DataReceived, 4096, &NumberOfBytesRead) && NumberOfBytesRead )
{
cout << DataReceived;
}
DataReceived is receiving arbitrary bytes. It is not a null-terminated string, but the code is passing it to the operator<< overload that expects a null-terminated string. So the printing is exceeding the end of the received data, printing bytes from surrounding memory, until a random 0x00 byte is encountered.
Use the istream::write() method instead, so that you can tell it exactly how many characters to print:
cout.write(DataReceived, NumberOfBytesRead);
|
71,727,530 | 71,806,716 | How to find indexes of elements in recursive-knapsack? | I'm trying to implement recursive Knapsack which would return 2 things:
Max value we get by filling knapsack.
Indexes of the elements considered for filling the knapsack.
Please note that I don't want to use Dynamic Programming Approach to get this done (by reverse iterating the 2-D matrix to get the indexes of elements). I want to understand how it can be done in recursive knapsack approach?
This is what I have tried below (getting correct MaxValue (op#1) BUT not getting correct list of indexes (op#2)):
int knapsack(vector<int> wt, vector<int> val, int W, int N, vector<int>& idx)
{
if (W == 0 || N == 0) return 0;
if (wt[N - 1] <= W)
{
int consider = val[N - 1] + knapsack(wt, val, W - wt[N - 1], N - 1, idx);
int dontconsider = knapsack(wt, val, W, N - 1, idx);
if (consider > dontconsider)
{
idx.push_back(N-1);
}
return max(consider, dontconsider);
}
else
{
return knapsack(wt, val, W, N - 1, idx);
}
}
int main()
{
vector<int> wt = { 10, 20, 30 };
vector<int> val = { 60, 100, 120 };
int W = 50;
vector<int> idx; // this should retain the indexes of the elements considered for knapsack.
cout << knapsack(wt, val, W, wt.size(), idx);
cout << "\nIndex of elements considered for knapsack: ";
for (int i = 0; i < idx.size(); i++)
cout << idx[i] << " ";
getchar();
return 0;
}
Expected output should be:
220
Index of elements considered for knapsack: 1 2
Please help me. Thank you.
| The vector idx is passed by reference: vector<int>& idx.
The issue is that here:
int consider = val[N - 1] + knapsack(wt, val, W - wt[N - 1], N - 1, idx);
int dontconsider = knapsack(wt, val, W, N - 1, idx);
This vector idx is modified twice.
One solution is to create a temporary vector for the first call...
#include <iostream>
#include <vector>
#include <algorithm>
int knapsack(const std::vector<int>& wt, const std::vector<int>& val, int W, int N, std::vector<int>& idx) {
if (W == 0 || N == 0) return 0;
if (wt[N - 1] <= W) {
std::vector<int> idx0;
int consider = val[N - 1] + knapsack(wt, val, W - wt[N - 1], N - 1, idx0);
int dontconsider = knapsack(wt, val, W, N - 1, idx);
if (consider > dontconsider) {
idx = idx0;
idx.push_back(N-1);
return consider;
}
return dontconsider;
}
else {
return knapsack(wt, val, W, N - 1, idx);
}
}
int main()
{
std::vector<int> wt = { 10, 20, 30 };
std::vector<int> val = { 60, 100, 120 };
int W = 50;
std::vector<int> idx; // this should retain the indexes of the elements considered for knapsack.
std::cout << knapsack(wt, val, W, wt.size(), idx);
std::
cout << "\nIndex of elements considered for knapsack: ";
for (int i = 0; i < idx.size(); i++)
std::cout << idx[i] << " ";
std::cout << "\n";
//getchar();
return 0;
}
|
71,728,040 | 71,728,102 | Error C2011, Tried everything already asked on here | i am new to Cpp and am having this error:
Error C2011 'point2d': 'struct' type redefinition
it is the first time i use modules, and i am having an error with the headers. Here is my code:
squarecell.cc:
#include <vector>
#include "squarecell.h"
using namespace std;
struct point2d {
point2d(int x, int y) {
X = x;
Y = y;
}
point2d() {
X = 0;
Y = 0;
}
int X;
int Y;
};
squarecell.h:
#pragma once
#include <iostream>
#include <vector>
using namespace std;
struct point2d {
point2d(int x, int y);
point2d();
int X;
int Y;
};
I tried this in the header:
#pragma once
#include <iostream>
#include <vector>
using namespace std;
#ifndef point2d_HEADER
#define point2d_HEADER
struct point2d {
point2d(int x, int y);
point2d();
int X;
int Y;
};
#endif
Also didnt work, I searched everywhere, i know im doing something wrong but i cant figure it out.
Any help would be much appreciated,
Karl
| The issue is in the source file, not the header.
Implementations are done like this:
point2d::point2d(int x, int y) { ... }
Not like this:
struct point2d {
point2d(int x, int y) { ... }
};
|
71,728,124 | 71,728,169 | C++ Error (Segmentation fault / Bus error / Memory limit exceeded / Stack limit exceeded) when using functions lower_bound, sort, | My program crashes after uploading to the school test server with the announcement that one of these errors has occurred (Segmentation fault / Bus error / Memory limit exceeded / Stack limit exceeded), I have no exact information. If I run the program in the debugger, I can't find anything. The audit method may fail.
The whole program https://onecompiler.com/cpp/3xy2j7dmd
class Company
{
private:
string name;
string addr;
string id;
unsigned int totalIncome;
unsigned int numberOrders;
unsigned int amount;
};
bool Company::cmpNA (const Company &a, const Company &b)
{
if ( a.getName() < b.getName())
return a.getName() < b.getName();
return a.getAddr() < b.getAddr();
}
bool CVATRegister::audit ( const string &name, const string &addr, unsigned int &sumIncome ) const
{
Company cmp(name, addr,"-1");
vector<Company> tmp = DCompany;
sort(tmp.begin(), tmp.end(), [](const Company & a, const Company & b)
{
if ( a.getName() < b.getName())
return a.getName() < b.getName();
return a.getAddr() < b.getAddr();
});
auto itr = lower_bound(tmp.begin(), tmp.end(), cmp, &Company::cmpNA);
if(itr != tmp.end() && addr == itr->getAddr() && itr->getName() == name)
{
sumIncome = itr->getTotalIncome();
return true;
}
return false;
}
| That sort lambda doesn't provide strict weak ordering as required by std::sort. Both sort and lower_bound can/will fail.
Did you mean?
sort(tmp.begin(), tmp.end(), [](const Company & a, const Company & b)
{
if ( a.getName() != b.getName())
return a.getName() < b.getName();
return a.getAddr() < b.getAddr();
});
|
71,728,125 | 73,003,610 | Getting Arduino IDE to compile for C++14 | I've been looking to modify the build flags under Arduino's IDE 1.x, or even the Arduino CLI (which I haven't used but am willing to adopt) such that I can undefine -std=gnu++11 and instead define -std=gnu++14
I found a question related to this which gives me almost what I need:
Arduino 1.0.6: How to change compiler flag?
But it only shows how to add flags, not to remove them. I found another related post about changing arduino to GNU C++17 but the answer was it's not possible.
In this case, I know it's possible, as I do it in Platform IO in order to use the htcw_gfx library. It works great on most platforms that will run GFX reasonably anyway.
But I just don't know how to fiddle with Arduino to get it to dance the way I need to.
Any help would be greatly appreciated.
| You can modify the default compile flags in the hardware/arduino/avr/platform.txt file.
$ grep -n "std" hardware/arduino/avr/platform.txt
23:compiler.c.flags=-c -g -Os {compiler.warning_flags} -std=gnu11 -ffunction-sections -fdata-sections -MMD -flto -fno-fat-lto-objects
28:compiler.cpp.flags=-c -g -Os {compiler.warning_flags} -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto
For some linux systems the following would work to automatically do this:
dirname $(realpath $(which arduino)) | xargs -I{} sed -i "s/\(std=gnu++1\)1/\14/" {}/hardware/arduino/avr/platform.txt
But this is not very portable, and will not work if the user has installed Arduino with Snap (as snap has these files mounted RO).
Sources:
https://stackoverflow.com/a/28047811/6946577
https://stackoverflow.com/a/55254754/6946577
|
71,728,218 | 71,728,324 | Why is C++ copy constructor called twice? | I have some code that returns a class object by value and the copy constructor is being called more than I thought it would. This seems to be how the g++ compiler does things but I'm not sure why. Say I have this code:
#include <memory>
#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "constructor" << endl; }
A(const A& other) { cout << "copy constructor" << endl; }
~A() { cout << "destructor" << endl; }
};
A f()
{
return A();
}
int main()
{
cout << "before f()\n";
A a = f();
cout << "after f()\n";
return 0;
}
When compiled with constructor elision turned off
g++ test.cpp -fno-elide-constructors
it outputs this:
before f()
constructor
copy constructor
destructor
copy constructor
destructor
after f()
destructor
So the copy constructor is called twice. I can see why the copy constructor would be called when copying the return value of f() into the variable a but why again?
I've read about C++ compilers returning temporary objects from functions but I don't understand the point of that. Even with elision turned off it seems unnecessary to create a temporary object for every function return value.
Update
Just to be super clear here, I'm not surprised that the copy constructor is being called. I expect that since I turned off elision. What I'm confused about is why the copy constructor needs to be called twice. It seems like once should be enough to copy the result from f() into a.
| Pre-C++17
In Pre-C++17 standard there was non-mandatory copy elison, so by using the -fno-elide-constructors flag you are disabling the return value optimization and some other optimizations where copies are elided.
This is what is happening in your program:
First due to the return statement return A(); an object is constructed using the default constructor A::A().
Next, a copy of that default constructed object is returned to the caller. This is done using the copy constructor A::A(const A&). Hence you get the first copy constructor call output.
Finally, due to the statement A a = f(); which is copy initialization, the object named a is created as a copy of that returned value using the copy constructor A::A(const A&). Hence you get the second copy constructor call output.
//--v----------------------->1st copy constructor called due to this(return by value)
A f()
{
//-------------vvv---------->default constructor called due to this
return A();
}
//--vvvvvvvvv--------------->2nd copy constructor called due to this(copy initialization)
A a = f();
C++17
In C++17(and onwards), due to mandatory copy elison, you will not get any copy constructor call output. Demo.
|
71,728,323 | 71,728,967 | How do you access the menus given a QMenuBar? | In Qt how do you recover the menus given a populated QMenuBar?
They do not seem to be the menu bar's children. For example, after the following (where the menu creation functions succeed and do what you expect)
menuBar()->addMenu(create_file_menu(this));
menuBar()->addMenu(create_view_menu(this));
auto children = menuBar()->children();
auto first_child = children[0];
children ends up with a size of 1 and that one child, first_child, is some object of type QMenuBarExtension. I was expecting to get two children with the first being the file menu.
I'm using Qt6 if that matters.
| A QMenu is added to a QMenuBar internaly via QWidget::addAction(menu->menuAction()) (see <QtInstallPath/src\widgets\widgets\qmenubar.cpp>.
From QWidget you can retrieve the added QActions via QWidget::actions() - method which returns a list of associated QActions. In your specific example menuBar()->actions() should retrieve at least two actions for your menus.
However, there seems to be no way to get from a QMenu::menuAction() - created QAction back to the associated menu. Therefore you may need to store a pointer to your created QMenu - objects on your own.
|
71,728,842 | 71,729,048 | Problem on std::sort with QObject and QVector<MyQObject*> | I have a problem with sort of QVector<MyQObject*>. This is in real case of use for listing directorys and datas (like ls unix command). Here in this example "/Users/Stephane/" on my unix mac os computer.
The std::sort function doesn't work, I'm sure I have done a mistake.
Here are my files of Console Qt:
entry.h
#ifndef ENTRY_H
#define ENTRY_H
#include <QObject>
#include <QString>
#include <QDateTime>
enum Type {
File, Directory, Other
};
class Entry : public QObject
{
Q_OBJECT
public:
explicit Entry(QObject *parent = nullptr);
void setValue(Type type, QString name, int size_file);
QString getName();
int getSize();
bool operator<(const Entry other);
signals:
private:
QString name;
Type type;
int size_file;
};
#endif // ENTRY_H
entry.cpp
#include "entry.h"
Entry::Entry(QObject *parent)
: QObject{parent}
{
}
void Entry::setValue(Type type, QString name, int size_file)
{
this->type = type;
this->name = name;
this->size_file = size_file;
}
QString Entry::getName()
{
return this->name;
}
int Entry::getSize() {
return this->size_file;
}
bool Entry::operator<(const Entry other) {
return this->name < other.name;
}
main.cpp
#include <QCoreApplication>
#include "entry.h"
#include <sys/stat.h>
#include <dirent.h>
#include <QDebug>
#include <iostream>
#include <QDateTime>
struct EntryCompare {
bool operator()(const Entry *a, const Entry *b) {
return(a < b);
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// My vector
QVector<Entry*> vec_entry;
QString directory = "/Users/Stephane/";
// Read dir/file
struct dirent *lecture;
DIR *dir;
struct stat buf;
QString currentPath;
dir = opendir(directory.toLocal8Bit());
if (dir == NULL) {
qCritical() << directory << " don't exist";
return a.exec();
}
while ((lecture = readdir(dir)) != NULL) {
if (strcmp(lecture->d_name, ".") != 0) {
currentPath = directory + lecture->d_name;
const char *charCurrentPath = currentPath.toLocal8Bit();
if ((stat(charCurrentPath, &buf)) == -1) {
qCritical() << "stat" << currentPath;
}
int size = buf.st_size;
Entry *entry = new Entry();
if (!strcmp(lecture->d_name, "..")) {
entry->setValue(Type::Directory, lecture->d_name, 0);
vec_entry.append(entry);
} else {
vec_entry.append(entry);
if (S_ISDIR(buf.st_mode)) {
QString qstringTemp = lecture->d_name;
qstringTemp += "/";
entry->setValue(Type::Directory, qstringTemp, 0);
} else {
entry->setValue(Type::File, lecture->d_name, size);
}
}
}
}
closedir(dir);
// This part doesn't work
std::sort(vec_entry.begin(), vec_entry.end(), EntryCompare());
foreach(Entry *v, vec_entry) {
qInfo() << "Vector entry:" << v << "Name:" << v->getName() << "Size:" << v->getSize();
}
return a.exec();
}
| When you pass a pointer to any function, it's your responsibility to dereference the pointer and get from it the information it points to. That is not automatic -- you have to write the code to do it.
As to std::sort "not working", it is working exactly as you've written. Your comparison spec is comparing the value of two pointers. You're responsible for providing std::sort
The proper range to sort, plus
The proper sorting criteria that sorts two values, plus
The sorting criteria follows a "strict-weak-ordering" (no ambiguities as to which item is placed before another item).
If you do that, std::sort works all the time. If the results are wrong, you must have violated one or more of those prerequisites. Your code violates number 2).
In all likelihood, you meant to do the following:
struct EntryCompare
{
bool operator()(Entry *a, Entry *b) const
{
return(a->getName() < b->getName());
}
};
This compares the names that a and b point to.
|
71,729,018 | 71,729,681 | How can I get icon of Windows app in CPP? | I'm trying to build an File Manager with in Win32, and I have a problem with the icons. Whenever I trying to get icon that an windows 10 app is associated with it like .png (Photos app), the icon is blank paper. What I'm doing wrong? Thanks in advance and please answer :)
BOOL InitTreeViewImageLists(HWND hwndTV) {
HIMAGELIST himl; // handle to image list
HBITMAP hbmp; // handle to bitmap
// Create the image list.
if ((himl = ImageList_Create(16,
16,
ILC_COLOR16 | ILC_MASK,
3, 0)) == NULL)
return FALSE;
// Add the open file, closed file, and document bitmaps.
HICON hIcon;
SHFILEINFO sfi;
LPCWSTR path = L"C:\\Users\\Shalev\\Desktop\\WhatsApp.lnk";
sfi = GetShellInfo(path);
HICON* iconHandles = new HICON;
hIcon = sfi.hIcon;
cout << hIcon << endl;
g_nOpen = sfi.iIcon;
ImageList_AddIcon(himl, hIcon);
sfi = GetShellInfo(L"C:\\");
hIcon = sfi.hIcon;
g_nClosed = sfi.iIcon;
ImageList_AddIcon(himl, hIcon);
sfi = GetShellInfo(L"C:\\");
hIcon = sfi.hIcon;
g_nDocument = sfi.iIcon;
ImageList_AddIcon(himl, hIcon);
// Associate the image list with the tree-view control.
TreeView_SetImageList(hwndTV, himl, TVSIL_NORMAL);
return TRUE;
}
SHFILEINFO GetShellInfo(LPCWSTR path) {
SHFILEINFO sfi;
SecureZeroMemory(&sfi, sizeof(sfi));
SHGetFileInfo(path, 0, &sfi, sizeof(sfi), SHGFI_SYSICONINDEX | SHGFI_SHELLICONSIZE | SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES);
return sfi;
}
| You can use the IShellItemImageFactory interface, something like this:
...
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); // need this somewhere when your thread begins, not for every call
...
IShellItemImageFactory* factory;
if (SUCCEEDED(SHCreateItemFromParsingName(path, nullptr, IID_PPV_ARGS(&factory))))
{
// the GetImage method defines a required size and multiple flags
// with which you can specify you want the icon only or the thumbnail, etc.
HBITMAP bmp;
if (SUCCEEDED(factory->GetImage(SIZE{ 256, 256 }, SIIGBF_ICONONLY, &bmp)))
{
... // do something with the HBITMAP
DeleteObject(bmp);
}
factory->Release();
}
...
CoUninitialize(); // call this each time you successfully called CoInitializeEx
|
71,729,019 | 71,729,127 | Apparently you can modify const values w/o UB. Or can you? | ---- Begin Edit ----
User @user17732522 pointed out the flaw that invokes UB is from the fact pop_back() invalidates the references used according to the vector library documentation. And constexpr evaluation is not required to detect this when it occurs as it's not part of the C++ core.
However, the fix, which was also pointed out by @user17732522, is simple. Replace occurrences of these two consecutive lines of code:
v.pop_back();
v.emplace_back(...);
with these two lines:
std::destroy_at(&v[0]); // optional since A has a trivial destructor
std::construct_at<A, int>(&v[0], ...);
---- Begin Original ----
While references are invalidated upon the destroy_at, they are reified automatically by the construct_at. See: https://eel.is/c++draft/basic#life-8,
It's well established you can't modify const values unless they were originally non const. But there appears an exception. Vectors containing objects with const members.
Here's how:
#include <vector>
#include <iostream>
struct A {
constexpr A(int arg) : i{ arg } {}
const int i;
};
int main()
{
std::vector<A> v;
v.emplace_back(1); // vector of one A initialized to i:1
A& a = v[0];
// prints: 1 1
std::cout << v[0].i << " " << a.i << '\n';
//v.resize(0); // ending the lifetime of A and but now using the same storage
v.pop_back();
v.emplace_back(2); // vector of one A initialized to i:2
// prints: 2 2
std::cout << v[0].i << " " << a.i << '\n';
}
Now this seems to violate the general rule that you can't change the const values. But using a consteval to force the compiler to flag UB, we can see that it is not UB
consteval int foo()
{
std::vector<A> v;
v.emplace_back(1); // vector of one A initialized to i:1
A& a = v[0];
v.pop_back();
v.emplace_back(2);
return a.i;
}
// verification the technique doesn't produce UB
constexpr int c = foo();
So either this is an example of modifying a const member inside a vector w/o UB or the UB detection using consteval is flawed. Which is it or am I missing something else?
| It is UB to modify a const object.
However it is generally not UB to place a new object into storage previously occupied by a const object. That is UB only if the storage was previously occupied by a const complete object (a member subobject is not a complete object) and also doesn't apply to dynamic storage, which a std::vector will likely use to store elements.
std::vector is specified to allow creating new objects in it after removing previous ones, no matter the type, so it must implement in some way that works in any case.
What you are doing has undefined behavior for a different reason. You are taking a reference to the vector element at v[0]; and then you pop that element from the vector. std::vector's specification says that this invalidates the reference. Consequently, reading from the reference afterwards with a.i has undefined behavior. (But not via v[0]).
So your code has undefined behavior (since you are doing this in both examples).
However, it is unspecified whether UB in standard library clauses of the standard such as using the invalidated reference needs to be diagnosed in constant expression evaluation. Only core language undefined behavior needs to be diagnosed (and even then there are exceptions that obviously shouldn't be required to be diagnosed, since it is impossible, e.g. order-of-evaluation undefined behavior). Therefore the compiler does not need to give you an error for the UB here.
Also, consteval is not required here. constexpr would have done the same since you already force constant evaluation with constexpr on the variable.
|
71,729,038 | 71,744,046 | Cannot add color to character on multiple lines using Ncurses mvchgat | I'm trying to color a video game map in Ncurses using a loop to have a specific color for multiple characters, it works fine on a single line but whenever I try to apply color to multiple lines either it doesn't apply any color, or it only applies color on the last line.
Here's my code:
initscr();
start_color();
char *map = strdup("OOOOOOOOOXOOOOOOOOO\nBXXXOXXXOXOXXXXOXXB\nOXXXOXXXOXOXXXXOXXO\nOOOOOOOOOOOOOOOOOOO\nOXXXOXOXXXXXOXXOXXO\nOOOOOXOOOXOOOXXOOOO\nXXXXOXXXOXOXXXXOXXX\nXXXXOXOOOOOOOXXOXXX\nXXXXOXOMMMMMOXXOXXX\nXXXXOOOMMMMMOOOOXXX\nXXXXOXOMMMMMOXXOXXX\nXXXXOXOOOOOOOXXOXXX\nXXXXOXOXXXXXOXXOXXX\nOOOOOOOOOXOOOOOOOOO\nOXXXOXXXOXOXXXXOXXO\nBOOXOOOOOOOOOOOOXOB\nXXOXOXOXXXXXOXXOXOX\nOOOOOXOOOXOOOXXOOOO\nOXXXXXXXOXOXXXXXXXO\nOOOOOOOOOOOOOOOOOOO");
init_pair(1, COLOR_CYAN, COLOR_BLACK);
init_pair(2, COLOR_YELLOW, COLOR_BLACK);
init_pair(3, COLOR_RED, COLOR_BLACK);
int y = 0;
int x = 0;
while (true) {
mvprintw(0, 0, map);
for (int i = 0; y < 19; i++, x++) {
if (x == 19) {
y++;
x = 0;
}
if (map[i] == 'O') {
mvchgat(map[i], y, x, 1, A_BLINK, 2, NULL);
}
else if (map[i] == 'X') {
mvchgat(y, x, 1, A_BLINK, 1, NULL);
}
else if (map[i] == 'B'){
mvchgat(y, x, 1, A_BLINK, 3, NULL);
}
refresh();
}
| The \n in the string erases the next line(s), wiping out the video attributes.
mvprintw (and printw, etc), ultimately call waddch, which documents the behavior:
Newline does a clrtoeol, then moves the cursor to the window left
margin on the next line, scrolling the window if on the last line.
|
71,729,213 | 71,729,311 | C++ Search using lower_bound in the vector and ignore lowercase / uppercase letters | How can I find an element in a vector if I don't care about case. For example, if I have in cmp name = "tOM" addr = "LONDON" and I want it to find an element with values name = "Tom" addr = "London" that I have saved in vector? I enclose the whole program https://onecompiler.com/cpp/3xy2j7dmd .
bool Company::cmpNA2 (const Company &a, const Company &b)
{
if ( (strcasecmp(a.getName().c_str(), b.getName().c_str()) != 0) )
return ( strcasecmp(a.getName().c_str(), b.getName().c_str()) );
return ( strcasecmp(a.getAddr().c_str(), b.getAddr().c_str()));
}
bool CVATRegister::invoice ( const string &name, const string &addr, unsigned int amount )
{
Company cmp(name, addr,"-1");
sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b)
{
if ( (strcasecmp(a.getName().c_str(), b.getName().c_str()) != 0) )
return ( strcasecmp(a.getName().c_str(), b.getName().c_str()) );
return ( strcasecmp(a.getAddr().c_str(), b.getAddr().c_str()));
});
auto itr = lower_bound(DCompany.begin(), DCompany.end(), cmp, &Company::cmpNA2);
// cout << itr->getTotalIncome() << itr->getId() << endl; <--- Nothing
| The first thing is that std::sort requires you to return true or false. The issue is that strcasecmp returns an int denoting whether the first item comes before, is equal, or after the second item (-1, 0, 1). That's three values, not just true or false.
To simplify your code, you could do something similar to this:
bool CVATRegister::invoice ( const string &name, const string &addr, unsigned int amount )
{
std::sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b)
{
return strcasecmp(a.getName().c_str(), b.getName().c_str()) < 0;
});
}
Since strcasecmp returns -1 if the first item is placed before the second item, then the predicate simply returns true if the result is < 0, and false otherwise.
|
71,730,891 | 71,731,004 | How to Unreal Engine C++ CustomStruct RemoveAt or Remove UE4 | #1 or #2
The function is not working but It works fine with inEditor Blueprint
(Write operator==)
.h
TArray<FStruct> StructArray
.cpp
void Func(FStruct struct_2)
{
const uint32 Index = SturctArray.Find(struct_2); // Always Value = 0
if(StructArray[Index] == struct_2)
{
StructArray.RemoveAt(struct_2) // #1
StructArray.Remove(Index) // #2
}
}
| Calling Func will create a copy of the FStruct object passed in. StructArray will never contain the copy that was made for function Func. To make that work, have Func use something that does not create a copy. Like a reference.
Don't use the result of TArray.Find() before checking if it is valid.
TArray.RemoveAt() expects an index, your code supplies it an object.
TArray.Remove() expects on item of the same type used to declare the TArray, your code supplies it an index.
#1
void Func(FStruct& struct_2)
{
const uint32 Index = StructArray.Find(struct_2);
if (Index != INDEX_NONE)
{
StructArray.RemoveAt(Index); // #1
}
}
#2
void Func(FStruct& struct_2)
{
StructArray.Remove(struct_2); // #2
}
|
71,731,641 | 71,732,431 | how to make console automatically zoom to full screen when running (In C++) | I want to make a game by coding on Visual Studio. When I run code, the console will appear but it's small. And I need to press maximize to make it full screen.
After I google about window.h, I use this code:
void ConsoleSize(SHORT width, SHORT height)
{
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
SMALL_RECT WindowSize;
WindowSize.Top = 0;
WindowSize.Left = 0;
WindowSize.Right = width;
WindowSize.Bottom = height;
SetConsoleWindowInfo(hStdout, 1, &WindowSize);
}
But it only makes the console bigger, not automatically full screen.
So please help me.
Thanks.
I'm not good at English so my question will have some grammatical errors. Sometimes it doesn't do what I want but I sincerely thank you all.
| I have written two functions, maxsc() and fullsc() are two different full screen, you could use these two functions separately to see if it can meet your needs.
#include<iostream>
#include<Windows.h>
using namespace std;
void maxsc()
{
HWND Hwnd = GetForegroundWindow();
ShowWindow(Hwnd, SW_MAXIMIZE);
}
void fullsc()
{
HWND Hwnd = GetForegroundWindow();
int x = GetSystemMetrics(SM_CXSCREEN);
int y = GetSystemMetrics(SM_CYSCREEN);
LONG winstyle = GetWindowLong(Hwnd, GWL_STYLE);
SetWindowLong(Hwnd, GWL_STYLE, (winstyle | WS_POPUP | WS_MAXIMIZE) & ~WS_CAPTION & ~WS_THICKFRAME & ~WS_BORDER);
SetWindowPos(Hwnd,HWND_TOP,0,0,x,y,0);
}
int main()
{
//maxsc();
fullsc();
return 0;
}
|
71,731,703 | 71,731,829 | How do I erase the last star? |
I tried many things, but I fell into a swamp.
When you enter an odd number, one star in the last row pops out and you try to erase it, but it's hard...
#include<iostream>
using namespace std;
int main()
{
int num, star, line;
cout << "num ";
cin >> num;
for (line = 0; line < num/2+1; line++)
{
for (star = 0; star <= line; star++)
{
cout << "*";
}
for (star = num/2; star > line; star--)
{
cout << "x";
}
for (star = num/2-1; star > line; star--)
{
cout << "x";
}
for (star = 0; star <= line; star++)
{
cout << "*";
}
cout << endl;
}
}
| The problem is that the last line breaks the pattern.
This is what you get:
*xxx*
**x**
******
And from your description, I assume this is what you want:
*xxx*
**x**
*****
In all the lines before the last line, the number of x:s are odd, but in the last line, the number is even (zero). You first add three *, then zero x, then three * which makes 6 characters while the previous lines only had 5.
A direct approach at fixing it could be to count the output of *s and xs and at the end, print num minus the number printed so far *s. Example:
#include <iostream>
int main() {
int num, star, line;
if(!(std::cin >> num)) return 1; // error
num |= 1; // make sure the number is odd
for (line = 0; line < num / 2 + 1; line++) {
int output = 0; // count how many *'s and x's you've printed
for (star = 0; star <= line; star++) {
++output;
std::cout << '*';
}
for (star = num / 2; star > line; star--) {
++output;
std::cout << 'x';
}
for (star = num / 2 - 1; star > line; star--) {
++output;
std::cout << 'x';
}
// now print num - output asterisks:
for (star = 0; star < num - output; star++) {
std::cout << '*';
}
std::cout << '\n';
}
}
|
71,733,342 | 71,733,548 | How do I deallocate the dynamic memory correctly in this C++ program? I get a segmentation fault (core dump) when I execute the program | How do I deallocate the dynamic memory correctly in this simple C++ program? I get a segmentation fault (core dump) when I execute the program. I am trying to find out where I went wrong. Thanks in advance.
I am trying to add dynamically allocated objects to an array and am trying to get the destructor to clear the memory. I am unsure if I have created the destructor correctly in carList.
#include <iostream>
#define MAX 3
class Car{
public:
Car(std::string name){
this->name = name;
}
~Car(){
}
std::string getName(){
return this->name;
}
private:
std::string name;
};
class carList{
public:
carList(){
this->length = 0;
}
~carList(){
//the deconstructer; I am unsure If I have implemented it correctly
for (int i = 0; i < this->length; i++)
{
if(listCar[i] != nullptr){
delete[] listCar[i];
}
}
}
int getLength(){
return this->length;
}
// adding to the end of the list, unsure whether Implemented correctly
void addEndList(Car* car){ //???
if(this->length < MAX){
this->listCar[length+1] = car;
this->length++;
}
}
private:
Car* listCar[MAX];
int length;
};
int main(){
carList* carlist = new carList();
std::cout << carlist->getLength() <<std::endl;
Car* car2 = new Car("one");
Car* car3 = new Car("two");
carlist->addEndList(car2);
carlist->addEndList(car3);
std::cout << carlist->getLength() <<std::endl;
std::string name1 = car2->getName();
std::cout << name1 << std::endl;
delete carlist; // deleting the carlist, unsure if I need to delete car2,
//and car3 or if the destructor handles that, which I am
//trying to implement
return 0;
}
| Array indexes starts at 0 in C++. So,
this->listCar[length+1] = car;
should be
this->listCar[length] = car;
Otherwise you don't initialize index 0, but you delete it.
Second problem is with the delete. You should use delete for pointer returned by new and delete[] for new[]. You used new. So,
delete[] listCar[i];
should be
delete listCar[i];
After these 2 changes it looks okay: https://godbolt.org/z/84M1fq1fv
|
71,733,467 | 71,733,865 | C++ Multiple function parameters with varargs of a specific type | I am relatively new to C++ coming from a Java background so I am not sure if the functionality I am looking for is directly possible.
I am attempting to create a C++ function that accepts two different parameters but with the following requirements: The first parameter is a single input object of a specific type and the second parameter is a variable list of additional objects all of the which are the same type as the first parameter.
I am specifically looking for something similar to this Java code (if possible).
public static <E> boolean func(E input, E... args) {}
If this is not possible, does anyone know of some sort of implementation to make this to work for strings specifically?
Something along the lines of:
bool func(std::string input, std::string... args) {}
I have researched this topic a bit and found that function templates might be able to help here, but I am unsure on how to support multiple parameter types (of the same datatype) using this approach.
My initial line of thinking was to try something like this:
template<class... T>
bool func(const T input, const T&... args) {}
But this only accounts for the varargs parameter type, not the first parameter.
Any help/advice is greatly appreciated.
Thanks in advance.
| You need to define two templates types, one for the input and one for the parameter pack.
The function would then look like this:
template <typename T, typename ... Ts>
bool func(const T & input, const Ts & ... args);
To guarantee all the types are the same, we can combine std::conjunction with std::is_same.
We can also make use of static_assert so that we can generate an error at compile time if the condition is not satisfied.
It allows us to provide a custom error message so that the error would be clearer and easier for the user to understand.
It would then become:
template <typename T, typename ... Ts>
bool func(const T & input, const Ts & ... args)
{
static_assert(std::conjunction_v<std::is_same<T, Ts>...>, "Error: All parameters must be of the same type.");
//...
return true;
}
You could also use std::enable_if instead of static_assert.
I personally prefer to use static_assert because we can make the error more explicit. If we use std::enable_if, in case of failure, the user will still need to check on his/her own what was the evaluated condition to find out what was wrong.
In that case, the function would be like:
template <typename T, typename ... Ts>
std::enable_if_t<std::conjunction_v<std::is_same<T, Ts>...>, bool>
func(const T & input, const Ts & ... args)
{
//...
return true;
}
|
71,734,316 | 71,734,431 | List initialization (aka uniform initialization) and initializer_list? | Why does the following code give different output?
std::vector<int> v{12};
std::cout << v.size() << std::endl;
std::vector<int> v(12);
std::cout << v.size() << std::endl;
What if I list-initialize an object which has a ctor accepting an initializer_list as parameter?
And how can I call std::vector::vector(size_t) with list-initialization?
| List-initialization prefers constructors with a std::initializer_list argument. From cppreference:
The effects of list-initialization of an object of type T are:
[...cases that do not apply here ...]
Otherwise, the constructors of T are considered, in two phases:
All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have
default values, are examined, and matched by overload resolution
against a single argument of type std::initializer_list
If the previous stage does not produce a match, all constructors of T participate in overload resolution against the set of arguments
that consists of the elements of the braced-init-list, with the
restriction that only non-narrowing conversions are allowed. If this
stage produces an explicit constructor as the best match for a
copy-list-initialization, compilation fails (note, in simple
copy-initialization, explicit constructors are not considered at all).
While direct initialization does not prefer the initializer_list constructor. It calls the constructor that takes the size as argument.
And from https://en.cppreference.com/w/cpp/container/vector/vector:
Note that the presence of list-initializing constructor (10) means
list initialization and direct initialization do different things:
std::vector<int> b{3}; // creates a 1-element vector holding {3}
std::vector<int> a(3); // creates a 3-element vector holding {0, 0, 0}
std::vector<int> d{1, 2}; // creates a 2-element vector holding {1, 2}
std::vector<int> c(1, 2); // creates a 1-element vector holding {2}
And how can I call std::vector::vector(size_t) with list-initialization?
As explained above, the presence of the std::initializer_list constructor prevents you from calling the other constructor via list-initialization.
|
71,735,475 | 71,735,839 | How to properly implement operator<=> for a non-POD class? | I'm looking for a way to implement the three-way comparison operator and the operator== for the following class:
class Foo
{
public:
auto operator<=>( const Foo& rhs ) const noexcept = default;
private:
std::uint32_t m_Y;
std::uint32_t m_X;
char m_C;
std::vector<char> m_Vec;
};
But the default implementation is not what I intended. Therefore I need to write my own implementation.
What I want is:
I want the equality comparison (== and !=) to be based on comparing the members m_Y, m_X, and m_C of two operands (of type Foo). All of those three members must be equal to satisfy the equality. The equality of the content of m_Vec is not important (since it's not efficient to compare all those elements lexicographically).
I want the ordering comparison (< and >) to be based on comparing the expression m_Y * m_X.
I want the ordering comparison (<= and >=) to be based on comparing the expression m_Y * m_X and if both operands are equal in that regard, then all three members of both operands should be equal to satisfy the <= or >= (just like in ==).
Also with all this said, which comparison category type suits this scenario better, std::strong_ordering or std::weak_ordering?
How should I implement such logic? It seems simple and I read a whole recipe in a C++20 book on this topic and I still can't figure it out.
| I believe this is a partial order, which is an order where elements may be incomparable (none of <, >, or == hold between them). You should verify the necessary laws hold (a <= b iff a < b || a == b, a <= a for all a, a == b if a <= b && b <= a for all a, b, and a <= c if a <= b && b <= c for all a, b, c). If that is the case, use std::partial_ordering.
std::partial_ordering operator<=>(Foo const &other) const noexcept {
// compare your * expression first
std::partial_ordering ret = (this->m_Y * this->m_X) <=> (other.m_Y * other.m_X);
if(ret != 0) return ret;
// if that's not informative, compare the fields
return std::tie(this->m_Y, this->m_X, this->m_C) == std::tie(other.m_Y, other.m_X, other.m_C)
? std::partial_ordering::equivalent : std::partial_ordering::unordered;
}
|
71,735,690 | 71,735,823 | Find index of vector element using search_n function | I need to find index of vector element using a function from algorithm library.
EXAMPLE:
{1,2,3,4,5,6,7,8,9,10}
Element 5 found at 5 position.
#include <algorithm>
#include <iostream>
#include <vector>
bool comp(int a, int b) { return a < b; }
int main() {
int n = 10;
std::vector<int> a{10, 8, 5, 4, 1, 2, 3, 6, 7, 9};
sort(a.begin(), a.begin() + n, comp);
int number = 5;
std::vector<int>::iterator it;
it = std::search_n(a.begin(), a.begin() + n, number);
if (it != a.end())
std::cout << "found at position " << (it - a.begin()) << '\n';
else
std::cout << "match not found\n";
return 0;
}
I get error (in the 11th line):
no matching function for call to ‘search_n(std::vector::iterator, __gnu_cxx::__normal_iterator >, int&)’
Could you explain me what is the problem here?
| The std::search_n function looks for a sequence of a specified number of occurrences of a particular value in a range; that number is the third argument (count on this cppreference page).
So, if you insist on using std::search_n for this, you will need to add an extra argument (count, which will be 1) in your call:
it = std::search_n(a.begin(), a.begin() + n, 1, number);
However, using search_n is something of an overkill when looking for a single value; better to use the simpler (and faster) std::find function. Also, in place of a.begin() + n, you can use the easier and clearer a.end().
it = std::find(a.begin(), a.end(), number);
Also note that indexes and iterator positions in C++ start at zero, so, with the above fix(es) applied to your code, the answer will be "found at position 4"; if you want a 1-based position, then add 1 to the position; something like this:
auto position = std::distance(a.begin(), it) + 1;
|
71,736,101 | 71,737,418 | Why std::shared_ptr doesn't work with base template classes? | First let me show you the inheritance structure:
template <class Type>
class Base {
public:
Base() {}
virtual bool verify() const = 0;
};
class Derived : public Base<int> {
public:
Derived() : Base<int>::Base() {}
virtual bool verify() const override;
};
So, the base class for Derived is Base<int>.
I'm trying to define a template overload of the "|" operator:
template<class Type>
std::shared_ptr<Base<Type>> operator|(std::shared_ptr<Base<Type>> p1, std::shared_ptr<Base<Type>> p2)
{
return std::shared_ptr<Base<Type>>();
}
And, if I write something like:
std::shared_ptr<Derived> d;
std::shared_ptr<Base<int>> bInt;
auto result = d | bInt;
I'll get an error like:
C++ missing "|" operator corresponding to these operands:
std::shared_ptr<Derived> | std::shared_ptr<Base<int>>
But, if I explicitly specify the type of the base class when overloading, everything will work correctly:
std::shared_ptr<Base<int>> operator|(std::shared_ptr<Base<int>> p1, std::shared_ptr<Base<int>> p2)
{
return std::shared_ptr<Base<int>>();
}
How can I make the templated overload work?
| you have to either specify operator for a Derived class, or to save both of your variables in the pointer of Base:
std::shared_ptr<Base<int>> d = std::make_shared<Derived>();
std::shared_ptr<Base<int>> bInt;
auto res = d | bInt;
|
71,736,102 | 71,736,161 | How to use Class? (with poor English ability) | Code that implements Vectors as Class and inputs and outputs them as txt files.
I was temporarily implementing a function of Class, but I have a question because there is an error.
I tried to add vectorA and vectorB as Add functions in the main function and replace them with vectorO to printf.
However, in the Vector output part of the Add function, the error No default creator of the Vector class continues to appear. How should we solve this problem?
#include<stdio.h>
class Vector
{
public: // private?
double x, y, z;
public:
Vector(int x, int y, int z) {
x = x;
y = y;
z = z;
}
double Magnitude(void);
Vector Add(Vector v) {
Vector output;
output.x = x + v.x;
output.y = y + v.y;
output.z = z + v.z;
return output;
}
Vector Subract(Vector v);
double DotProduct(Vector v);
Vector CrossProduct(Vector v);
};
int main()
{
Vector vectorA(1, 2, 3);
Vector vectorB(4, 5, 6);
Vector vectorO = vectorA.Add(vectorB);
printf("(%d, %d, %d)\n", vectorO.x, vectorO.y, vectorO.z); // (5, 7, 9)
return 0;
}
Even if I put this code in the Vector class, I get a strange value.
Vector() {
x = x;
y = y;
z = z;
}
| This should fix your errors. have a basic and an overrided contructors, also be careful of the variable names they shouldn't be the same
#include<stdio.h>
class Vector
{
public: // private?
double x, y, z;
public:
Vector() {
x = 0;
y = 0;
z = 0;
}
Vector(int _x, int _y, int _z) {
x = _x;
y = _y;
z = _z;
}
double Magnitude(void);
Vector Add(Vector v) {
Vector output;
output.x = x + v.x;
output.y = y + v.y;
output.z = z + v.z;
return output;
}
Vector Subract(Vector v);
double DotProduct(Vector v);
Vector CrossProduct(Vector v);
};
int main()
{
Vector vectorA(1, 2, 3);
Vector vectorB(4, 5, 6);
Vector vectorO = vectorA.Add(vectorB);
printf("(%d, %d, %d)\n", vectorO.x, vectorO.y, vectorO.z); // (5, 7, 9)
return 0;
}
Read More Here
|
71,736,276 | 71,736,338 | Does std::terminate() trigger stack unwinding? | I've been trying to implement Exception class, and for program termination i've decided to use std::terminate(), but i'm not suse whether or not std::terminate() triggers stack unwinding process.
For example, if i compile and run this code:
struct Test {
Test() {
std::cout << "Constructed\n";
}
~Test() {
std::cout << "Destructed\n";
}
};
int main() {
Test t;
std::terminate();
return 0;
}
it will output this:
Constructed
terminate called without an active exception
and it seems that destructor is not being called.
| The standard handler for std::terminate() calls directly std::abort.
If you take a look here, you will find out that std::abort() did not call any of the destructors.
Destructors of variables with automatic, thread local (since C++11) and static storage durations are not called. Functions registered with std::atexit() and std::at_quick_exit (since C++11) are also not called. Whether open resources such as files are closed is implementation defined. An implementation defined status is returned to the host environment that indicates unsuccessful execution.
|
71,737,118 | 71,739,320 | What is a good technique for compile-time detection of mismatched preprocessor-definitions between library-code and user-code? | Motivating background info: I maintain a C++ library, and I spent way too much time this weekend tracking down a mysterious memory-corruption problem in an application that links to this library. The problem eventually turned out to be caused by the fact that the C++ library was built with a particular -DBLAH_BLAH compiler-flag, while the application's code was being compiled without that -DBLAH_BLAH flag, and that led to the library-code and the application-code interpreting the classes declared in the library's header-files differently in terms of data-layout. That is: sizeof(ThisOneParticularClass) would return a different value when invoked from a .cpp file in the application than it would when invoked from a .cpp file in the library.
So far, so unfortunate -- I have addressed the immediate problem by making sure that the library and application are both built using the same preprocessor-flags, and I also modified the library so that the presence or absence of the -DBLAH_BLAH flag won't affect the sizeof() its exported classes... but I feel like that wasn't really enough to address the more general problem of a library being compiled with different preprocessor-flags than the application that uses that library. Ideally I'd like to find a mechanism that would catch that sort of problem at compile-time, rather than allowing it to silently invoke undefined behavior at runtime. Is there a good technique for doing that? (All I can think of is to auto-generate a header file with #ifdef/#ifndef tests for the application code to #include, that would deliberately #error out if the necessary #defines aren't set, or perhaps would automatically-set the appropriate #defines right there... but that feels a lot like reinventing automake and similar, which seems like potentially opening a big can of worms)
| One way of implementing such a check is to provide definition/declaration pairs for global variables that change, according to whether or not particular macros/tokens are defined. Doing so will cause a linker error if a declaration in a header, when included by a client source, does not match that used when building the library.
As a brief illustration, consider the following section, to be added to the "MyLibrary.h" header file (included both when building the library and when using it):
#ifdef FOOFLAG
extern int fooflag;
static inline int foocheck = fooflag; // Forces a reference to the above external
#else
extern int nofooflag;
static inline int foocheck = nofooflag; // <ditto>
#endif
Then, in your library, add the following code, either in a separate ".cpp" module, or in an existing one:
#include "MyLibrary.h"
#ifdef FOOFLAG
int fooflag = 42;
#else
int nofooflag = 42;
#endif
This will (or should) ensure that all component source files for the executable are compiled using the same "state" for the FOOFLAG token. I haven't actually tested this when linking to an object library, but it works when building an EXE file from two separate sources: it will only build if both or neither have the -DFOOFLAG option; if one has but the other doesn't, then the linker fails with (in Visual Studio/MSVC):
error LNK2001: unresolved external symbol "int fooflag"
(?fooflag@@3HA)
The main problem with this is that the error message isn't especially helpful (to a third-party user of your library); that can be ameliorated (perhaps) by appropriate use of names for those check variables.1
An advantage is that the system is easily extensible: as many such check variables as required can be added (one for each critical macro token), and the same idea can also be used to check for actual values of said macros, with code like the following:
#if FOOFLAG == 1
int fooflag1 = 42;
#elif FOOFLAG == 2
int fooflag2 = 42;
#elif FOOFLAG == 3
int fooflag3 = 42;
#else
int fooflagX = 42;
#endif
1 For example, something along these lines (with suitable modifications in the header file):
#ifdef FOOFLAG
int CANT_DEFINE_FOOFLAG = 42;
#else
int MUST_DEFINE_FOOFLAG = 42;
#endif
Important Note: I have just tried this technique using the clang-cl compiler (in Visual Studio 2019) and the linker failed to catch a mismatch, because it is completely optimizing away all references to the foocheck variable (and, thus, to the dependent fooflag). However, there is a fairly trivial workaround, using clang's __attribute__((used)) directive (which also works for the GCC C++ compiler). Here is the header section for the last code snippet shown, with that workaround added:
#if defined(__clang__) || defined(__GNUC__)
#define KEEPIT __attribute__((used))
// Equivalent directives may be available for other compilers ...
#else
#define KEEPIT
#endif
#ifdef FOOFLAG
extern int CANT_DEFINE_FOOFLAG;
KEEPIT static inline int foocheck = CANT_DEFINE_FOOFLAG; // Forces reference to above
#else
extern int MUST_DEFINE_FOOFLAG;
KEEPIT static inline int foocheck = MUST_DEFINE_FOOFLAG; // <ditto>
#endif
|
71,737,442 | 71,744,877 | Why don't types with invalid inheritance get rejected when passed as template parameters? | As we all know, classes can't be inherited from fundamental types and from classes that are marked as final. But despite that, the code presented below compiles without any problems on Clang 12 and GCC 9.
#include <type_traits>
template<typename T>
struct Inheriter : public T{};
int main()
{
std::void_t<Inheriter<int>>();
}
| There will only be an error due to the inheritance if the template specialization Inheriter<int> is instantiated.
Simply using the specialization, e.g. as a template argument, does not cause implicit instantiation. Roughly speaking implicit instantiation of the class template specialization happens only if it is used in a context that requires the class to be complete or otherwise depends on class completeness.
std::void_t is defined as
template<typename...>
using void_t = void;
There is nothing in this alias template that requires the template argument to be a complete type. As a consequence no implicit instantiation will happen.
The program is therefore well-formed and the compiler should not reject it.
|
71,737,631 | 71,738,051 | What is the design purpose of iterator_traits? | The C++ standard library has both iterator and iterator_traits templates defined. It seemed that in general, the iterator_traits just extracts properties that defined explicitly in iterator. If a iterator_traits is to be used, one can use the corresponding iterator directly. If a specialization of certain type (e.g. T*) is required, a specialization of iterator could match the requirement. What's the benefit this indirection?
|
It seemed that in general, the iterator_traits just extracts properties that defined explicitly in iterator. If a iterator_traits is to be used, one can use the corresponding iterator directly.
Not all iterators can type aliases as members.
What's the benefit this indirection?
To allow all iterators to have a uniform interface. More specifically, pointers are iterators too and as non-class types, pointers cannot have members.
So, when for example the user of an iterator wants the answer to the question "What is the type of the object pointed by an_iterator_type", they cannot use an_iterator_type::value_type because that cannot be defined for all iterators - specifically pointers. What they can use is std::iterator_traits<an_iterator_type>::value_type which can be defined for all iterators - including pointers. That is the purpose of std::iterator_traits.
The standard defines the std::iterator_traits<T*> specialisations for pointers. Although you can, you don't need to define specialisations for custom iterator types because you can instead define the types as members, which will be used by the generic definition of std::iterator_traits.
The intention of std::iterator was to be optionally used as a base class to help define the member types for custom iterators. However its use was never necessary, it is considered to be a flawed design and its use has long been discouraged. Since C++17, it has been deprecated and it may be removed from future standards.
An example that hopefully demonstrates the problem of the design of std::iterator:
// using the deprecated std::iterator
struct iterator : std::iterator<
std::input_iterator_tag, // OK so far
long, // can you guess what member this argument defines?
long, // how about this?
const long*, // you can probably guess this one
long> // still, no clue
{
...
// recommended way without using std::iterator
struct iterator
{
using iterator_category = std::input_iterator_tag;
using value_type = long;
using difference_type = long;
using pointer = const long*;
using reference = long;
...
|
71,737,656 | 71,738,009 | What are the use cases for a base class pointer pointing to a derived class object | I'm a new to OOP and trying to learn C++ and I came cross polymorphism and using the virtual keyword.
I just don't understand why we might need to do that.
I've checked this site for similar questions but none of them attempts to answer that why?
| The main goal is: Separation of concerns.
Let's take an example from my day job. I work on a codebase that does networking. The vast majority of the codebase depends on a class that looks like:
class Transport
{
public:
virtual bool SendMessage(int clientId, string message);
};
Imagine I've got hundred files, and tens of thousand of lines of code, using this class.
Now, my colleague in the low-level team wants to allow our code to use both UDP and TCP for communications. They can simply implement:
class UdpTransport:public Transport
{
public:
bool SendMessage(int clientId, string message) override { /* their code */};
};
class TcpTransport:public Transport
{
public:
bool SendMessage(int clientId, string message) override { /* their code */};
};
This allows me to keep the whole of my code unchanged (using only Transport* or Transport&) and not have to worry about what a UdpTransport or TcpTransport is. It allows one part of the code to work without knowing what another part of the code is doing.
|
71,737,757 | 71,737,883 | Doxygen multi line comments | I am new to Doxygen and trying to comment my code.
I have some issue with the comments: my multi line comments appear in a single line and I don't want to use \\n or <br>.
/**
Brief - this is a function
Get -
Return -
*/
void func1()
{
return
}
I want each line to start a new line.
However, the result is:
Brief - this is a function Get: - Return: - Post: -
I have tried also:
/// Brief - this is a function
/// Get -
/// Return -
void func1()
{
return
}
Same result as mentioned above.
| The doxygen comments in that case are meant to ignore the implicit new lines so the text wrapping doesn't affect the output like
/** This is a long comment that caused the
IDE to wrap the text and therefore
span onto multiple lines **/
int func(bool b) {
}
but in your example I think you should use appropriate commands if each line of your doxygen has a semantic meaning like parameters, return values, etc.
/**
\brief This is a description of my function
\param[in] b This is some bool argument of my function
\return This describes the int that is returned in this case
**/
int func(bool b) {
}
See the list of available commands here.
|
71,738,552 | 71,739,093 | C3520 parameter pack must be expanded - incorrect behaviour for 'variadic using' | While compiling the code below with Qt 5.12 using Microsoft Visual C++ Compiler 15.9.28307.1300 (amd64) and c++17 standard I get the following error:
error C3520: 'Args': parameter pack must be expanded in this context
note: see reference to class template instantiation
'Helper<Args...>' being compiled
template<typename T>
struct Base {
void operator()(const T& arg){}
};
template <typename... Args>
class Helper : Base<Args>... {
public:
using Base<Args>::operator()...;
};
Is this a bug with msvc? Is there any known workaround? The same code compiles on macOS using clang.
| As workaround to variadic using (C++17), you might use the recursive way:
template <typename... Args>
class Helper;
template <>
class Helper<>
{
};
template <typename T>
class Helper<T> : Base<T>
{
public:
using Base<T>::operator();
};
template <typename T, typename... Ts>
class Helper<T, Ts...> : Base<T>, Helper<Ts...>
{
public:
using Base<T>::operator();
using Helper<Ts...>::operator();
};
Demo
|
71,739,445 | 71,739,621 | Procedure entry point could not be located in exe | I have a exe that I built on Windows using mingw-gcc. It has several dependencies. All of them are located on the PATH. However, when I run it I get the following error.
The procedure entry point _ZNSt11logic_errorC2EOS could not be located in the dynamic link library <name_of_exe>
I have looked at similar questions and they suggested using __declspec(dllimport) but those questions the dynamic link library in question is actually a dll and not an exe. Do I need to trawl through my dependencies and add each one as a __declspec(dllimport) or something?
| Usually the entry point name is the name of a function or class method with some decoration. I think you are missing some dll or in the path you have some not updated version of the dll. The first thing to do is to search your project for anything like St11logic_error. This way you'll find the dll which is not updated then check the one on your exe path to be sure that it's the rigth one
|
71,739,626 | 71,739,676 | string subscript out of range in C++ for Cowculations | Please help with debugging.
It gives me an error 'string subscript out of range error' after the fifth input.
I was unable to figure out what to change.
Here is the code:
#include <iostream>
#include <string>
#define N 100
int str2int(std::string input)
{
int num = 0;
for (int i = 0; i < input.length(); i++)
{
if (input[i] == 'V')
num *= 4 + 0;
else if (input[i] == 'U')
num *= 4 + 1;
else if (input[i] == 'C')
num *= 4 + 2;
else if (input[i] == 'D')
num *= 4 + 3;
}
return num;
}
int main(void)
{
int tablet = 0, num1 = 0, num2 = 0, ans = 0;
std::string cowNum1 = "", cowNum2 = "", result = "";
std::string operation = "";
std::cin >> tablet;
std::cout << "COWCULATIONS OUTPUT" << std::endl;
while (tablet--)
{
std::cin >> cowNum1 >> cowNum2;
num1 = str2int(cowNum1);
num2= str2int(cowNum2);
for (int oprt = 0; oprt < 3; oprt++)
{
std::cin >> operation[oprt];
switch (operation[oprt])
{
case 'A':
{
num2 += num1;
break;
}
case 'R':
{
num2 >>= 2;
break;
}
case 'L':
{
num2 <<= 2;
break;
}
case 'N':
default:
break;
}
}
std::cin >> result;
ans = str2int(result);
if (num2 == ans)
std::cout << "YES" << std::endl;
else
std::cout << "NO" << std::endl;
std::cout << "END OF OUTPUT" << std::endl;
}
return 0;
}
Question is from 377 - Cowculations
Sample Input
5
VVVVU
VVVVU
A
A
A
VVVVVVUV
VVCCV
VVDCC
L
R
A
VVVVUCVC
VVCCV
VVDCC
R
L
A
VVVVUCVV
VVUUU
VVVVU
A
N
N
VVVVVUCU
DDDDD
VVVVU
A
L
L
UVVVVVVV
| You may not use the subscript operator for an empty string to change its value
std::cin >> operation[oprt];
At least you have to declare the object operation with the magic number 3 used in your for loop. For example
std::string operation( 3, '\0' );
Or
std::string operation;
operation.resize( 3 );
If you need to enter only one characters in a loop then an object of the type std::string is not required. You could just write
for (int oprt = 0; oprt < 3; oprt++)
{
char c;
std::cin >> c;
switch ( c )
{
case 'A':
{
num2 += num1;
break;
}
case 'R':
{
num2 >>= 2;
break;
}
case 'L':
{
num2 <<= 2;
break;
}
case 'N':
default:
break;
}
}
|
71,739,765 | 71,740,893 | Is there a way to create std::vector<arma::mat> from arma::mat matrices without creating a copy of the matrices? | I am new to C++. For a statistical method, I compute large matrices, e.g. A and B . They are n x n so for large sample sizes n, they become very large. If they are double and n = 70k , I think it might be on the order of 30GB?
Because the number of matrices needed can vary, I implemented the algorithm to use a vector of matrices and iterate over it for some operations. E.g.
arma::mat A;
arma::mat B;
std::vector<arma::mat> matrices;
matrices = {A, B};
Is there a way to create this std::vector without copying the matrices?
I tried to check whether the memory is the same by doing this:
logger->info("Memory address for A: {}.", (void *)&A);
logger->info("Memory address for matrices.at(0): {}.", (void *)&matrices.at(0));
And it showed different addresses so I assume it is creating a copy but I am not sure.
I tried to use
std::vector<arma::mat> matrices;
matrices.push_back(A);
The memory addresses differed still. With
std::vector<arma::mat> matrices;
matrices.push_back(std::move(A));
the algorithm no longer worked because the matrices were empty.
| You need to reverse the logic: Let the std::vector allocate the memory and create the matrices. Then you work directly with the elements in the vector. For example:
std::vector<arma::mat> matrices;
matrices.resize(2);
arma::mat & A = matrices[0];
arma::mat & B = matrices[1];
// Initializing the values of A and B, and do stuff with them.
Note: It is important to note here that the references to A and B will become invalid if you add more elements afterwards to the vector, i.e. if the vector grows. But since these matrices are so large, you want to avoid this anyway at all costs.
If the container needs to grow, you might want to take a look at e.g. std::list.
|
71,740,041 | 71,740,104 | Not calling the appropriate constructor | #include<iostream>
using namespace std;
class String
{
protected:
enum {SZ= 80};
char str[SZ];
public:
String (){str[0]='\0';}
String(char s[])
{
strcpy(str,s);
}
void display() const
{
cout<<str;
}
operator char*()
{
return str;
}
};
class Pstring : public String
{
public:
Pstring(char s[])
{
if(strlen(s)>SZ-1)
{
for(int j=0;j<SZ-1;j++)
{
str[j]=s[j];
}
str[SZ-1]='\0';
}
else
{String(s);}
}
};
int main()
{
Pstring s2 ="This is a strong string.";
cout<<"\ns2="; s2.display();
return 0;
}
s2.display() returns blank. Upon debugging it's is found that String(s) in Pstring calls the no-argument constructor in the String class. I understand it as a constructor with one argument and thus String(char s[]) should've been called. What is this behavior?
| This code snippet
else
{String(s);}
does not make a sense.
This line
String(s);
is a declaration of the variable s of the type String with the scope of the compound operator of the else part of the if statement.
Pay attention to that this constructor
Pstring(char s[])
calls implicitly the default constructor of the class String before the control will be passed to the body of the constructor. That is the body of the constructor gets the control only after all sub-objects of the created object of the derived class will be created.
You should place the check of the passed string in the constructor of the class String.
For example in the class String you could define the constructor with parameter the following way
String( const char s[] )
{
strncpy( str, s, SZ );
str[SZ - 1] = '\0';
}
And the constructor in the derived class could be defined like
Pstring( const char s[] ) : String( s )
{
}
|
71,740,186 | 71,740,356 | Loop for load multiples files (C++) | I´m trying to load all the files in a folder that have names from the form "file_i.csv".
For this I write the program:
void load_reel_set()
{
bool file_exists = true;
unsigned n_files = 0;
vector<unsigned> my_vector;
string line;
int i;
ifstream file("..\\file_" + to_string(n_files) + ".csv");
file_exists = file.good();
while (file_exists) {
//Load reel strips from file:
my_vector.clear();
getline(file, line, '\n');
save_line(my_vector, line);
all_my_vectors.push_back(my_vector);
file.close();
n_files++;
ifstream file("..\\file_" + to_string(n_files) + ".csv");
file_exists = file.good();
}
}
The function "save_line" turns character to unsigned place by place and saves that in a vector.
I have four files in the folder, each with only one line. This function recognizes all my files but, after the first one, the lines for the files are empty. The "all_my_vectors" vector has the expected value in the first loop but is 0 for the next ones.
| You have two independent instances ifstream file, the one inside the loop hiding the one outside. While the inner one runs out of scope after closing the loop the outer one remains at the end of the very first file.
Try instead:
file.open("the new path");
Side note: This file_exists variable is totally obsolete, you can simply check directly while(file.good()).
You actually can avoid a bit of duplicate code by:
// other variables...
for(unsigned int n_files = 0;; ++n_files)
{
std::ifstream file("path to next file");
if(!file)
{
break;
}
// now file content handling here
}
Note that now the std::ifstream is back inside the loop again, but there's now no outer instance hidden any more.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.