1 2 3 4 5 6 7 8 9 Next »

Erasing a vector element by key

Create Date: April 08, 2018 at 11:06 AM         Tag: CPLUS         Author Name: Sun, Charles

Erasing a vector element by key

Assuming by specific_key you mean the element at that position in the vector:

my_vector.erase(my_vector.begin() + specific_key);

Would be the "most correct" answer.

If you meant to delete the element that matches specific_key (which will have to be of type vector in the given example:

my_vector.erase(find(my_vector.begin(), my_vector.end(), specific_key));
New Comment

std::sort in C++

Create Date: March 07, 2018 at 12:32 AM         Tag: CPLUS         Author Name: Sun, Charles

std::sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// sort algorithm example
#include      // std::cout
#include     // std::sort
#include        // std::vector

bool myfunction (int i,int j) { return (istruct myclass {
  bool operator() (int i,int j) { return (iint main () {
  int myints[] = {32,71,12,45,26,80,53,33};
  std::vector<int> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33

  // using default comparison (operator <):
  std::sort (myvector.begin(), myvector.begin()+4);           //(12 32 45 71)26 80 53 33

  // using function as comp
  std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

  // using object as comp
  std::sort (myvector.begin(), myvector.end(), myobject);     //(12 26 32 33 45 53 71 80)

  // print out content:
  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

there is an interesting application from leetcode:

class LargestNumber179 {
public:
	string largestNumber(vector& nums) {
		vector arr;
		for (auto i : nums) {
			arr.push_back(to_string(i));
		}
		sort(begin(arr), end(arr), [](string &s1, string &s2) { return s1 + s2 > s2 + s1; });
		string res;
		for (auto s : arr) {
			res += s;
		}
		while (res[0] == '0' && res.size() > 1) {  //both length() and size() are working here
			res.erase(0, 1);
		}
		return res;
	}
};

 

New Comment

Cannot print out result on the console and complex tree structure cannot be asserted in google test in C++

Create Date: February 28, 2018 at 01:02 AM         Tag: CPLUS         Author Name: Sun, Charles

The solution is easy. Just Ctril + F5 to run in the main(), and then rerun it in the google test. 

Not srue why the complex tree strcuture is not valid in the google text. 

for example, the TreeLinkNode doesn’t work.

struct TreeLinkNode {
	int val;
	TreeLinkNode *left, *right, *next;
	TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};

But ListNode works:

struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};
New Comment
1 2 3 4 5 6 7 8 9 Next »