Chinaunix首页 | 论坛 | 博客
  • 博客访问: 519503
  • 博文数量: 184
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1172
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-21 13:40
个人简介

技术改变命运

文章分类

全部博文(184)

文章存档

2020年(16)

2017年(12)

2016年(156)

我的朋友

分类: C/C++

2016-08-03 16:46:01

Evaluate the value of an arithmetic expression in .

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.         stack<string> s;
  5.         for (auto token : tokens)
  6.         {
  7.             if (!is_operator(token))
  8.             {
  9.                 s.push(token);
  10.             }
  11.             else
  12.             {
  13.                 int y = stoi(s.top());
  14.                 s.pop();
  15.                 int x = stoi(s.top());
  16.                 s.pop();
  17.                 if (token[0] == '+') {
  18.                     x += y;
  19.                 }else if (token[0] == '-') {
  20.                     x -= y;
  21.                 }else if (token[0] == '*') {
  22.                     x *= y;
  23.                 }else {
  24.                     x /= y;
  25.                 }
  26.                 s.push(to_string(x));
  27.             }
  28.         }
  29.         return stoi(s.top());
  30.     }
  31. private:
  32.     bool is_operator(const string &op) {
  33.         return op.size() ==1 && string("+-*/").find(op) != string::npos;
  34.     }
  35. };
对这段代码的些许注释:
 C++11这次的更新带来了令很多C++程序员期待已久的for range循环,每次看到javascript, lua里的for range,心想要是C++能有多好,心里别提多酸了。这次C++11不负众望,再也不用羡慕别家人的for range了。

使用场景
ex1:遍历字符串
[cpp] view plain copy
  1. std::string str = “hello, world”;  
  2. for(auto ch : str) {  
  3.      std::cout << ch << std::endl;  
  4. }  

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

ex2:遍历数组
[cpp] view plain copy
  1. int arr[] = {1, 2, 3, 4};  
  2. for(auto i : arr) {  
  3.      std::cout<< i << std::endl;  
  4. }  

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

ex3:遍历stl 容器
[cpp] view plain copy
  1. std::vector str_vec = {“i”, “like”,  "google”};  
  2. for(auto& it : str_vec) {  
  3.      it = “c++”;  
  4. }  

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

ex4:遍历stl map 
[cpp] view plain copy
  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  with the representation of val.

The format used is the same that  would print for the corresponding type:
type of val printfequivalent description
int "%d" Decimal-base representation of val.
The representations of negative values are preceded with a minus sign (-).
long "%ld
long long "%lld
unsigned "%u" Decimal-base representation of 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

A  object containing the representation of val as a sequence of characters.

Example

1
2
3
4
5
6
7
8
9
10
11
12 
// 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.141593
28 is a perfect number 

Exceptions

The  may throw.

See also

Write formatted data to string (function ) 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  (or ) to perform the conversion (see  for more details on the process).

Parameters

str String object with the representation of an integral number. idx Pointer to an object of type , 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  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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 
// 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: -1201
0x7f: 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  exception is thrown.

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

An invalid idx causes undefined behavior.

See also

Convert string to long int (function template ) Convert string to unsigned integer (function template ) Convert string to long integer (function )


阅读(1170) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~