Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are+,-,*,/. Each operand may be an integer or another expression.

Some examples:


["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6




此处)折叠或打开


1. class Solution {
2. public:
3. int evalRPN(vector<string> &tokens) {
4. <string> s;
5. for (auto token : tokens)
6. {
7. if (!is_operator(token))
8. {
9. .push(token);
10. }
11. else
12. {
13. int y = stoi(s.top());
14. .pop();
15. int x = stoi(s.top());
16. .pop();
17. if (token[0] == '+') {
18. += y;
19. }else if (token[0] == '-') {
20. -= y;
21. }else if (token[0] == '*') {
22. *= y;
23. }else {
24. /= y;
25. }
26. .push(to_string(x));
27. }
28. }
29. (s.top());
30. }
31. private:
32. (const string &op) {
33. .size() ==1 && string("+-*/").find(op) != string::npos;
34. }
35. };

对这段代码的些许注释:


 C++11这次的更新带来了令很多C++程序员期待已久的for range循环,每次看到javascript, lua里的for range,心想要是C++能有多好,心里别提多酸了。这次C++11不负众望,再也不用羡慕别家人的for range了。




使用场景


ex1:遍历字符串


1. std::string str = “hello, world”;  
2. for(auto ch : str) {  
3.      std::cout << ch << std::endl;  
4. }


遍历str,输出每个字符,同时用上auto,简直是如虎添翼。




ex2:遍历数组

1. int arr[] = {1, 2, 3, 4};  
2. for(auto i : arr) {  
3.      std::cout<< i << std::endl;  
4. }



不用知道数组容器的大小,即可方便的遍历数组。




ex3:遍历stl 容器

1. std::vector str_vec = {“i”, “like”,  "google”};  
2. for(auto& it : str_vec) {  
3.      it = “c++”;  
4. }



在这段程序中,可以返回引用值,通过引用可以修改容器内容。然后用到了初始化列表,在下一篇文章中,将会介绍。




ex4:遍历stl map 


1. std::map<int, std::string> hash_map = {{1, “c++”}, {2, “java”}, {3, “python”}};  
2. for(auto it : hash_map) {  
3.      std::cout << it.first << “\t” << it.second << std::endl;  
4. }


遍历map返回的是pair变量,不是迭代器。




后记


     for range 很简单,但是为遍历容器提供了很大的便利,再也不用写那么长的for循环了。同时也印证我

这边文章

说的,C++是变的复杂了,但同时它变的更好了。它提供的特性你不用也没关系,但如果你一直在使用C++,或者作为合格的程序员,保持学习是亘古不变的。何不花一点时间学习一下C++新特性,不仅提高效率,并且使得自己的代码更加优美,何乐而不为呢?


find函数有以下四种重载版本:

size_t find (const string& str, size_t pos = 0) const noexcept;
size_t find (const char* s, size_t pos = 0) const;
size_t find (const char* s, size_t pos, size_type n) const;
size_t find (char c, size_t pos = 0) const noexcept;

参数说明:

str/s/c:要寻找的序列,可以是字符串(版本1),也可以是字符串字面值或者说C风格字符串(版本2、3,在版本3中,所寻找的序列是从s[0]开始的前n个字符),也可以是字符(版本4)。

pos:从string的pos位置开始寻找(注意第一个位置是0)。

函数返回序列第一次出现的位置,如果没有找到则返回string::npos。

std::to_string


string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);


Convert numerical value to string

Returns a 

string with the representation of 

val.



The format used is the same that 

printf would print for the corresponding type:


val

printfequivalent

description

int

"%d"

val.

The representations of negative values are preceded with a minus sign (-).

long

"%ld

long long

"%lld

unsigned

"%u"

val.

unsigned long

"%lu

unsigned long long

"%llu

float

"%f"

As many digits are written as needed to represent the integral part, followed by the decimal-point character and six decimal digits.

inf (or infinity) is used to represent infinity.

nan (followed by an optional sequence of characters) to represent NaNs (Not-a-Number).

The representations of negative values are preceded with a minus sign (-).

double

"%f

long double

"%Lf


Parameters

val Numerical value.


Return Value


string object containing the representation of 

val as a sequence of characters.


Example

// to_string example #include  // std::cout #include  // std::string, std::to_string int main ()
{
  std::string pi = "pi is " + std::to_string(3.1415926);
  std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
  std::cout << pi << '\n';
  std::cout << perfect << '\n'; return 0;
}




Possible output:


pi is 3.14159328 is a perfect number



Exceptions

The 

string constructor may throw.



See also


sprintf Write formatted data to string 

(function ) to_wstring Convert numerical value to wide string 

(function )

function template



std::stoi


int stoi (const string&  str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);


Convert string to integer

Parses 

str interpreting its content as an integral number of the specified 

base, which is returned as an int value.



If 

idx is not a null pointer, the function also sets the value of 

idx to the position of the first character in 

str after the number.



The function uses 

strtol (or 

wcstol) to perform the conversion (see 

strtol for more details on the process).



Parameters

str String object with the representation of an integral number. idx Pointer to an object of type 

size_t, whose value is set by the function to position of the next character in 

strafter the numerical value.


This parameter can also be a null pointer, in which case it is not used. base Numerical base (radix) that determines the valid characters and their interpretation.


If this is 0, the base used is determined by the format in the sequence (see 

strtol for details). Notice that by default this argument is 10, not 0.


Return Value

On success, the function returns the converted integral number as an int value.



Example

// stoi example #include  // std::cout #include  // std::string, std::stoi int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz; // alias of size_t int i_dec = std::stoi (str_dec,&sz); int i_hex = std::stoi (str_hex,nullptr,16); int i_bin = std::stoi (str_bin,nullptr,2); int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n'; return 0;
}




Output:


2001, A Space Odyssey: 2001 and [, A Space Odyssey]40c3:  16579-10010110001: -12010x7f: 127



Complexity

Unspecified, but generally linear in the number of characters interpreted.



Data races

Modifies the value pointed by 

idx (if not zero).



Exceptions

If no conversion could be performed, an 

invalid_argument exception is thrown.



If the value read is out of the range of representable values by an int, an 

out_of_range exception is thrown.




An invalid  
idx causes  
undefined behavior.

See also


stol Convert string to long int  
(function template ) 
stoul Convert string to unsigned integer  
(function template ) 
strtol Convert string to long integer  
(function )