我正在尝试迭代字符串的单词.
可以假设该字符串由用空格分隔的单词组成.
请注意,我对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)
有没有更优雅的方式来做到这一点?
如果我想获得向量中的值,我可以使用两个选项:使用[]运算符.或者我可以使用函数.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是一个更好的选择,因为当我使用该选项时,我可以在异常中抛出这个.
有人可以解释一下吗?