New to C++, having trouble understanding nuances of the language [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've been coding in swift and python for a while, but I've been wanting to learn C++ and have been doing these daily challenges. This challenge in specific requires you to take a string, and then split each letter into an element for an array. I can do that fairly easily, but the language seems to have gotten the better of me.
#include <string>
#include <vector>
std::vector<std::string> solution(const std::string &s)
{
return {}; // Your code here
}
I am super confused by that third line. I have no idea where I'm supposed to take the input from and what means what. If someone could break down that entire third line for me that would be hugely appreciated. Thank you a ton in advance.

The third line is std::vector<std::string> solution(const std::string &s). It declares a function in C++. The declaration has three parts: return type, function name and parameters name and type. So std::vector<std::string> is the return type, solution is the function name and (const std::string &s) is the paramer
list.
First of all, std is a namespace in C++. A namespace can isolate functions so even if two function signatures are the same, as long as they live in different namespaces they can be distinguished as two functions. To use something ins a namespace :: operator will help. std::vector is a container type in C++. It is a growable array, much like NSArray in swift. std::vector is actually a C++ template which adds generics to the language (but can do a lot more).<std::string> is the type parameter, which is used to tell the compiler what type of objects will be stored in the vector.
Then in the parameter list, const is the abbreviation for constant, which means you cannot modify the content of the parameter in the function. std::string denotes the type of the parameter. Unlike swift, C++ puts the type of a variable before it but not after it with a colon. and lastly &s is the name of the parameter. Here & means a reference. Since C++ passes values instead of references to the function by default, to reduce the runtime overhead in passing a large object many parameters will be denoted as to pass a reference to it.
These should be the basic knowledge to write a C++ program, so I recommend you to first read some books about C++ to learn more on this

It's a function that returns vector of strings and takes const reference to the string value. Take a look at lvalue and rvalue, what does const means and vector container (it takes template parameter).

Related

Specific C++ notation for function arguments? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
This is a simple question, but I couldn't find the answer through searching online. I was trying to work through some leetcode problems to better my understanding of C++. I was wondering if someone could walk me through the meaning behind the creation of this function.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
}
};
I understand that public is used so that we can access ____ outside the Solution class, but I am not sure what exactly... it also looks like we are initializing a vector of integers named "twoSum" with the arguments of a vector of numbers and a target value... I was wondering what the meaning of the & is... etc. I guess a simple question would be can someone translate this block of code so that I can write my own versions for various problems (it seems like this is a constant block (or variation of a similar block) of code that is common throughout these leetcode problems).
The shown code snippet, defines a member function named twoSum that has the return type of vector<int> and has 2 parameters. The first parameter named nums is an lvalue reference to a non-const vector<int> while the second parameter named target is an int.
I was wondering what the meaning of the & is
The & in the first parameter nums of the member function means that nums is an lvalue reference to a non-const vector<int>. Meaning, the argument that will be passed to the nums parameter, will be passed by reference instead of passed by value. That is, inside the member function twoSums, the nums refer to the original vector<int> that is passed as an argument.
Also note that there should be a return statement inside the member function since the return type of the member function is non-void.

