相关疑难解决方法(0)

如何迭代字符串的单词?

我正在尝试迭代字符串的单词.

可以假设该字符串由用空格分隔的单词组成.

请注意,我对C字符串函数或那种字符操作/访问不感兴趣.另外,请在答案中优先考虑优雅而不是效率.

我现在最好的解决方案是:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string s = "Somewhere down the road";
    istringstream iss(s);

    do
    {
        string subs;
        iss >> subs;
        cout << "Substring: " << subs << endl;
    } while (iss);
}
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的方式来做到这一点?

c++ string split

2895
推荐指数
43
解决办法
214万
查看次数

为什么在C++中使用"vector.at(x)"比"vector [x]"更好?

如果我想获得向量中的值,我可以使用两个选项:使用[]运算符.或者我可以使用函数.at示例来使用:

vector<int> ivec;
ivec.push_back(1);
Run Code Online (Sandbox Code Playgroud)

现在我可以做两件事

int x1 = ivec[0];
int x2 = ivec.at(0); // or
Run Code Online (Sandbox Code Playgroud)

我听说使用at是一个更好的选择,因为当我使用该选项时,我可以在异常中抛出这个.

有人可以解释一下吗?

c++ exception vector

29
推荐指数
2
解决办法
1595
查看次数

标签 统计

c++ ×2

exception ×1

split ×1

string ×1

vector ×1