我正在尝试迭代字符串的单词.
可以假设该字符串由用空格分隔的单词组成.
请注意,我对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);
}
有没有更优雅的方式来做到这一点?
我在一些库头文件中有一堆枚举类型,我正在使用,我想有一种方法将枚举值转换为用户字符串 - 反之亦然.
RTTI不会为我做这件事,因为'用户字符串'需要比枚举更具可读性.
一个强力解决方案将是一堆像这样的功能,但我觉得这有点像C样.
enum MyEnum {VAL1, VAL2,VAL3};
String getStringFromEnum(MyEnum e)
{
  switch e
  {
  case VAL1: return "Value 1";
  case VAL2: return "Value 2";
  case VAL1: return "Value 3";
  default: throw Exception("Bad MyEnum");
  }
}
我有一种直觉,认为使用模板有一个优雅的解决方案,但我还不能完全理解它.
更新:感谢您的建议 - 我应该明确说明枚举是在第三方库头中定义的,所以我不想更改它们的定义.
我现在的直觉是避免使用模板并执行以下操作:
char * MyGetValue(int v, char *tmp); // implementation is trivial
#define ENUM_MAP(type, strings) char * getStringValue(const type &T) \
 { \
 return MyGetValue((int)T, strings); \
 }
; enum eee {AA,BB,CC}; - exists in library header file 
; …