1

I'm a beginner and getting back to programming after 2 months. Almost forgotten everything. The code I just tried to compile eliminates the second half of the vector usin iterators, if the character I want is found in the first half.

Here's the code:

#include<iostream> #include<string> #include<vector> using namespace std; int main() { vector<string> v; string s("hello world"); char sought = 'e'; v.push_back(s); auto mid = (v.begin() + v.end())/2; if (sought<*mid) { end = mid; } cout<<*v; } 

Please tell me what my mistake is.

Also, can programming be forgotten? Also, once proficient, do the concept stay forever, or does it require constant practice and reading?

7
  • your code is not valid, where is end/it come from? Commented Sep 24, 2013 at 9:22
  • You definitely don't want to add Begin to End. Commented Sep 24, 2013 at 9:23
  • 1
    Plus you never declare it or end. Correct your basic errors before asking about the algorithm. Commented Sep 24, 2013 at 9:24
  • Why not? I realized that, but can I et an explanation please? I'm missing something. Obviously. Commented Sep 24, 2013 at 9:26
  • Please show real code, cout<<*v; this is not valid, sought<*mid won't compile as well. Commented Sep 24, 2013 at 9:28

1 Answer 1

6

First of all, you cannot add iterators together (in v.begin() + v.end()). Instead, use

auto mid = v.begin() + v.size() / 2; 

Secondly, end and it are undeclared.

Finally, you cannot erase part of a vector by assigning to "end". You need to use a different method (left as an exercise).

Sign up to request clarification or add additional context in comments.

6 Comments

Worked! Why does v.size() work, but v.end() doesn't? It was given the same way in the book I'm reading, but had no explanation. I'm clearly missing something silly due to my wrong intuition.
@user2530836: Think about this: What should the type and the value of v.begin() + v.end() be?
I am surprise this works, as sought is char and *mid is std::string.
@NPE, the value will be 11, because that is the number of characters (in the form of a string) present, right? Wouldn't v.begin() + v.size() give the same value?
I realized my mistake. v.end() computes to the element after the last one. Is that right?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.