gpt4 book ai didi

c++ - 多索引插入失败返回( boost )

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:32:38 26 4
gpt4 key购买 nike

我目前正在使用 Boost 的多索引来帮助跟踪数据包通过系统的次数。

每次系统接触数据包时,其 IP 地址都会添加到一个字符串中,以逗号分隔。然后我遍历该字符串,将其标记化并将找到的每个 IP 添加到多索引中。由于 IP 现在设置为唯一,因此不可能将同一个 IP 添加到多重索引中两次。然后应该发生的是与 IP 地址关联的值应该递增,计算数据包通过同一 IP 的次数。

无论如何,我的问题就在这里。当我使用类似 STL map 的东西时,我会得到一个响应,让我知道由于 map 中已经存在重复键而无法添加键。 Boost 的多索引是否提供类似的东西?我知道如果我尝试插入相同的 IP,它会失败,但我怎么知道它失败了?

这是我当前代码的一部分:

// Multi-index handling
using boost::multi_index_container;
using namespace boost::multi_index;

struct pathlog
{
string hop;
int passedthru;

pathlog(std::string hop_,int passedthru_):hop(hop_),passedthru(passedthru_){}

friend std::ostream& operator<<(std::ostream& os,const pathlog& e)
{
os<<e.hop<<" "<<e.passedthru<<std::endl;
return os;
}
};

// structs for data
struct hop{};
struct passedthru{};

// multi-index container setup
typedef multi_index_container<
pathlog,
indexed_by<
ordered_unique<
tag<hop>, BOOST_MULTI_INDEX_MEMBER(pathlog,std::string,hop)>,
ordered_non_unique<
tag<passedthru>, BOOST_MULTI_INDEX_MEMBER(pathlog,int,passedthru)> >
> pathlog_set;


int disassemblepathlog(const string& str, pathlog_set& routecontainer, const string& delimiters = ","){
// Tokenizer (heavily modified) from http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html

// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);

while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
routecontainer.insert(pathlog((str.substr(lastPos, pos - lastPos)),1)); // if this fails, I need to increment the counter!
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}

最佳答案

您对 insert 的调用返回一个 std::pair< iterator, bool >。仅当插入成功时, bool 值才为真。

参见 http://www.boost.org/doc/libs/1_43_0/libs/multi_index/doc/reference/ord_indices.html#modifiers

关于c++ - 多索引插入失败返回( boost ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3129409/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com