C++访问向量的一定范围的索引

C++ access a certain range of indices of a vector

本文关键字:范围 索引 向量 C++ 访问      更新时间:2023-10-16

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

我有一个包含很多单词的字符串向量。假设第一个元素有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)

应避免进行不必要的内存分配。

我只想访问第一个。。

使用std::string::substr是一种方便的方法,但它可能会导致堆分配。因此,如果您需要性能或希望精确地实现您的目标,并且仅访问这些元素,那么您应该使用algorithm:中的std::equal

std::equal(words[0].begin(), words[0].begin()+3,
  "text which is not shorter than 3 elements")

还有一个compare成员函数,如putnampp所示。

"假设第一个元素有5个字母,但我只想访问前3个字母。我该怎么做?!"

您可以应用std::string::substr()函数来引用前3个字母:

if (test_word == words[0].substr(0,3)) {

如果您对std::string特别感兴趣,可以使用substr

if (test_word == words[0].substr(0, 3))

正如@DanielJour在评论中提到的,您也可以使用std::equal

if (std::equal(begin(test_word), begin(test_word) + 3, begin(words[0]))