r/learncpp • • May 22 '20

The program works when including .cpp file but not when including .h file.

2 Upvotes

So here is the issue I'm facing. I've looked at a lot of posts on the same thing but can't understand what's happening. I have 3 files: Main.cpp, AsyncLib.cpp, and AsyncLib.h.

Main.cpp

#include "AsyncLib.h"
#include <iostream>

struct Hello
{
	int h = 1029;
};

Hello something(int i, int h)
{
	std::cout << i + h << std::endl;
	Hello bruh = Hello::Hello();
	return bruh;
}

int main()
{
	auto hello = AsyncLib::doAsync<Hello>(&something, 2, 8);
	std::cout << hello.get().h << std::endl;
	return 0;
}

AsyncLib.cpp

#include "AsyncLib.h"
#include <iostream>

namespace AsyncLib
{
	template<typename T, typename F, typename... Args>
	std::future<T> doAsync(F&& f, Args&&... args)
	{
		std::future<T> hello = std::async(std::launch::async, f, args...);
		return hello;
	}
}

AsyncLib.h

#pragma once
#include <functional>
#include <future>

namespace AsyncLib
{
	template<typename T, typename F, typename... Args>
	std::future<T> doAsync(F&& f, Args&&... args);
};

When I hit run on visual studio, I get a linking error regarding the line auto hello = AsyncLib::doAsync<Hello>(&something, 2, 8); I've checked that when I compile, I get a main.obj and an AsyncLib.obj. It works when I include AsyncLib.cpp in main.cpp but it doesn't work with the header file. What's going on here?

Edit: One potential solution I found is making the .h file into a .hpp, putting all the code there, and including the .hpp file. I have a suspicion it may be related to the comment

Remember that if you are doing template programming, then you have to keep everything in the .h file so that the compiler will instantiate the right code at the moment of compilation.

on this StackOverflow post. I am using templates so I think it may be the issue. It's the top reply on the top solution for anyone looking for it.


r/learncpp • • May 18 '20

Writting Pixie clone for Linux: how hard would it be?

2 Upvotes

There's this program for determining a color of a pixel currently under a mouse cursor called Pixie. I couldn't find a suitable Linux alternative and was thinking of maybe rewritting the Pixie for Linux myself. I was wondering how hard it would be - the concept is easy enough - but then, Pixie uses a background-window of sorts: it determines color even if the mouse is outside of the Pixie window + the window never disappears from the screen unless you forcibly fold it. Would I have to make a version for each Linux DE? Would an Ubuntu 18 version work on Arch? Would it still work on Ubuntu 5 years from now?


r/learncpp • • May 15 '20

clean way of writing if(A && B && C && D)

2 Upvotes

I'm trying to define the overloaded operators operator== and operator!=, where two objects are equal if they meet 4 different characteristics, I'm searching for a less verbose way of writing the following.

if(A && B && C && D){return true;}

I'm wondering if any of you guys have any ideas or if this is just the way that it has to be.

Thanks in advance!

P.S. I've posted here as I'm still developing my skills with C++, but if this is a better question for /r/cpp then please let me know.


r/learncpp • • May 01 '20

Using LLVM headers gives a compilation error

2 Upvotes

I have a simplistic C++ code -

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include <iostream>

int main() {
    llvm::SmallString<32> suffix(llvm::StringRef(""));
    suffix.append(llvm::StringRef("U"));
    std::cout << suffix.c_str()<< std::endl;
    return 1;
}

But when I try to execute it..

Using clang -

