所以我试图在地图中的向量中删除某个索引元素,而不删除某个索引元素的键。
using dictionary_type = map<unsigned, vector<char>>;
dictionary_type words;
即我正在使用它的地图在书中存储了0行,而char是每个位置的字符。比我拉一个文本文档读取它然后搜索与该文本文档和书籍相似的字符。
for (const auto& pair : words)
{
// run an outer for to search through the message
for (auto c = 0; c < message.size(); ++c )
{
// run and inner for to look at the second element of the map
for (size_t i = 0 ; i < pair.second.size(); ++i)
{
// compare them to see if they're the same
if (pair.second[i] == message[c])
{
out << pair.first << " " << i << " " << endl;
words.erase(pair.second[i]);
// Trying to just delete the character at that index element
// once the character is found break out and search for the next
break;
} // end if
} // end most inner for
} // end second for
// this makes it so the outside for wont repeat
break;
} // end range for
答案 0 :(得分:1)
根据我对你的问题的理解,它归结为:
如何从
vector<char> A
中删除与vector<char> B
中的字符匹配的字符?
新解决方案
在评论澄清之后,我提出了这个新的解决方案。
void removeMessage(dictionary_type& words, vector<char> const& message)
{
for_each(begin(words), end(words), [message](auto& keypair)
{
for(auto const& charIter : message)
{
auto const& findIter = find(begin(keypair.second), end(keypair.second), charIter);
if(findIter != end(keypair.second))
{
keypair.second.erase(findIter);
}
}
});
}
执行以下操作:
message
message
中的每个字符,删除当前条目中该字符的第一个实例。下面显示了一个示例(see it running here)。
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
using dictionary_type = map<unsigned, vector<char>>;
void removeMessage(dictionary_type& words, vector<char> const& message)
{
for_each(begin(words), end(words), [message](auto& keypair)
{
for(auto const& charIter : message)
{
auto const& findIter = find(begin(keypair.second), end(keypair.second), charIter);
if(findIter != end(keypair.second))
{
keypair.second.erase(findIter);
}
}
});
}
void printMessage(vector<char> const& message)
{
for(auto const& iter : message)
{
cout << iter;
}
cout << endl;
}
int main()
{
dictionary_type words;
words.insert(std::make_pair(0, vector<char>{ 't', 'e', 's', 't' }));
words.insert(std::make_pair(1, vector<char>{ 't', 't', 'o', 'o', 'r', 'r', 'n', 'n' }));
printMessage(words[0]);
printMessage(words[1]);
cout << "\nRemoving 'torn'\n" << endl;
removeMessage(words, vector<char>{ 't', 'o', 'r', 'n' });
printMessage(words[0]);
printMessage(words[1]);
return 0;
}
哪个输出
test
ttoorrnn
Removing 'torn'
est
torn
旧解决方案
这是一个解决方案:
void removeMessage(dictionary_type& words, vector<char> const& message)
{
for_each(begin(words), end(words), [&message](auto& keypair)
{
keypair.second.erase(remove_if(begin(keypair.second), end(keypair.second), [&message](auto& charIter) {
return (find(begin(message), end(message), charIter) != end(message));
}), end(keypair.second));
});
}