C++ 基于整数对返回字符串

标签 c++

我有一个网站列表,例如site1、site2、site3 等(相当长的一个)映射到我的程序从远程客户端接收的一对个位数整数,并且我需要一种有效的方法来返回(作为字符串)站点基于这对整数的名称。第一个数字本身很重要,第二个数字不重要,除非与第一个数字配对。这些“站点代码”应各自返回一个唯一的字符串。

这是我目前的做法:

#include<string>
#include<iostream>
#include<vector>

// sbits is a vector of integers from which these two integers are being pulled
std::string readSite( vector<int> sbits ) {
    int rgcode = sbits[5];
    int uid = sbits[6];
    if ( rgcode == 0 ) {
        if ( uid == 0 ) {
            return "site1";
        }
        else if ( uid == 1 ) {
            return "site2";
        }
        else if ( uid == 2 ) {
            return "site3";
        }
        // throw an exception if it's  not here
        else {
             std::throw 10;
        }
    }
    else if ( rgcode == 1 ) {
        if ( uid == 0 ) {
            return "site4";
        else if ( uid == 1 ) {
            return "site5";
        else {
            std::throw 10;
        }
    }
    else {
        std::throw 5;
    }
    std::catch( int err ) {
        std::cout << "An exception has occurred. Error "<< err << " closing." << std::endl;
        exit;
    }
}

这一切都让我内心有些崩溃。写起来很累,读起来也很累,而且对于我需要做的事情来说可能不是最佳的。

所以我的问题是:是否有更优雅(并且更少自杀)的方法来做到这一点? 我一直在阅读有关 std::enum、std::map 的内容,但它们似乎不适合我在这里尝试做的事情。

编辑:有没有办法使用网站的某种有序列表来做到这一点?这样我就不必遍历并编写同一行的 70 多个变体。某种方式来迭代每个?也许?

最佳答案

您需要正确定义数据结构以简化您的代码:

typedef std::pair<int, int> RgCodeUidPair;
//               rgcode, uid

然后您可以使用(rgcode, uid)作为对来搜索cachedData映射。

std::string readSite( int rgcode, int uid)
{ 
   static std::map<RgCodeUidPair, std::string> cachedData; // cache data, only load once
   if (cachedData.empty())
   {
     cachedData.insert(make_pair(make_pair(0, 0), "site1"));
     cachedData.insert(make_pair(make_pair(0, 1), "site2"));
     cachedData.insert(make_pair(make_pair(1, 0), "site3"));
     cachedData.insert(make_pair(make_pair(1, 1), "site4"));
   }

   auto it = cachedData.find(make_pair(rgcode, uid));
   if (it != cachedData.end())
   {
      return it->second;
   }
   // throw if not found
}

关于C++ 基于整数对返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24666521/

相关文章:

c++ - 永远不会调用全局 CBT Hook

c++ - 在具有属性的 vector 中查找元素

c++ - 如何在 XCode 4 中将旧式构建日志设置为默认构建错误 View

c++ - 装饰者模式 vs. 调用 super 反模式

c++ - 使用外部SDK工具链文件的VisualStudio上的CMake项目编译错误

c++ - 垂直转动相机(使用角度轴旋转)

c++ - 在 OpenGL4 中绘制两个对象?

c++ - 将元素插入左倾的黑红树c++

c++ - 无法编译 boost::logger

c++ - 当我们在 for 循环条件中使用 cin 时发生了什么?