gpt4 book ai didi

c++元素在存储在 map 中时丢失

转载 作者:行者123 更新时间:2023-11-28 00:56:52 25 4
gpt4 key购买 nike

我尝试了几天来模拟一个非确定性有限自动机,使用我正在存储状态转换的 map ,完全如本 post 中所示.

问题是它们缺少不确定的转换,即那些通过相同的符号将我引向不同状态的转换。这是我的代码:

#include <iostream>
#include <map>
#include <utility>
#include <iterator> // for ostream_iterator

using namespace std;

int main (){

freopen ("testMap.in", "r", stdin);
int testCases;
int i, j;

int stateOrigin, stateDestination;
char transitionCharacter ;
int numberTransitions=8;

typedef map<pair<int, char>, int> transitions;
transitions trans;

for (j=0; j<numberTransitions;j++){
cin>> stateOrigin>>stateDestination>>transitionCharacter;
trans.insert(transitions::value_type(std::make_pair(stateOrigin,transitionCharacter), stateDestination ));
}

map<pair<int, char>, int>::iterator p = trans.begin();

for( p = trans.begin(); p != trans.end(); p++ ){
cout << p->first.first<< " "<<p->first.second<<" "<<p->second<<endl;
}

return 0;
}

当我打印 map 的全部内容时,这会告诉我:

0 a 0
1 b 1
1 c 2
3 d 4
4 d 4

预期的输出是:

0 0 a
0 1 a
1 1 b
1 2 c
1 3 c
3 4 d
4 4 d
4 5 d

我做错了什么。在另一个问题中,回答说模拟非确定性有限自动机的转换的最佳方法是使用 map,但是使用 map 是否适合此类问题或者可以以任何方式解决?。为什么这些值会丢失?

更改 map 结构方便吗?即:

typedef map<pair<int, int>, char> transitions;

最佳答案

映射是键和值之间的1对1关系,因此它可以表示确定性自动机。

非确定性自动机可以用一对多关联容器表示。

即你需要一个 std::multimap 或者你可以继续使用一个值类型不同的容器的 std::map:

 typedef map<pair<int, int>, vector<char> > transitions;

因此您可以为每个 int 对设置多个 char 值。

关于c++元素在存储在 map 中时丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10613057/

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