Caroline Schuster
Caroline Schuster

Reputation: 43

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

I think I got an easy problem, but I can't find the solution anywhere.

I have a string vector containing a lot of words. say the 1st element has 5 letters, but I only want to access the first 3 letters. how do I do this?!

std::string test_word = "hou";
std::vector<std::string> words = {"house", "apple", "dog", "tree", ...}

if (test_word == /*(words[0].begin(), words[0].begin()+3)*/) {
...
}

what is the correct grammatical way to write it?

EDIT: solution

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) {
      ...
      }
   }
}

Upvotes: 0

Views: 742

Answers (4)

Daniel Jour
Daniel Jour

Reputation: 16156

I only want to access the first ..

Using std::string::substr is a convenient way of doing this, but it might result in a heap allocation. So if you need performance or want to stick exactly to your goal and only access these elements, then you should use std::equal from algorithm:

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

And there is also the compare member function, as putnampp showed.

Upvotes: 2

Cory Kramer
Cory Kramer

Reputation: 117876

If you are specifically interested in a std::string you can use substr

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

As @DanielJour mentioned in the comments, you may also use std::equal

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

Upvotes: 1

putnampp
putnampp

Reputation: 341

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

Should avoid doing unnecessary memory allocations.

Upvotes: 3

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

"say the 1st element has 5 letters, but I only want to access the first 3 letters. how do I do this?!"

You can apply the std::string::substr() function to refer to the first 3 letters:

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

Upvotes: 1

Related Questions