Return a functor based on command line input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
From command line input I am receiving a single char of '=','<', or '>' followed by a value and my goal is to iterate through and modify my underlying data container using a custom functor (for example using remove_if). The simple but slow solution would be to have a single functor that is constructed using the input char and switching between the operators within it. However, this requires a check on the operator type every time the functor's operator is called. My first solution was using a switch statement on the char and creating a base functor class with 3 derived classes. However, I realized that while this was a completely viable and fast solution, I ended up having a large amount of code duplication of the switch statements. My attempt at a solution to this was using polymorphism and having a function that accepted the input char and returned a pointer of the base class which had a virtual () operator. However, when I passed the dereferenced base class pointer, it would not accept a pure virtual() operator and it was not overriden by the operators of the derived classes. In a sense, I want a function that returns a particular lambda or comparator assosciated with the value of an input char. What would be a good way of going about this?
Since lambdas have there own type i am not aware of a way to construct a function that returns different lambdas. You could store them in std:: function and pay for the overhead.
I think a combination of function ptr and map might be a good solution. Consider using a constexpr map (like in https://youtu.be/INn3xa4pMfg), create your functions and store the mapping in that map.
Note that you can also convert a non capturing lambda to a funtion ptr using ClosureType::operator ret(*)(params)() (See https://en.cppreference.com/w/cpp/language/lambda).

Is there any other advantage of lambdas besides convenience? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
The title might not be precise but I couldn't think of any brief one that would be. (Feel free to suggest one or edit my question.)
I was wondering if there is any other advantage of using lambda functions other than the fact that that one doesn't have to explicitly define (and write) the whole class definition of a functor or define a separate function to be used (possibly) just once. In other words, are lambdas introduced just for convenience or is there more to them?
Edit:
One thing to add to my question. Lambdas allow programmer to write less, do it more conveniently and therefore they are less error-prone. Which in itself is a different thing/reason than just convenience but is associated with it.
See full motivation for lamdas at A proposal to add lambda functions to the C++ standard
:
C++ Standard Library algorithms would be much more pleasant to use if C++ had support for lambdas. Lambda functions would let people use C++ Standard Library algorithms in many cases where currently it is easier to write a for loop. Many developers do not use function objects simply because of the syntactic overhead.
Lambdas are largely syntactic sugar, but not entirely. One point about lambdas is that they capture arrays by direct-initialization in subscript order [expr.prim.lambda]:
22 - [...] (For array members, the array elements are direct-initialized in increasing
subscript order.) [...]
This is surprisingly difficult to achieve otherwise; it is necessary to construct an index parameter pack using something like std::index_sequence and the semantics are not quite the same.
Another thing lambdas can do is to capture a (variadic) parameter pack; this cannot be done generically (since structure members cannot be a parameter pack expansion) except via something like std::tuple.
Basically: They exist for your convenience.
In addition to Maxim's answer, according to the MSDN article about Lambda Expressions in C++:
When you write code, you probably use function pointers and function
objects to solve problems and perform calculations, especially when
you use STL algorithms. Function pointers and function objects have
advantages and disadvantages—for example, function pointers have
minimal syntactic overhead but do not retain state within a scope, and
function objects can maintain state but require the syntactic overhead
of a class definition.
A lambda combines the benefits of function
pointers and function objects and avoids their disadvantages. Like a
function objects, a lambda is flexible and can maintain state, but
unlike a function object, its compact syntax doesn't require a class
definition. By using lambdas, you can write code that's less
cumbersome and less prone to errors than the code for an equivalent
function object.
The one advantage to captureless lambdas over the corresponding function object is that they are convertible to function pointers.
Using STL algorithms becomes more convenient.
If you want to write
reusable code in your function but might not make sense to put it in
a free function, then lambdas come to the rescue.
For eg.
void foo()
{
auto validate = [] (const std::string& str) -> bool { // do some validation. };
/// ... code.
if (!validate("some info"))
{
// throw error;
}
////
validate("some other info");
}

Should main with trailing return type be avoided? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In the code example below the main function is written with the C++11 trailing return type notation:
auto main() -> int {
//...
return 0;
}
Question:
Are there any reasons that main with trailing return type should be avoided and the classical notation should be preferred?
It's perfectly valid and works just fine.
The only issue to concern is that it is new. It may confuse or surprise readers of your code who are only familiar with C++98.
But it works, so feel free to write your main this way if you feel like it.
First, let's see why you would want to use trailing return types in general.
Kerrek SB's comment to your previous question:
Trailing return types are a specialized language feature that's mostly
useful for generic library writers (that is, writers of generic
libraries, not generic personalities who happen to be writing
libraries), similar to decltype. Incidentally, both language features
also have some limited use in obscure or long lambda expressions, but
they shouldn't be used a lot on "normal" user code.
From Dietmar Kühl's answer (that you have linked in your previous question so you must have read it):
The significance of trailing return types is primarily for function
template where it is now possible to use parameters to the function
together with decltype() to determine the return type. For example:
template <typename M, typename N>
auto multiply(M const& m, N const& n) -> decltype(m * n);
This declares the function multiply() to return the type produced by m * n. Putting the use of decltype() in front of multiply() would be invalid because m and n are not, yet, declared.
I consider both Kerrek SB and Dietmar Kühl C++ experts and find their guidelines good. Now let's see how the above guidelines apply to int main(). Some observations:
int main() is not a function template.
There is no type deduction going on.
The return type (int) won't change in the foreseeable future; we can safely commit to this type.
Are there any reasons that main with trailing return type should be avoided and the classical notation should be preferred?
Yes:
It confuses those developers who are not familiar with the new
syntax.
Not all tools support this new language feature.
As discussed above, using this feature is unnecessary with int main().
I rest my case.
It's plain stupid.
There's no gain, no need or reason to write something like this.
To be pedantic you add the auto and -> symbol for no reason.
A trailing return type is typically used to deduce the return type after the function arguments have been introduced. Here you already know the return type.
Can you imagine (the looks of) your code base if all your functions used this notation without the need to do so ? You'd practically keep at the front all the storage, likage specifications, static etc and leave the return type at the end, to mingle with exception specifications, const specifiers and friends ?
People you don't need to convince me. I'm not against trailing return types; I'm against the "nouveau riche" mentality of using features where there's no need to do it and concerned about C++ becoming a huge blob of styles and collapsing under its own weight.
Lighthearted shifts of the norm are signs of instabillity and lack of communication. A feature like Python's PEP8 would be a good thing to have and trained eyes should be discarded with caution.

C++ making a loosely typed language parser [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm thinking about implementing a very small loosely typed language in C++.
I know that C and C++ CAN be used to make new programming languages but I'm totally lost on how to get around the strict type enforcement.
I need to be able to store any value (char, int, double, std::string are what I'll support)
And then be able to retrieve it.
I know you can store the type as a string in a structure with a void *. But even after you dereference the value inside, it is hard to find a way to store them all consistently.
I know you can use a templated class but I think it makes it so the members of that class can only be the specified template and even then cannot change type.
I'm making a Lisp variant so I need a Cell class that has an internal value that can be any of the listed types above. (Please look up Lisp "cons" cell to understand why I need a data member that can be reassigned)
EDIT:
Let me add that this will be an interpreted language and will not need to be compiled into raw C++.
I suggest something like
struct Value {
enum Tag { Char, Int, Double, String } m_Tag;
union {
char m_char;
int m_int;
double m_double;
std::string m_string;
} u;
};
Of course this will not work as written because you can not have a type with a constructor (string) in a union.
But C++11 loosened that restriction.
When you create a programming language, the key step is parsing the code and translating it into something else. Where I believe you are getting stuck is in your thinking. You are imagining setting things up in c/c++ so that you will use the actual classes you have made in a 'loosely typed' sort of way. Instead your process will be more like this:
Read over the text that has been written in your new language
Figure out what 'type' the author has put in by looking at the text
generate c/c++ (or any other language) code that will deal with their code appropriately
The final conversion could change their code into something that looks completely different. This is where you would define all of the rules that make your language 'loosely typed'.
Since you are making a loosely typed system on top of a strictly typed system, you would have to define all of the logic for all of the possible cases that you are interested in.
Suffice it to say this is not a task for the feint of heart. Here is a list of tools you are going to need to complete the task (or at least the tools I would use):
A regular expression library to parse their text
A context free grammar to define your language
A lexer to validate the code
A variety of object oriented classes to represent your data
A compiler to generate the final code
A whole bundle of knowledge and perseverance
Best of luck.
I know you can store the type as a string in a structure with a void *. But even after you dereference the value inside, it is hard to find a way to store them all consistently.
What do you mean by saying "store them all consistently? They'll consistently lie in the place pointed by the pointer. The pointer will consistently have the same size, no matter what it will actually store. And you'll be able to consistently know the type of the value with the string decribing it. You can even use a single char to store the type information (since you need only 4 values).
If you want to make a variable class, that's probably the only thing you can do - store a pointer and information about the type it's pointing to.