我想我遇到了一个简单的问题,但我无法在任何地方找到解决方案。
我有一个包含很多单词的字符串 vector 。假设第一个元素有 5 个字母,但我只想访问前 3 个字母。我该怎么做?!
std::string test_word = "hou";
std::vector<std::string> words = {"house", "apple", "dog", "tree", ...}
if (test_word == /*(words[0].begin(), words[0].begin()+3)*/) {
...
}
正确的语法写法是什么?
编辑:解决方案
std::string test_word = "hou";
std::vector<std::string> words = {"house", "apple", "dog", "tree", ...}
for (int i = 0; i < words.size(); i++) {
for (int j = 1; j <= words[i].size(); j++) {
if (words[i].compare(0,j, test_word) == 0) {
...
}
}
}
最佳答案
if( words[0].compare(0,3, test_word) == 0)
应避免进行不必要的内存分配。
关于C++访问 vector 的一定范围的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31009574/