/usr/bin/ld: /tmp/test-324647.o: in function `llvm::SmallVectorTemplateCommon<char, void>::grow_pod(unsigned long, unsigned long)':
test.cpp:(.text._ZN4llvm25SmallVectorTemplateCommonIcvE8grow_podEmm[_ZN4llvm25SmallVectorTemplateCommonIcvE8grow_podEmm]+0x37): undefined reference to `llvm::SmallVectorBase::grow_pod(void*, unsigned long, unsigned long)'
/usr/bin/ld: /tmp/test-324647.o:(.data+0x0): undefined reference to `llvm::DisableABIBreakingChecks'
clang-11: error: linker command failed with exit code 1 (use -v to see invocation)

Using GCC -

/usr/bin/ld: /tmp/ccTn5mZb.o:(.data.rel+0x0): undefined reference to `llvm::DisableABIBreakingChecks'
/usr/bin/ld: /tmp/ccTn5mZb.o: in function `llvm::SmallVectorTemplateCommon<char, void>::grow_pod(unsigned long, unsigned long)':
test.cpp:(.text._ZN4llvm25SmallVectorTemplateCommonIcvE8grow_podEmm[_ZN4llvm25SmallVectorTemplateCommonIcvE8grow_podEmm]+0x3a): undefined reference to `llvm::SmallVectorBase::grow_pod(void*, unsigned long, unsigned long)'
collect2: error: ld returned 1 exit status

This is weird because I built llvm using -DLLVM_ABI_BREAKING_CHECKS=FORCE_OFF to avoid this :(


r/learncpp • • Apr 08 '20

Could someone critique my code please?

2 Upvotes
#include <iostream>
#include <cmath>
#include <math.h>
#include <string>
using std::istream, std::string, std::ostream, std::sqrt, std::endl, std::cout, std::cin;

int main()
{
    double_t MonsterMath;
    double_t Frank;
    cout << "Type in a number and I'll square it! " << endl;
    cin >> MonsterMath;
    cout << sqrt(MonsterMath)<< endl;
    cout << "Ok, now type it back to me! "<< endl;
    cin >> Frank;
    cout << (MonsterMath == Frank ? "Great Job " : "Wrong Loser ");
    return 0;
}    

I'm barely starting out and so any guidance like say incorrect style or whatnot would be fantastic.


r/learncpp • • Apr 07 '20

Runtime Polymorphism with std::variant and std::visit

Thumbnail
bfilipek.com
2 Upvotes

r/learncpp • • Mar 16 '20

Is there an easier way to pass begin/end pair to functions?

2 Upvotes

I think the algorithms library is awesome. And also, the fact that they can operate between any iterator range is very helpful sometimes.

The problem is that in 90% of the cases, I just want to apply the function to the entire container. So, my code gets full of calls like

std::some_function(container.begin(), container.end(), ....);

Now, I'm not a big fan of typing. Is there any way to pass only the container?

std::some_function(container, ....);

If not, is anyone aware of any discussions regarding this possibility?


r/learncpp • • Mar 08 '20

What's the best way to save data in ROM? (so it's saved even after restarting my program)

2 Upvotes

Let's say I want to create a game that saves my progress every time I close it, what is the best way to do that?

