我正在尝试迭代字符串的单词.
可以假设该字符串由用空格分隔的单词组成.
请注意,我对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)
有没有更优雅的方式来做到这一点?
我有以下代码:
std::string str = "abc def,ghi";
std::stringstream ss(str);
string token;
while (ss >> token)
{
printf("%s\n", token.c_str());
}
Run Code Online (Sandbox Code Playgroud)
输出是:
abc
def,ghi
因此,stringstream::>>运算符可以按空格分隔字符串,但不能用逗号分隔.反正有没有修改上面的代码,以便我可以得到以下结果?
输入:"abc,def,ghi"
输出:
abc
def
ghi
我可以使用g ++ -c test.cpp -std = c ++ 0x创建.o文件,但无法链接它,得到下一个错误:
test.cpp:(.text+0xe5): undefined reference to `std::regex_iterator<char const*, char, std::regex_traits<char> >::regex_iterator(char const*, char const*, std::basic_regex<char, std::regex_traits<char> > const&, std::bitset<11u>)'
test.cpp:(.text+0xf1): undefined reference to `std::regex_iterator<char const*, char, std::regex_traits<char> >::regex_iterator()'
Run Code Online (Sandbox Code Playgroud)
码:
#include <regex>
#include <iostream>
#include <string.h>
typedef std::regex_iterator<const char *> Myiter;
int main()
{
const char *pat = "axayaz";
Myiter::regex_type rx("a");
Myiter next(pat, pat + strlen(pat), rx);
Myiter end;
return (0);
}
Run Code Online (Sandbox Code Playgroud) 我正在Yosemite的XCode上运行.
代码编译但在运行时崩溃,为什么?
我故意在第二个std :: copy中使用"{}"作为"范围结束".
我试验了这段代码,因为一个工作示例使用"{}"作为"默认构造的流迭代器作为范围的结尾".
那么为什么(见第二个代码)一个正在工作,但这个(第一个代码)一个失败了?
#include <algorithm>
#include <iterator>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int> coll1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// copy the elements of coll1 into coll2 by appending them
vector<int> coll2;
copy (coll1.cbegin(), coll1.cend(), // source
back_inserter(coll2)); // destination
vector<int> coll3;
copy (coll1.begin(), {},
back_inserter(coll3));
}
Run Code Online (Sandbox Code Playgroud)
以下代码来自The C++ Standard Library第二版.
带有"// end of source"的行可以是"istream_iterator()",也可以是"{}",
两者都有效,因为:引用了这本书
"请注意,从C++ 11开始,您可以将空的花括号而不是默认构造的流迭代器作为范围的结尾传递.这是有效的,因为定义源范围结束的参数类型是从前一个参数推导出来的它定义了源范围的开始."
/* The following code example is …Run Code Online (Sandbox Code Playgroud)