C++访问 vector 的一定范围的索引

标签 c++ string vector

我想我遇到了一个简单的问题,但我无法在任何地方找到解决方案。

我有一个包含很多单词的字符串 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/

相关文章:

C++ vector 读取访问冲突 Mylast 返回 0x8

c++ - Irrlicht 正在错误路径中查找文件

c++ - 如何在 CMakeLists.txt 中包含 h/hpp 头文件而不是 cpp 或其他 hpp 文件

c++ - 读取文件时进入无限循环

c# - 检查字符串是否包含通用列表中的值并替换它

c++ - 如何访问 std::vector 的内部连续缓冲区,我可以将它与 memcpy 等一起使用吗?

C++ 在范围结束前删除函数指针

c++ - 用一个空格替换字符串中的多个空格

java - 字符串操作模式

C++ 语法错误