【问题标题】:Traverse using macros in STL [closed]在 STL 中使用宏进行遍历 [关闭]
【发布时间】:2015-02-21 09:55:21
【问题描述】:
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
    map<string, int> M; 
    int r = 0; 
    tr(M, it) //this line is causing trouble
    { 
        r += it->second; 
    }  
}

我需要输入什么头文件或预处理器命令才能运行。

【问题讨论】:

  • 这不是 C++ 标准中的宏;其他人设计了它,你需要在你的系统上找到相关的标题,或者直接写出代码,或者重新发明那个特定的轮子(看起来有点方,或者可能只是不规则)。
  • 这条线到底造成了什么问题?
  • @UlrichEckhardt:没有可用的函数tr 并且存在语法错误,因为调用后没有分号,也没有it 的声明,因此代码由于多种原因无法编译。
  • 这仍然不是确切错误消息。我的评论是写给作者的,他的帖子缺少任何准确的错误信息,而不是你,乔纳森。

标签: c++ macros stl


【解决方案1】:

不要尝试使用宏,只需正确编写循环即可。在 C++11 中,它几乎和宏一样简单:

for (auto const & pair : M) {
    r += pair.second;
}

从历史上看,它并没有更冗长:

for (map<string, int>::const_iterator it = M.begin(); it != M.end(); ++it) {
    r += it->second;
}

如果您真的想要这样一个邪恶的宏,那么您需要 C++11(或特定于编译器的扩展)来推断迭代器类型;如果你有 C++11,那么只需使用范围样式循环。

【讨论】:

    猜你喜欢
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    相关资源
    最近更新 更多