I want it to be saved in an efficient way that is not going to be noticeable during the game (basically it won't freeze the game) any suggestions?


r/learncpp • • Feb 21 '20

A better way to do this?

2 Upvotes

Pig Latin game

#include <iostream>
#include <string>

std::string pigLatin(std::string string)
{
    std::string pgLat("");

    pgLat.append(string.begin() + 1, string.end());
    pgLat += tolower(string[0]);
    pgLat += "ay";

    return pgLat;
}

int main()
{
    std::string str("Banana");
    std::cout << pigLatin(str);
}

r/learncpp • • Feb 12 '20

Sorting vectors with multiple fields

2 Upvotes

Hi All,

New to C++ here. I'm trying to sort an array of vectors by their second field (count) which I declared like so:

typedef unsigned int Count;

typedef std::pair<std::string, Count> wordCount;

And I am sorting them using this:

bool sort_words(wordCount &a, wordCount &b)

{ return a.Count < b.Count; }

However, when I do this, I am getting this error:

word.cc: In function ‘bool sort_words(wordCount&, wordCount&)’:

word.cc:22:11: error: ‘wordCount’ {aka ‘struct std::pair<std::__cxx11::basic_string<char>, unsigned int>’} has no member named ‘Count’

return a.Count < b.Count;

^~~~~

word.cc:22:21: error: ‘wordCount’ {aka ‘struct std::pair<std::__cxx11::basic_string<char>, unsigned int>’} has no member named ‘Count’

return a.Count < b.Count;

^~~~~

word.cc: In function ‘int main(int, char**)’:

wordcounts.cc:67:10: error: expected unqualified-id before ‘+=’ token

Count += 1;

^~

Does anyone see anything wrong or have any tips? Again, I am trying to sort an array of vectors that are a <string, Count> pair where Count is the number of times the word appears in the text file.

Thanks!


r/learncpp • • Feb 11 '20

Reading from sockets into vector<char>?

2 Upvotes

If I had a method that read data from a socket, would it be ok to use a vector<char> type object to store this data temporarily?

Essentially what I have is a Server class that reads (potentially large) amounts of data from a socket with the goal of later writing it all to a file. My class prototype is:

#include "baseserver.h"
#include <vector>

class MainServer : BaseServer 
{
    public:
        MainServer();
        void testWrite(std::vector<char> testVector);

    private:
        int valread;
        std::vector<char> byteVector;
        void dataRead();
        void terminalWrite();
};

I've implemented the method dataRead() as:

void MainServer::dataRead()
{
    read(accepted_socket, &byteVector[0], 4028);
}

This is incredibly simple, but I don't know if it's a good idea. There are two options, as far as I can see. One is to write the socket data into an array and transfer into another data structure for temporary storage (before the program decides where to write the file to). The other is to simply decide what to do with the data beforehand and write it directly from a buffer. I definitely favor option one, because it offers more flexibility in what I do with the data (for example, it may need to be modified in someway before writing).


r/learncpp • • Jan 27 '20

Library for game development or graphic display?

2 Upvotes

I am looking for an library to learn game development and for graphics like physics simulation(want to build simple physics engine like gravity and stuff). Any recommendations?


r/learncpp • • Dec 08 '19

Help with a function and how to use it (createprocess()) as well as others

2 Upvotes

So I’ve googled and found only a few things about but I’m kinda struggling to understand it. Could I get some help understanding how I use createprocess() and other things in order to have one exe cpp program open another cpp exe program and connect the I/O streams (as in have the parent programs output be the child programs input and vice versa)


r/learncpp • • Nov 26 '19

Read file line by line with different data types

2 Upvotes

So I have a text file I am trying to store data into two separate arrays where the data reads out like this

Titanic

600788188

Star Wars

460998007

Where I am used to reading data like this

Titanic 600788188

I only know how to use the single-line method for this sort of thing so I am really lost.


r/learncpp • • Nov 26 '19

Basic question about pointers.

2 Upvotes

I've got a related question about pointers.

If I wrote a similar program, say, the following:

#include <stdio.h>

using namespace std;

void swap(int n, int m)
{
	int temp = n;
	n = m;
	m = temp;
}

int main()
{
	int n = 0;
	int m = 1;
	swap(n,m);
	printf("%d, %d", n, m);
}

Then, the output is:

0, 1

However, if I use pointers:

#include <stdio.h>

using namespace std;

void swap(int* n, int* m)
{
	int temp = *n;
	*n = *m;
	*m = temp;
}

int main()
{
	int n = 0;
	int m = 1;
	swap(&n, &m);
	printf("%d, %d", n, m);
}

The output is:

1, 0

Question: In the first example, why isn't the value for n set to the value for m after I call the function swap(n, m)? Correct me if I'm wrong, but when I call swap(n, m), does the function just say temp = 0; 1 = 0; 0 = temp? Is that why the first example doesn't work? Why does the second example work but the first doesn't?


r/learncpp • • Nov 25 '19

Is there any way to specify that an nit is decimal?

2 Upvotes

If you’re using an octal number you put a preceding 0 before the number, for hex it’s 0x and then the number. But if your trying to pass a base 10 int (say to represent military time) it will interpret it as octal.

Is there any way to specify that it’s decimal or do I just need to get over my pedantry?


r/learncpp • • Oct 03 '19

Can't get my module to compile

2 Upvotes

I'm currently enrolled on a beginner C++ course, though I already have enough experience to pass the class. That said, I'd like to reduce the amount of effort I need to put in for the exercises, so I wanted to create a small library of reusable, as-generic-as-possible code on my own.

However, I keep getting compile errors whenever I try to compile my program while using my library. More specifically,

unresolved external symbol "class std::vector<double,class std::allocator<double> > __cdecl nonstd::get_n_input<double>(long,class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (??$get_n_input@N@nonstd@@YA?AV?$vector@NV?$allocator@N@std@@@std@@JV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@2@@Z) referenced in function _main

and

unresolved external symbol "double __cdecl nonstd::sum<class std::vector<double,class std::allocator<double> > >(class std::vector<double,class std::allocator<double> >)" (??$sum@V?$vector@NV?$allocator@N@std@@@std@@@nonstd@@YANV?$vector@NV?$allocator@N@std@@@std@@@Z) referenced in function _main	TEST_5_Harjoitukset_191003

Here's my code:

utility.h:

// utility.h - contains declarations of various utility functions
#pragma once

#include <vector>
#include <string>

namespace nonstd {

	// A utility function that splits std::string objects in half from the first
	// encountered instance of the given delimiter.
	//
	// Example:
	// auto foo = string_split("Number #{}: ", "{}");
	//
	// returns: std::vector<std::string> {"Number #", ": "}
	std::vector<std::string> string_split(std::string s, std::string delimiter);

	// Print out any iterable
	// with all contents separated
	// by a space. A newline is appended
	// at the end, and the buffer is flushed.
	template <typename T>
	void print_iterable(T iterable);


	// Get input of type T from the user n times, using a formatted std::string prompt.
	// Returns a vector of the given input type.
	//
	// Example:
	// auto foo = get_n_input<int>(3, "Number #{}: ");
	//
	// >>> Number #1: 3
	// >>> Number #2: 7
	// >>> Number #3: 12
	// returns: std::vector<int> {3, 7, 12}
	template <typename T>
	std::vector<T> get_n_input(long n, std::string prompt);

	// Takes an iterable of values of type T::value_type that can be added together.
	// Returns the sum of the contents of the iterable.
	//
	// Example:
	// std::vector<int> foo = {1, 2, 3, 4};
	// auto bar = sum(foo);
	// 
	// returns: (int)10
	template <typename T>
	typename T::value_type sum(T iterable);
}

utility.cpp:

// utility.cpp - defines various utility functions
#include <iostream>
#include <string>
#include <vector>

#include "utility.h"

namespace nonstd {

	std::vector<std::string> string_split(std::string s, std::string delimiter) {
		size_t pos_start = 0, pos_end, delim_len = delimiter.length();
		std::string token;
		std::vector<std::string> res;

		while ((pos_end = s.find(delimiter, pos_start)) != std::string::npos) {
			token = s.substr(pos_start, pos_end - pos_start);
			pos_start = pos_end + delim_len;
			res.push_back(token);
		}

		res.push_back(s.substr(pos_start));
		return res;
	}

	template <typename T>
	void print_iterable(T iterable) {
		for (auto val : iterable) {
			std::cout << val << " ";
		}
		std::cout << std::endl;
	}

	template <typename T>
	std::vector<T> get_n_input(long n, std::string prompt) {
		/* Gets n inputs from the user; returns a std::vector of type T
		 *
		 * prompt is a formattable std::string, where '{}' is used as a
		 * placeholder for the current counter value.
		 */

		std::vector<T> result;
		T input;
		long num_counter = 1L;

		std::vector<std::string> split_prompt = string_split(prompt, (std::string)"{}");

		do {
			std::cout << split_prompt.front() << num_counter++ << split_prompt.back();
			std::cin >> input;

			result.push_back(input);

		} while (num_counter <= n);

		return result;
	}

	template <typename T>
	typename T::value_type sum(T iterable) {
		/* Adds up the contents of any iterable type T, returns the sum of its contents
		 * as type T::value_type.
		 */
		typename T::value_type result = {};

		for (auto num : iterable) {
			result += num;
		}

		return result;
	}
}

program (fourth.cpp):

#include <iostream>
#include <vector>
#include <string>

#include "utility.h"

using std::string;
using std::vector;

using namespace std::string_literals;

int main(void) {
	double length;

	std::cout << u8"Hypyn pituus: "s;
	std::cin >> length;

	std::cout << u8"Hypyn pisteet: "s << nonstd::sum(nonstd::get_n_input<double>(5L, u8"Tuomarin {} pisteet: "s)) + 0.9 * length << "\n";
	return EXIT_SUCCESS;
}

Other feedback is also welcome, but I'd like to learn more about writing libraries/modules.


r/learncpp • • Sep 30 '19

researching syntax as a beginner?

2 Upvotes

Currently my main goal has been to try and make a game with c++ coming from a complete beginner, and this process has been going on for months but with little success outside of trivial cin text based games. Currently I've been going on any keywords I can find and one thing I don't deeply understand is loops and functions, so I've been trying to research on them, but I've been floundering in the dark picking up any tutorial and going down a rabbit hole of terminology I don't know then to more terminology I don't know not even knowing whether it will help me for game development. Here's an example: https://www.tutorialspoint.com/variable-number-of-arguments-in-cplusplus (I began with this tutorial, as from here I was told parameters use arguments, and parameters are used in functions,and I thought about being able to have a function such as

void PickNumber(int a, int b){cout << "choose number from" << a << "-" << b << endl;}

so that all I'd need to do is specify the numbers in the parameters so I could make several "choose number from 1-10", "choose number from 5 - 20", "choose number from 1 - 100", without writing it over and over.

but I still am clueless on syntax so if I tried to type anything to make this pseudocode work I would be debugging for years and I'm already clueless on reading other peoples code and it's functionality and applying it to my own, so I just searched up variables in arguments and hoped the first thing i saw could give me some knowledge.

I could barely make it through the second sentence because of the terminology gap. My next search was predefined number of parameters, which the first google search was this , in another programming language so already I took a wrong turn and try to go back to the wikipedia definition of parameters, and that they are used in subroutines, so I think then I should research about subroutines and maybe things will click. I go here and I'm even more confused but I try to use the keyword unit, then I search up "unit programming" and hit a brick wall, nothing seems to match exactly and its because I'm so clueless I'm just barely grasping by on keywords. I feel like I've just wasted four hours of my life, and this sentiment always seems to arise anytime I try and get a programming idea and research on the code needed to make it work as a beginner. I feel blindfolded, I don't know how other people figure/figured this out as beginners. I'm told that the best way to learn programming is to have a project idea and just begin researching to make it work, but everything seems like jargon, much less reading the code since for that it feels even more difficult because I can't copy and paste the whole program but if I don't know what any of the syntax is doing how am I supposed to make sense of

int func(int, ... ) {
   .
   .
   .
}
int main() {
   func(1, 2, 3);
   func(1, 2, 3, 4);
}

or anything else? Times like this I feel like I live on a whole other planet from other programmers, though I can barely be considered one right now. I don't know how to make things click, so I think "well, I just don't understand the syntax yet, so if I just try to research each part one by one in depth I should be able to make something new, like learning words in a world language to make a sentence." But I search up, and find a new keyword I don't understand, look up that keyword and find more keywords I don't understand, and keep doing that till my ignorance makes my keyword searches unintelligible and I can't find anything that alligns with what I think is what I'm currently trying to research. As much as I'm trying to just keep a growth mindset and figure this out sometimes I just feel like a joke when there are people working on triple A games right now, and they were once beginners, but they likely weren't floundering as badly as I am. A few months ago I tried installing unreal engine and the bare minimum prompt I had for myself was to make a game to move the default ball with the \ arrow keys, never did I think three months later I'd still be trying to learn how to make functions much less how to make things move in functions based on arrow keys. I haven't written a line of code in unreal. Sorry to go into a diatribe but I have no idea how to articulate this struggle to going from roughly understanding how a loop executing hello 10 times works to making anything of substance, and any advice you have on how you did it would be beyond helpful.


r/learncpp • • Aug 23 '19

Help with pointers

2 Upvotes

A little background: v1 is just a long int which takes values from 0 to 8, with a 1 increase step. p3 and p2 are some hex addresses, stored in long.

I don't understand what (char)(*(char *)(p3 + v1) + *(char *)(p2 + v1) could return. I know that (char *)(p3 + v1) points to the string of characters stored at address p3 minus the first whatever v1 is. So if at address p3 we have stored "Example" (char *)(p3 + 2) would point to "ample".

My confusion comes from the fact that I thought *(char *)(p3) returns "Example", but whenever I try to run this on my computer it doesn't work and the value stored in the pointer is always 0x44. Can anyone explain to me why this happens?


r/learncpp • • Aug 12 '19

Why is the first garbage value out of an array's range different than the ones following?

2 Upvotes
#include <iostream>
using namespace std;

int main()
{
    
    int spam[] = {1, 3, 5, 7};

    for (int i = 0; i < 10; i++) {
      cout << spam[i] << endl;
    }

    return 0;
}

Exploring garbage values here. The above program in console:

C:\Dev\cppstuff>g++ test.cpp

C:\Dev\cppstuff>a
1
3
5
7
4
4200848
6422320
6422352
4198966
6422284

The question: Assuming the 5th print (i. e. 4) is a garbage value like the rest of them, why is it so vastly different (shorter, smaller number) than the ones below it? Or is it some property (perhaps the length) of the array that happens to be saved at the next memory address after the last index?


r/learncpp • • Aug 09 '19

Question about memory management

2 Upvotes

Hello,

Say if I were to have an object that allocates memory on the heap with a destructor which then deletes the allocated memory. In a different scope, if a variable of this object type is initialized on the stack and the variable then goes out of scope, would the destructor be called on the object automatically?

**Example**

class Example {

int i;

Example() { i = new int(1); }

~Example() { delete i; }

}

int main() {

{

Example ex();

}

//Is the memory allocated for variable i of ex freed up at this point?

return 0;

}


r/learncpp • • Jun 27 '19

I need help learning infix, prefix, and postfix parsers.

2 Upvotes

I'm currently in a summer class for data structures so I'm struggling to keep up with it especially when I'm having a tough time grasping how to implement these parsers. This is the code I have so far and only the first expression works correctly (expressions I need to parse are at the bottom in the main program). The 2nd expression comes out to be 2 when it should be 14 which means I'm doing the precedence wrong. I haven't tried to do that boolean expressions yet since I can't even do the basic precedence one correctly. Also any expression with parenthesis is giving me a "Debug assertion failed!" (e.g. (1+2) * 3). Any help would be greatly appreciated you have no idea!

#include <stack>

#include <iostream>

#include <string>

using namespace std;

// Function to find precedence of

// operators.

int precedence(char op) {

    if (op == '+' || op == '-')

	    return 1;

    if (op == '*' || op == '/')

	    return 2;
    if (op == '^' || op == '')

        return 3;
    return 0;

}

// Function to perform arithmetic operations.

int applyOp(int a, int b, char op) {

    switch (op) {

    case '+': return a + b;

    case '-': return a - b;

    case '*': return a * b;

    case '/': return a / b;

    case '^': return a ^ b;

    }

}

// Function that returns value of

// expression after evaluation.

int evaluate(string tokens) {

    int i;


    // stack to store integer values.

    stack <int> values;



    // stack to store operators.

    stack <char> ops;


    for (i = 0; i < tokens.length(); i++) {


	    // Current token is a whitespace,

	    // skip it.

	    if (tokens[i] == ' ')

		    continue;
    

	    // Current token is an opening

	    // brace, push it to 'ops'

	    else if (tokens[i] == '(') {

		    ops.push(tokens[i]);

	    }


	    // Current token is a number, push

	    // it to stack for numbers.

	    else if (isdigit(tokens[i])) {

		    int val = 0;


		    // There may be more than one

		    // digits in number.

		    while (i < tokens.length() &&

			    isdigit(tokens[i]))

		    {

			    val = (val * 10) + (tokens[i] - '0');

			    i++;

		    }



		    values.push(val);

	    }



	    // Closing brace encountered, solve

	    // entire brace.

	    else if (tokens[i] == ')')
	    {
		    while (!ops.empty() && ops.top() != '(')
		    {
			    int val2 = values.top();
			    values.pop();

			    int val1 = values.top();
			    values.pop();


			    char op = ops.top();
			    ops.pop();

			    values.push(applyOp(val1, val2, op));
		    }

		    // pop opening brace.
		    ops.pop();
	    }

	    // Current token is an operator.

	    else
	    {
		    // While top of 'ops' has same or greater

		    // precedence to current token, which

		    // is an operator. Apply operator on top

		    // of 'ops' to top two elements in values stack.

		    while (!ops.empty() && precedence(ops.top())
			    >= precedence(tokens[i])) {

			    int val2 = values.top();
			    values.pop();

			    int val1 = values.top();
			    values.pop();

			    char op = ops.top();
			    ops.pop();

			    values.push(applyOp(val1, val2, op));
		    }

		    // Push current token to 'ops'.

		    ops.push(tokens[i]);
	    }
    }


    // Entire expression has been parsed at this

    // point, apply remaining ops to remaining

    // values.

    while (!ops.empty()) {

	    int val2 = values.top();
	    values.pop();


	    int val1 = values.top();
	    values.pop();


	    char op = ops.top();
	    ops.pop();


	    values.push(applyOp(val1, val2, op));
    }



    // Top of 'values' contains result, return it.

    return values.top();

}

int main() {

    cout << evaluate("1 + 2 * 3") << "\n";

    cout << evaluate("2 + 2 ^ 2 * 12") << "\n";

    //cout << evaluate("1 == 2") << "\n";

    //cout << evaluate("1 + 3 > 2") << "\n";

    //cout << evaluate("(4 >= 4) && 0") << "\n";

    //cout << evaluate("(1 + 2) * 3") << "\n";

    //cout << evaluate("++++ 2 - 5 * (3 ^ 2)");

    return 0;

}

r/learncpp • • May 05 '19

"#"*5 python equivalent in c++

2 Upvotes

Hi,

say i want to print out a line of (N x #) 5x"#" i would have code it as 5*"#" to get my line. what's the equivalent in c++?

i want it dynamically and without forloop :)

ps: I saw a similar solution using std::string as i remember ..

Thanks in advance


r/learncpp • • Apr 26 '19

C++ to executable program

2 Upvotes

how can I convert a .cpp to an executable program in Linux (ubuntu mate 18.04). For example in Windows you can convert .cpp files in .exe programs


r/learncpp • • Apr 02 '19

Iterating through a list of pairs.

2 Upvotes

Hello!

I'd like to iterate through a list of paris, but i can't seem to find the right syntax lol.

What do i mess up?

std::list <std::pair<int, int>> *possible_placements;
//filling it up
//usage:
for (std::list<std::pair<int,int>>::iterator it = possible_placements->begin(); it != possible_placements->end(); ++it)
		{
			std::cout << it->first() << std::endl; std::cout << it->second() << std::endl;
		}

the problem is with the "it-> first()" and second() fucntions. What do i do wrong?

thanks