C++访问向量的一定范围的索引
C++ access a certain range of indices of a 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)
应避免进行不必要的内存分配。
我只想访问第一个。。
使用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]))
相关文章:
- 并行用于C++17中数组索引范围内的循环
- C++ - 成功打印超出范围的字符串索引
- 张量不会在超出范围索引时引发异常
- 如何在一定范围内将无锁更新索引设置为最大值
- 为什么 std::string 在索引超出范围时不自动追加(或崩溃)?
- 向量下标出的范围错误.即使向量的索引大于访问数据的索引,也会发生误差
- 打包元组及其索引范围
- 如何在 C++ 的字符串中打印从一个索引到另一个索引的字符范围
- 绑定或色谱柱索引超出范围Sqlite C
- 具有多维数组的索引范围之外的索引是不确定的
- 如何在向量的给定索引范围内查找最小元素
- 如何跳过基于"索引"的基于范围的 for 循环中的元素?
- 阵列索引(转换为整数)用范围枚举
- 为什么在 std::vector 中使用索引超出范围的运算符 [] 时没有出现异常?
- 范围循环中的访问索引
- 使用迭代器的矢量擦除特定索引(不基于范围或条件)
- 在向量的排序向量中查找特定值的索引范围
- 请解释 for 循环索引的范围
- 如何在庞大的二进制数据中快速识别 1(索引)的连续范围
- 字符串下标超出范围.我不知道如何使用字符索引数组,所以我使用了(无符号整数),但它不起作用